Java Code Examples for javax.servlet.FilterRegistration.Dynamic#addMappingForUrlPatterns()

The following examples show how to use javax.servlet.FilterRegistration.Dynamic#addMappingForUrlPatterns() . 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: Initializer.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    super.onStartup(servletContext);

    Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());

    configureSessionCookie(servletContext);
    
    CharacterEncodingFilter cef = new CharacterEncodingFilter();
    cef.setEncoding("UTF-8");
    cef.setForceEncoding(true);
    
    Dynamic characterEncodingFilter = servletContext.addFilter("CharacterEncodingFilter", cef);
    characterEncodingFilter.setAsyncSupported(true);
    characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*");

    //force log initialization, then disable it
    XRLog.setLevel(XRLog.EXCEPTION, Level.WARNING);
    XRLog.setLoggingEnabled(false);

}
 
Example 2
Source File: ITSpanCustomizingAsyncHandlerInterceptor.java    From brave with Apache License 2.0 6 votes vote down vote up
@Override public void init(ServletContextHandler handler) {
  AnnotationConfigWebApplicationContext appContext =
    new AnnotationConfigWebApplicationContext() {
      // overriding this allows us to register dependencies of TracingHandlerInterceptor
      // without passing static state to a configuration class.
      @Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
        beanFactory.registerSingleton("httpTracing", httpTracing);
        super.loadBeanDefinitions(beanFactory);
      }
    };

  appContext.register(Servlet3TestController.class); // the test resource
  appContext.register(TracingConfig.class); // generic tracing setup
  DispatcherServlet servlet = new DispatcherServlet(appContext);
  servlet.setDispatchOptionsRequest(true);
  ServletHolder servletHolder = new ServletHolder(servlet);
  servletHolder.setAsyncSupported(true);
  handler.addServlet(servletHolder, "/*");
  handler.addEventListener(new ContextLoaderListener(appContext));

  // add the trace filter, which lazy initializes a real tracing filter from the spring context
  Dynamic filterRegistration =
    handler.getServletContext().addFilter("tracingFilter", DelegatingTracingFilter.class);
  filterRegistration.setAsyncSupported(true);
  filterRegistration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
 
Example 3
Source File: SessionHelpers.java    From HttpSessionReplacer with MIT License 5 votes vote down vote up
/**
 * Sets up servlet context - registers {@link SessionFilter} and {@link ShutdownListener}.
 *
 * @param context
 *          servlet context to set up
 */
static void setupContext(ServletContext context) {
  if (ServletLevel.isServlet3) {
    // When using Servlet 3.x+, we will register SessionFilter to make
    // sure session replacement is enabled
    Dynamic reg = context.addFilter("com.amdeus.session.filter", new SessionFilter());
    if (reg != null) {
      // The filter applies to all requests
      reg.addMappingForUrlPatterns(null, false, "/*");
    }
    // At the web app shutdown, we need to do some cleanup
    context.addListener(new ShutdownListener());
  }
}
 
Example 4
Source File: OpenTracingInitializer.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    ServletContext servletContext = servletContextEvent.getServletContext();

    String skipPatternAttribute = servletContext.getInitParameter(TracingFilter.SKIP_PATTERN);
    if (null != skipPatternAttribute && !skipPatternAttribute.isEmpty()) {
        servletContext.setAttribute(TracingFilter.SKIP_PATTERN, Pattern.compile(skipPatternAttribute));
    }

    logger.info("Registering Tracing Filter");
    Dynamic filterRegistration = servletContext
        .addFilter("tracingFilter", new TracingFilter());
    filterRegistration.setAsyncSupported(true);
    filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "*");
}
 
Example 5
Source File: OpenTracingContextInitializer.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
  ServletContext servletContext = servletContextEvent.getServletContext();
  Dynamic filterRegistration = servletContext
      .addFilter("tracingFilter", new SpanFinishingFilter());
  filterRegistration.setAsyncSupported(true);
  filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "*");
}
 
Example 6
Source File: FilterConfigurer.java    From micro-server with Apache License 2.0 5 votes vote down vote up
private void addExplicitlyDeclaredFilters(ServletContext webappContext) {
	for (FilterData filterData : filterData) {
		Dynamic filterReg = webappContext.addFilter(
				filterData.getFilterName(), filterData.getFilter());
		
		filterReg.addMappingForUrlPatterns(
				EnumSet.allOf(DispatcherType.class),true,
				filterData.getMapping());
		logFilter(filterData);
	}
}
 
Example 7
Source File: Initializer.java    From spring-session with Apache License 2.0 5 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
	this.instance = createHazelcastInstance();
	Map<String, Session> sessions = this.instance.getMap(SESSION_MAP_NAME);

	MapSessionRepository sessionRepository = new MapSessionRepository(sessions);
	SessionRepositoryFilter<? extends Session> filter = new SessionRepositoryFilter<>(sessionRepository);

	Dynamic fr = sce.getServletContext().addFilter("springSessionFilter", filter);
	fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
}
 
Example 8
Source File: AbstractHttpSessionApplicationInitializer.java    From spring-session with Apache License 2.0 5 votes vote down vote up
/**
 * Registers the provided filter using the {@link #isAsyncSessionSupported()} and
 * {@link #getSessionDispatcherTypes()}.
 * @param servletContext the servlet context
 * @param insertBeforeOtherFilters should this Filter be inserted before or after
 * other {@link Filter}
 * @param filterName the filter name
 * @param filter the filter
 */
private void registerFilter(ServletContext servletContext, boolean insertBeforeOtherFilters, String filterName,
		Filter filter) {
	Dynamic registration = servletContext.addFilter(filterName, filter);
	if (registration == null) {
		throw new IllegalStateException("Duplicate Filter registration for '" + filterName
				+ "'. Check to ensure the Filter is only configured once.");
	}
	registration.setAsyncSupported(isAsyncSessionSupported());
	EnumSet<DispatcherType> dispatcherTypes = getSessionDispatcherTypes();
	registration.addMappingForUrlPatterns(dispatcherTypes, !insertBeforeOtherFilters, "/*");
}
 
Example 9
Source File: NewtsService.java    From newts with Apache License 2.0 5 votes vote down vote up
private void configureCors(Environment environment) {
    Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class);
    filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
    filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
    filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
    filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
    filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
    filter.setInitParameter("allowCredentials", "true");
}
 
Example 10
Source File: WebAppSecurityInitializer.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
  // add filters
  Dynamic forwardedHeaderFilter =
      servletContext.addFilter("forwardedHeaderFilter", ForwardedHeaderFilter.class);
  forwardedHeaderFilter.setAsyncSupported(true);
  forwardedHeaderFilter.addMappingForUrlPatterns(EnumSet.of(REQUEST, ERROR, ASYNC), false, "*");
}
 
Example 11
Source File: MainWebAppInitializer.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * Register and configure all Servlet container components necessary to power the web application.
 */
@Override
public void onStartup(final ServletContext sc) throws ServletException {
    System.out.println("MyWebAppInitializer.onStartup()");

    // Create the 'root' Spring application context
    final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
    root.scan("com.baeldung.config.parent");
    // root.getEnvironment().setDefaultProfiles("embedded");

    // Manages the lifecycle of the root application context
    sc.addListener(new ContextLoaderListener(root));

    // Handles requests into the application
    final AnnotationConfigWebApplicationContext childWebApplicationContext = new AnnotationConfigWebApplicationContext();
    childWebApplicationContext.scan("com.baeldung.config.child");
    final ServletRegistration.Dynamic appServlet = sc.addServlet("api", new DispatcherServlet(childWebApplicationContext));
    appServlet.setLoadOnStartup(1);
    final Set<String> mappingConflicts = appServlet.addMapping("/");
    if (!mappingConflicts.isEmpty()) {
        throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
    }

    // spring security filter
    final DelegatingFilterProxy springSecurityFilterChain = new DelegatingFilterProxy("springSecurityFilterChain");
    final Dynamic addedFilter = sc.addFilter("springSecurityFilterChain", springSecurityFilterChain);
    addedFilter.addMappingForUrlPatterns(null, false, "/*");
}
 
Example 12
Source File: ITTracingFilter.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public void init(ServletContextHandler handler) {
  handler.getServletContext()
    .addFilter("tracingFilter", TracingFilter.create(httpTracing))
    .addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");

  Dynamic sparkFilter = handler.getServletContext().addFilter("sparkFilter", new SparkFilter());
  sparkFilter.setInitParameter("applicationClass", TestApplication.class.getName());
  sparkFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
 
Example 13
Source File: ITSpanCustomizingApplicationEventListener.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public void init(ServletContextHandler handler) {
  ResourceConfig config = new ResourceConfig();
  config.register(new TestResource(httpTracing));
  config.register(SpanCustomizingApplicationEventListener.create());
  handler.addServlet(new ServletHolder(new ServletContainer(config)), "/*");

  // add the underlying servlet tracing filter which the event listener decorates with more tags
  Dynamic filterRegistration =
    handler.getServletContext().addFilter("tracingFilter", TracingFilter.create(httpTracing));
  filterRegistration.setAsyncSupported(true);
  // isMatchAfter=true is required for async tests to pass!
  filterRegistration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
 
Example 14
Source File: MolgenisWebAppInitializer.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
/** A Molgenis common web application initializer */
protected void onStartup(ServletContext servletContext, Class<?> appConfig, int maxFileSize) {
  // Create the 'root' Spring application context
  AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
  rootContext.registerShutdownHook();
  rootContext.setAllowBeanDefinitionOverriding(false);
  rootContext.register(appConfig);

  // Manage the lifecycle of the root application context
  servletContext.addListener(new ContextLoaderListener(rootContext));

  // Register and map the dispatcher servlet
  DispatcherServlet dispatcherServlet = new DispatcherServlet(rootContext);
  dispatcherServlet.setDispatchOptionsRequest(true);
  // instead of throwing a 404 when a handler is not found allow for custom handling
  dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);

  ServletRegistration.Dynamic dispatcherServletRegistration =
      servletContext.addServlet("dispatcher", dispatcherServlet);
  if (dispatcherServletRegistration == null) {
    LOG.warn(
        "ServletContext already contains a complete ServletRegistration for servlet 'dispatcher'");
  } else {
    final long maxSize = (long) maxFileSize * MB;
    dispatcherServletRegistration.addMapping("/");
    dispatcherServletRegistration.setMultipartConfig(
        new MultipartConfigElement(null, maxSize, maxSize, FILE_SIZE_THRESHOLD));
    dispatcherServletRegistration.setAsyncSupported(true);
  }

  // Add filters
  Dynamic browserDetectionFiler =
      servletContext.addFilter("browserDetectionFilter", BrowserDetectionFilter.class);
  browserDetectionFiler.setAsyncSupported(true);
  browserDetectionFiler.addMappingForUrlPatterns(
      EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC), false, "*");

  Dynamic etagFilter = servletContext.addFilter("etagFilter", ShallowEtagHeaderFilter.class);
  etagFilter.setAsyncSupported(true);
  etagFilter.addMappingForServletNames(
      EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC), true, "dispatcher");

  // enable use of request scoped beans in FrontController
  servletContext.addListener(new RequestContextListener());

  servletContext.addListener(HttpSessionEventPublisher.class);
}