javax.servlet.FilterRegistration Java Examples
The following examples show how to use
javax.servlet.FilterRegistration.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FoxtrotServer.java From foxtrot with Apache License 2.0 | 6 votes |
@Override public void run(FoxtrotServerConfiguration configuration, Environment environment) throws Exception { // Enable CORS headers final FilterRegistration.Dynamic cors = environment.servlets() .addFilter("CORS", CrossOriginFilter.class); // Configure CORS parameters cors.setInitParameter("allowedOrigins", "*"); cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin"); cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD"); // Add URL mapping cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); ((AbstractServerFactory)configuration.getServerFactory()).setJerseyRootPath("/foxtrot"); MetricUtil.setup(environment.metrics()); ElasticsearchUtils.setTableNamePrefix(configuration.getElasticsearch()); }
Example #2
Source File: CamundaBpmRestInitializer.java From camunda-bpm-platform with Apache License 2.0 | 6 votes |
private FilterRegistration registerFilter(final String filterName, final Class<? extends Filter> filterClass, final Map<String, String> initParameters, final String... urlPatterns) { FilterRegistration filterRegistration = servletContext.getFilterRegistration(filterName); if (filterRegistration == null) { filterRegistration = servletContext.addFilter(filterName, filterClass); filterRegistration.addMappingForUrlPatterns(DISPATCHER_TYPES, true, urlPatterns); if (initParameters != null) { filterRegistration.setInitParameters(initParameters); } log.debug("Filter {} for URL {} registered.", filterName, urlPatterns); } return filterRegistration; }
Example #3
Source File: CORSContextListener.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 6 votes |
/** * Initializes CORS filter */ private void initCORS(ServletContext servletContext) { WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext); Properties gP = (Properties) wc.getBean(BEAN_GLOBAL_PROPERTIES); Boolean corsEnabled = new Boolean(gP.getProperty(CORS_ENABLED)); if(logger.isDebugEnabled()) { logger.debug("CORS filter is" + (corsEnabled?" ":" not ") + "enabled"); } if (corsEnabled) { FilterRegistration.Dynamic corsFilter = servletContext.addFilter("CorsFilter", "org.apache.catalina.filters.CorsFilter"); corsFilter.setInitParameter(CORS_ALLOWED_ORIGINS, gP.getProperty(CORS_ALLOWED_ORIGINS)); corsFilter.setInitParameter(CORS_ALLOWED_METHODS, gP.getProperty(CORS_ALLOWED_METHODS)); corsFilter.setInitParameter(CORS_ALLOWED_HEADERS, gP.getProperty(CORS_ALLOWED_HEADERS)); corsFilter.setInitParameter(CORS_EXPOSED_HEADERS, gP.getProperty(CORS_EXPOSED_HEADERS)); corsFilter.setInitParameter(CORS_SUPPORT_CREDENTIALS, gP.getProperty(CORS_SUPPORT_CREDENTIALS)); corsFilter.setInitParameter(CORS_PREFLIGHT_CREDENTIALS, gP.getProperty(CORS_PREFLIGHT_CREDENTIALS)); corsFilter.addMappingForUrlPatterns(DISPATCHER_TYPE, false, "/*"); } }
Example #4
Source File: AbstractDispatcherServletInitializer.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Add the given filter to the ServletContext and map it to the * {@code DispatcherServlet} as follows: * <ul> * <li>a default filter name is chosen based on its concrete type * <li>the {@code asyncSupported} flag is set depending on the * return value of {@link #isAsyncSupported() asyncSupported} * <li>a filter mapping is created with dispatcher types {@code REQUEST}, * {@code FORWARD}, {@code INCLUDE}, and conditionally {@code ASYNC} depending * on the return value of {@link #isAsyncSupported() asyncSupported} * </ul> * <p>If the above defaults are not suitable or insufficient, override this * method and register filters directly with the {@code ServletContext}. * @param servletContext the servlet context to register filters with * @param filter the filter to be registered * @return the filter registration */ protected FilterRegistration.Dynamic registerServletFilter(ServletContext servletContext, Filter filter) { String filterName = Conventions.getVariableName(filter); Dynamic registration = servletContext.addFilter(filterName, filter); if (registration == null) { int counter = -1; while (counter == -1 || registration == null) { counter++; registration = servletContext.addFilter(filterName + "#" + counter, filter); Assert.isTrue(counter < 100, "Failed to register filter '" + filter + "'." + "Could the same Filter instance have been registered already?"); } } registration.setAsyncSupported(isAsyncSupported()); registration.addMappingForServletNames(getDispatcherTypes(), false, getServletName()); return registration; }
Example #5
Source File: SparkLambdaContainerHandler.java From aws-serverless-java-container with Apache License 2.0 | 6 votes |
@Override public void initialize() throws ContainerInitializationException { Timer.start("SPARK_COLD_START"); log.debug("First request, getting new server instance"); // trying to call init in case the embedded server had not been initialized. Spark.init(); // adding this call to make sure that the framework is fully initialized. This should address a race // condition and solve GitHub issue #71. Spark.awaitInitialization(); embeddedServer = lambdaServerFactory.getServerInstance(); // manually add the spark filter to the chain. This should the last one and match all uris FilterRegistration.Dynamic sparkRegistration = getServletContext().addFilter("SparkFilter", embeddedServer.getSparkFilter()); sparkRegistration.addMappingForUrlPatterns( EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC, DispatcherType.INCLUDE, DispatcherType.FORWARD), true, "/*"); Timer.stop("SPARK_COLD_START"); }
Example #6
Source File: WebFilterInstaller.java From dropwizard-guicey with MIT License | 6 votes |
private void configure(final ServletEnvironment environment, final Filter filter, final String name, final WebFilter annotation) { final FilterRegistration.Dynamic mapping = environment.addFilter(name, filter); final EnumSet<DispatcherType> dispatcherTypes = EnumSet.copyOf(Arrays.asList(annotation.dispatcherTypes())); if (annotation.servletNames().length > 0) { mapping.addMappingForServletNames(dispatcherTypes, false, annotation.servletNames()); } else { final String[] urlPatterns = annotation.urlPatterns().length > 0 ? annotation.urlPatterns() : annotation.value(); mapping.addMappingForUrlPatterns(dispatcherTypes, false, urlPatterns); } if (annotation.initParams().length > 0) { for (WebInitParam param : annotation.initParams()) { mapping.setInitParameter(param.name(), param.value()); } } mapping.setAsyncSupported(annotation.asyncSupported()); }
Example #7
Source File: SpringWebinitializer.java From Spring-5.0-Cookbook with MIT License | 6 votes |
private void addDispatcherContext(ServletContext container) { // Create the dispatcher servlet's Spring application context AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); dispatcherContext.register(SpringDispatcherConfig.class); // Declare <servlet> and <servlet-mapping> for the DispatcherServlet ServletRegistration.Dynamic dispatcher = container.addServlet("ch03-servlet", new DispatcherServlet(dispatcherContext)); dispatcher.addMapping("*.html"); dispatcher.setLoadOnStartup(1); FilterRegistration.Dynamic corsFilter = container.addFilter("corsFilter", new CorsFilter()); corsFilter.setInitParameter("cors.allowed.methods", "GET, POST, HEAD, OPTIONS, PUT, DELETE"); corsFilter.addMappingForUrlPatterns(null, true, "/*"); FilterRegistration.Dynamic filter = container.addFilter("hiddenmethodfilter", new HiddenHttpMethodFilter()); filter.addMappingForServletNames(null, true, "/*"); FilterRegistration.Dynamic multipartFilter = container.addFilter("multipartFilter", new MultipartFilter()); multipartFilter.addMappingForUrlPatterns(null, true, "/*"); }
Example #8
Source File: FilterRegistrationTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Test getUrlPatternMappings method. */ @Test public void testGetUrlPatternMappings() { webApp.addFilter("filter", TestFilterRegistrationFilter.class); FilterRegistration registration = webApp.getFilterRegistration("filter"); assertTrue(registration.getUrlPatternMappings().isEmpty()); }
Example #9
Source File: FilterRegistrationTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Test getName method. */ @Test public void testGetName() { webApp.addFilter("filter", TestFilterRegistrationFilter.class); FilterRegistration registration = webApp.getFilterRegistration("filter"); assertEquals(registration.getName(), "filter"); }
Example #10
Source File: ApplicationContextFacade.java From tomcatsrc with Apache License 2.0 | 5 votes |
@Override public FilterRegistration.Dynamic addFilter(String filterName, String className) { if (SecurityUtil.isPackageProtectionEnabled()) { return (FilterRegistration.Dynamic) doPrivileged( "addFilter", new Object[]{filterName, className}); } else { return context.addFilter(filterName, className); } }
Example #11
Source File: ApplicationContextFacade.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Override @SuppressWarnings("unchecked") // doPrivileged() returns the correct type public Map<String, ? extends FilterRegistration> getFilterRegistrations() { if (SecurityUtil.isPackageProtectionEnabled()) { return (Map<String, ? extends FilterRegistration>) doPrivileged( "getFilterRegistrations", null); } else { return context.getFilterRegistrations(); } }
Example #12
Source File: WebConfigurer.java From flowable-engine with Apache License 2.0 | 5 votes |
/** * Initializes Spring Security. */ private void initSpringSecurity(ServletContext servletContext, EnumSet<DispatcherType> disps) { LOGGER.debug("Registering Spring Security Filter"); FilterRegistration.Dynamic springSecurityFilter = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy()); springSecurityFilter.addMappingForUrlPatterns(disps, false, "/*"); }
Example #13
Source File: SparkLambdaContainerHandlerTest.java From aws-serverless-java-container with Apache License 2.0 | 5 votes |
@Test public void filters_onStartupMethod_executeFilters() { SparkLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler = null; try { handler = SparkLambdaContainerHandler.getAwsProxyHandler(); } catch (ContainerInitializationException e) { e.printStackTrace(); fail(); } handler.onStartup(c -> { if (c == null) { fail(); } FilterRegistration.Dynamic registration = c.addFilter("CustomHeaderFilter", CustomHeaderFilter.class); // update the registration to map to a path registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*"); // servlet name mappings are disabled and will throw an exception }); configureRoutes(); Spark.awaitInitialization(); AwsProxyRequest req = new AwsProxyRequestBuilder().method("GET").path("/header-filter").build(); AwsProxyResponse response = handler.proxy(req, new MockLambdaContext()); assertNotNull(response); assertEquals(200, response.getStatusCode()); assertTrue(response.getMultiValueHeaders().containsKey(CustomHeaderFilter.HEADER_NAME)); assertEquals(CustomHeaderFilter.HEADER_VALUE, response.getMultiValueHeaders().getFirst(CustomHeaderFilter.HEADER_NAME)); assertEquals(RESPONSE_BODY_TEXT, response.getBody()); }
Example #14
Source File: Bootstrap.java From quarkus-http with Apache License 2.0 | 5 votes |
@Override public void contextInitialized(ServletContextEvent sce) { container = (ServerWebSocketContainer) sce.getServletContext().getAttribute(ServerContainer.class.getName()); FilterRegistration.Dynamic filter = sce.getServletContext().addFilter(FILTER_NAME, JsrWebSocketFilter.class); sce.getServletContext().addListener(JsrWebSocketFilter.LogoutListener.class); filter.setAsyncSupported(true); if(!container.getConfiguredServerEndpoints().isEmpty()){ filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*"); } else { container.setContextToAddFilter((ServletContextImpl) sce.getServletContext()); } }
Example #15
Source File: ApplicationInitializer.java From AIDR with GNU Affero General Public License v3.0 | 5 votes |
@Override public void onStartup(ServletContext servletContext) throws ServletException { /* Setting the configuration classes */ AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext(); context.setConfigLocation("qa.qcri.aidr.data.config"); /*Configuring error handler filter for errors out isde the controllers FilterRegistration.Dynamic errorHandlerFilter = servletContext.addFilter("errorHandlerFilter", new ErrorHandlerFilter()); errorHandlerFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); */ FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encodingFilter", new org.springframework.web.filter.CharacterEncodingFilter()); encodingFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); encodingFilter.setInitParameter("encoding", "UTF-8"); encodingFilter.setInitParameter("forceEncoding", "true"); /* Adding context listener */ servletContext.addListener(new ContextLoaderListener(context)); /* Adding request listener */ servletContext.addListener(new RequestContextListener()); /* Configuring dispatcher servlet for spring mvc */ /*CustomDispatcherServlet servlet = new CustomDispatcherServlet(context); */ ServletRegistration.Dynamic appServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context)); appServlet.setLoadOnStartup(1); appServlet.addMapping("/*"); }
Example #16
Source File: ApplicationContextFacade.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Override public FilterRegistration.Dynamic addFilter(String filterName, String className) { if (SecurityUtil.isPackageProtectionEnabled()) { return (FilterRegistration.Dynamic) doPrivileged( "addFilter", new Object[]{filterName, className}); } else { return context.addFilter(filterName, className); } }
Example #17
Source File: PippoFilter.java From pippo with Apache License 2.0 | 5 votes |
private void initFilterPathFromWebXml(FilterConfig filterConfig) { String filterName = filterConfig.getFilterName(); FilterRegistration filterRegistration = filterConfig.getServletContext().getFilterRegistration(filterName); Collection<String> mappings = filterRegistration.getUrlPatternMappings(); int size = mappings.size(); if (size > 1) { throw new PippoRuntimeException("Expected one filter path for '{}' but found multiple", filterName); } if (size == 1) { String urlPattern = mappings.iterator().next(); initFilterPath(urlPattern); } }
Example #18
Source File: ServletContextSimulator.java From birt with Eclipse Public License 1.0 | 5 votes |
@Override public javax.servlet.FilterRegistration.Dynamic addFilter( String filterName, Class<? extends Filter> filterClass ) { // TODO Auto-generated method stub return null; }
Example #19
Source File: FilterRegistrationTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Test setInitParameters method. */ @Test public void testSetInitParameters() { webApp.addFilter("filter", TestFilterRegistrationFilter.class); FilterRegistration registration = webApp.getFilterRegistration("filter"); registration.setInitParameter("name", "value"); assertTrue(registration.setInitParameters(new HashMap<>()).isEmpty()); }
Example #20
Source File: TracingConfiguration.java From hola with Apache License 2.0 | 5 votes |
@Override public void contextInitialized(ServletContextEvent sce) { FilterRegistration.Dynamic filterRegistration = sce.getServletContext() .addFilter("BraveServletFilter", new TracingFilter(tracer)); // Explicit mapping to avoid trace on readiness probe filterRegistration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/api/hola", "/api/hola-chaining"); }
Example #21
Source File: WebConfigurer.java From flowable-engine with Apache License 2.0 | 5 votes |
/** * Initializes Spring Security. */ private void initSpringSecurity(ServletContext servletContext, EnumSet<DispatcherType> disps) { LOGGER.debug("Registering Spring Security Filter"); FilterRegistration.Dynamic springSecurityFilter = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy()); springSecurityFilter.addMappingForUrlPatterns(disps, false, "/*"); }
Example #22
Source File: ApplicationContext.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
@Override public FilterRegistration getFilterRegistration(String filterName) { FilterDef filterDef = context.findFilterDef(filterName); if (filterDef == null) { return null; } return new ApplicationFilterRegistration(filterDef, context); }
Example #23
Source File: RegistryApplication.java From registry with Apache License 2.0 | 5 votes |
private void enableCORS(Environment environment) { // Enable CORS headers final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); // Configure CORS parameters cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*"); cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Authorization,Content-Type,Accept,Origin"); cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "OPTIONS,GET,PUT,POST,DELETE,HEAD"); // Add URL mapping cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*"); }
Example #24
Source File: JPAWebConfigurer.java From activiti6-boot2 with Apache License 2.0 | 5 votes |
/** * Initializes Spring Security. */ private void initSpringSecurity(ServletContext servletContext, EnumSet<DispatcherType> disps) { log.debug("Registering Spring Security Filter"); FilterRegistration.Dynamic springSecurityFilter = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy()); springSecurityFilter.addMappingForUrlPatterns(disps, false, "/*"); }
Example #25
Source File: WebConfigurer.java From activiti6-boot2 with Apache License 2.0 | 5 votes |
/** * Initializes Spring Security. */ private void initSpringSecurity(ServletContext servletContext, EnumSet<DispatcherType> disps) { log.debug("Registering Spring Security Filter"); FilterRegistration.Dynamic springSecurityFilter = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy()); springSecurityFilter.addMappingForUrlPatterns(disps, false, "/*"); springSecurityFilter.setAsyncSupported(true); }
Example #26
Source File: FilterRegistrationTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Test setInitParameters method. */ @Test public void testSetInitParameters5() { webApp.addFilter("filter", TestFilterRegistrationFilter.class); FilterRegistration registration = webApp.getFilterRegistration("filter"); HashMap<String, String> parameters = new HashMap<>(); parameters.put("name", "value"); assertTrue(registration.setInitParameters(parameters).isEmpty()); assertFalse(registration.setInitParameters(parameters).isEmpty()); }
Example #27
Source File: WebInitializer.java From audit4j-demo with Apache License 2.0 | 5 votes |
public void onStartup(ServletContext servletContext) { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.setConfigLocation("org.audt4j.demo.hibernate.config"); servletContext.addListener(new ContextLoaderListener(ctx)); ctx.setServletContext(servletContext); Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); servlet.addMapping("/*"); servlet.setLoadOnStartup(1); FilterRegistration.Dynamic springSecurityFilterChain = servletContext .addFilter("springSecurityFilterChain", new DelegatingFilterProxy()); springSecurityFilterChain.addMappingForUrlPatterns(null, false, "/*"); springSecurityFilterChain.setAsyncSupported(true); }
Example #28
Source File: WebConfigurer.java From albedo with GNU Lesser General Public License v3.0 | 5 votes |
/** * Initializes the caching HTTP Headers Filter. */ private void initCachingHttpHeadersFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) { log.debug("Registering Caching HTTP Headers Filter"); FilterRegistration.Dynamic cachingHttpHeadersFilter = servletContext.addFilter("cachingHttpHeadersFilter", new CachingHttpHeadersFilter(applicationProperties)); cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/statics/*", "/WEB-INF/views/*"); cachingHttpHeadersFilter.setAsyncSupported(true); }
Example #29
Source File: WebConfigurerTest.java From albedo with GNU Lesser General Public License v3.0 | 5 votes |
@BeforeEach public void setup() { servletContext = spy(new MockServletContext()); doReturn(mock(FilterRegistration.Dynamic.class)) .when(servletContext).addFilter(anyString(), any(Filter.class)); doReturn(mock(ServletRegistration.Dynamic.class)) .when(servletContext).addServlet(anyString(), any(Servlet.class)); env = new MockEnvironment(); props = new ApplicationProperties(); webConfigurer = new WebConfigurer(env, props); }
Example #30
Source File: Log4jServletContainerInitializer.java From logging-log4j2 with Apache License 2.0 | 5 votes |
@Override public void onStartup(final Set<Class<?>> classes, final ServletContext servletContext) throws ServletException { if (servletContext.getMajorVersion() > 2 && servletContext.getEffectiveMajorVersion() > 2 && !"true".equalsIgnoreCase(servletContext.getInitParameter( Log4jWebSupport.IS_LOG4J_AUTO_INITIALIZATION_DISABLED ))) { final Logger LOGGER = StatusLogger.getLogger(); LOGGER.debug("Log4jServletContainerInitializer starting up Log4j in Servlet 3.0+ environment."); final FilterRegistration.Dynamic filter = servletContext.addFilter("log4jServletFilter", Log4jServletFilter.class); if (filter == null) { LOGGER.warn("WARNING: In a Servlet 3.0+ application, you should not define a " + "log4jServletFilter in web.xml. Log4j 2 normally does this for you automatically. Log4j 2 " + "web auto-initialization has been canceled."); return; } final Log4jWebLifeCycle initializer = WebLoggerContextUtils.getWebLifeCycle(servletContext); initializer.start(); initializer.setLoggerContext(); // the application is just now starting to start up servletContext.addListener(new Log4jServletContextListener()); filter.setAsyncSupported(true); // supporting async when the user isn't using async has no downsides filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*"); } }