Java Code Examples for javax.servlet.ServletContext#addFilter()

The following examples show how to use javax.servlet.ServletContext#addFilter() . 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: SpringWebinitializer.java    From Spring-5.0-Cookbook with MIT License 6 votes vote down vote up
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 3
Source File: AbstractDispatcherServletInitializer.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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 = 0;
		while (registration == null) {
			if (counter == 100) {
				throw new IllegalStateException("Failed to register filter with name '" + filterName + "'. " +
						"Check if there is another filter registered under the same name.");
			}
			registration = servletContext.addFilter(filterName + "#" + counter, filter);
			counter++;
		}
	}

	registration.setAsyncSupported(isAsyncSupported());
	registration.addMappingForServletNames(getDispatcherTypes(), false, getServletName());
	return registration;
}
 
Example 4
Source File: CORSContextListener.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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 5
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 6
Source File: AuthenticationInitializer.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Initialize Eleos
 * 
 * @param classes the classes.
 * @param servletContext the Servlet context.
 * @throws ServletException when a Servlet error occurs.
 */
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
    
    // Gets the authentication module class that was configured externally
    Class<?> authModuleClass = (Class<?>) servletContext.getAttribute(AUTH_MODULE_CLASS);
    if (authModuleClass == null) {
        authModuleClass = DoNothingServerAuthModule.class;
    }
    
    String appContextId = servletContext.getVirtualServerName() + " " + servletContext.getContextPath();
    
    // This sets the authentication factory to the default factory. This factory stores and retrieves
    // the authentication artifacts.
    Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, DefaultConfigFactory.class.getName());
    
    // Defines the modules that we have available. Here it's only a single fixed module.
    ConfigParser configParser = new DefaultConfigParser(authModuleClass);
    
    // Indicates the module we want to use
    Map<String, Object> options = new HashMap<>();
    options.put("authModuleId", authModuleClass.getSimpleName());
    
    // This authentication service installs an authentication config provider in the default factory, which
    // is the one we setup above. This authentication config provider uses the passed-in configParser to
    // retrieve configuration for authentication modules from.
    DefaultAuthenticationService authenticationService = new DefaultAuthenticationService(appContextId, options, configParser, null);
    
    servletContext.setAttribute(AUTH_SERVICE, authenticationService);
    
    servletContext.addFilter(AuthenticationFilter.class.getSimpleName(), AuthenticationFilter.class);
    
    // TMP - should use Dynamic
    ((WebApplication) servletContext).addFilterMapping(AuthenticationFilter.class.getSimpleName(), "/*");
}
 
Example 7
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 8
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 9
Source File: WebConfigurer.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 10
Source File: WebConfigurer.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
/**
 * 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 11
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 12
Source File: MdcInitializer.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException {
    try {
        ctx.getClassLoader().loadClass("org.apache.logging.log4j.web.ServletRequestThreadContext");
    } catch (final ClassNotFoundException e) {
        log.debug("log4j-web not available, skipping MDC setup");
        return;
    }
    final FilterRegistration.Dynamic filter = ctx.addFilter("mdc-request-binder", MdcRequestBinder.class);
    filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
    filter.setAsyncSupported(true);
}
 
Example 13
Source File: Log4jServletContainerInitializer.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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, "/*");
    }
}
 
Example 14
Source File: WebConfigurer.java    From flair-engine with Apache License 2.0 5 votes vote down vote up
/**
 * 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(jHipsterProperties));

    cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/content/*");
    cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/app/*");
    cachingHttpHeadersFilter.setAsyncSupported(true);
}
 
Example 15
Source File: WebConfiguration.java    From microcks with Apache License 2.0 5 votes vote down vote up
/** */
private void initCORSFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) {
   FilterRegistration.Dynamic corsFilter = servletContext.addFilter("corsFilter", new CorsFilter());
   corsFilter.addMappingForUrlPatterns(disps, true, "/api/*");
   corsFilter.addMappingForUrlPatterns(disps, true, "/dynarest/*");
   corsFilter.setAsyncSupported(true);
}
 
Example 16
Source File: WebInitializer.java    From maven-framework-project with MIT License 4 votes vote down vote up
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
	
	AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
	
	applicationContext.register(WebConfig.class);
	
	servletContext.addListener(new ContextLoaderListener(applicationContext));
	
	applicationContext.setServletContext(servletContext);
	
	FilterRegistration.Dynamic filter = servletContext.addFilter("characterEncodingFilter", org.springframework.web.filter.CharacterEncodingFilter.class);
	filter.setInitParameter("encoding", "utf-8");
	filter.setInitParameter("forceEncoding", "true");
	filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
	
	
	ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(applicationContext));
	
	dispatcher.setLoadOnStartup(1);
	
	dispatcher.addMapping("/");
}
 
Example 17
Source File: MyWebAppInitializer.java    From spring-rest-server with GNU Lesser General Public License v3.0 4 votes vote down vote up
private void addLoggingFilter(ServletContext container) {
    FilterRegistration.Dynamic fr = container.addFilter("loggingFilter", new CommonsRequestLoggingFilter());
    fr.addMappingForUrlPatterns(null, true, "/*");
}
 
Example 18
Source File: AuthorizationPreInitializer.java    From piranha with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Initialize Exousia
 *
 * @param classes the classes.
 * @param servletContext the Servlet context.
 * @throws ServletException when a Servlet error occurs.
 */
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
    WebApplication context = (WebApplication) servletContext;

    // Gets the authorization module classes that were configured externally
    Class<?> factoryClass = getAttribute(servletContext, AUTHZ_FACTORY_CLASS);
    Class<? extends Policy> policyClass = getAttribute(servletContext, AUTHZ_POLICY_CLASS);

    // Create the main Exousia authorization service, which implements the various entry points (an SPI)
    // for a runtime to make use of Jakarta Authorization
    AuthorizationService authorizationService = new AuthorizationService(
            factoryClass,
            policyClass, context.getServletContextId(),
            () -> localServletRequest.get(),
            () -> DefaultAuthenticatedIdentity.getCurrentSubject(),
            new PiranhaPrincipalMapper());

    // Join together in one list the constraints set by the servlet security elements, and the
    // piranha specific security constraint
    List<SecurityConstraint> securityConstraints = join(
            getConstraintsFromSecurityElements(servletContext, authorizationService),
            getConstraintsFromSecurityAnnotations(servletContext, authorizationService),
            getOptionalAttribute(servletContext, CONSTRAINTS),
            getConstraintsFromWebXMl(context));

    if (hasPermissionsSet(context)) {
        setPermissions(context, authorizationService);
    } else {
        authorizationService.addConstraintsToPolicy(
                securityConstraints != null ? securityConstraints : emptyList(),
                emptySet(),
                isDenyUncoveredHttpMethods(context),
                context.getServletRegistrations().keySet());
    }

    servletContext.setAttribute(AUTHZ_SERVICE, authorizationService);
    servletContext.addFilter(AuthorizationPreFilter.class.getSimpleName(), AuthorizationPreFilter.class);

    // TMP - should use Dynamic
    context.addFilterMapping(AuthorizationPreFilter.class.getSimpleName(), "/*");
}
 
Example 19
Source File: CxfCdiAutoSetup.java    From openwebbeans-meecrowave with Apache License 2.0 4 votes vote down vote up
@Override
public void onStartup(final Set<Class<?>> c, final ServletContext ctx) {
    final Configuration builder = Configuration.class.cast(ctx.getAttribute("meecrowave.configuration"));
    final MeecrowaveCXFCdiServlet delegate = new MeecrowaveCXFCdiServlet();
    final FilterRegistration.Dynamic jaxrs = ctx.addFilter(NAME, new Filter() {
        private final String servletPath = builder.getJaxrsMapping().endsWith("/*") ?
                builder.getJaxrsMapping().substring(0, builder.getJaxrsMapping().length() - 2) : builder.getJaxrsMapping();

        @Override
        public void init(final FilterConfig filterConfig) throws ServletException {
            delegate.init(new ServletConfig() {
                @Override
                public String getServletName() {
                    return NAME;
                }

                @Override
                public ServletContext getServletContext() {
                    return filterConfig.getServletContext();
                }

                @Override
                public String getInitParameter(final String name) {
                    return filterConfig.getInitParameter(name);
                }

                @Override
                public Enumeration<String> getInitParameterNames() {
                    return filterConfig.getInitParameterNames();
                }
            });
        }

        @Override
        public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
            if (!HttpServletRequest.class.isInstance(request)) {
                chain.doFilter(request, response);
                return;
            }
            final HttpServletRequest http = HttpServletRequest.class.cast(request);
            final String path = http.getRequestURI().substring(http.getContextPath().length());
            final Optional<String> app = Stream.of(delegate.prefixes).filter(path::startsWith).findAny();
            if (app.isPresent()) {
                delegate.service(new HttpServletRequestWrapper(http) { // fake servlet pathInfo and path
                    @Override
                    public String getPathInfo() {
                        return path;
                    }

                    @Override
                    public String getServletPath() {
                        return servletPath;
                    }
                }, response);
            } else {
                chain.doFilter(request, response);
            }
        }

        @Override
        public void destroy() {
            delegate.destroy();
        }
    });
    jaxrs.setAsyncSupported(true);
    jaxrs.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC), true, builder.getJaxrsMapping());
    ofNullable(builder.getCxfServletParams()).ifPresent(m -> m.forEach(jaxrs::setInitParameter));
}