Java Code Examples for javax.servlet.FilterRegistration#Dynamic

The following examples show how to use javax.servlet.FilterRegistration#Dynamic . 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: 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 2
Source File: OWBAutoSetup.java    From openwebbeans-meecrowave with Apache License 2.0 6 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 Meecrowave instance = Meecrowave.class.cast(ctx.getAttribute("meecrowave.instance"));
    if (builder.isCdiConversation()) {
        try {
            final Class<? extends Filter> clazz = (Class<? extends Filter>) OWBAutoSetup.class.getClassLoader()
                  .loadClass("org.apache.webbeans.web.context.WebConversationFilter");
            final FilterRegistration.Dynamic filter = ctx.addFilter("owb-conversation", clazz);
            filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
        } catch (final Exception e) {
            // no-op
        }
    }

    // eager boot to let injections work in listeners
    final EagerBootListener bootListener = new EagerBootListener(instance);
    bootListener.doContextInitialized(new ServletContextEvent(ctx));
    ctx.addListener(bootListener);
}
 
Example 3
Source File: WebConfigurer.java    From JiwhizBlogWeb with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the static resources production Filter.
 */
private void initStaticResourcesProductionFilter(ServletContext servletContext,
                                                 EnumSet<DispatcherType> disps) {

    log.debug("Registering static resources production Filter");
    FilterRegistration.Dynamic staticResourcesProductionFilter =
            servletContext.addFilter("staticResourcesProductionFilter",
                    new StaticResourcesProductionFilter());

    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/index.html");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/images/*");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/fonts/*");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/scripts/*");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/styles/*");
    staticResourcesProductionFilter.addMappingForUrlPatterns(disps, true, "/views/*");
    staticResourcesProductionFilter.setAsyncSupported(true);
}
 
Example 4
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 5
Source File: DefaultWebApplication.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Add the filter.
 *
 * @param filterName the filter name.
 * @param className the class name.
 * @return the filter dynamic.
 */
@Override
public FilterRegistration.Dynamic addFilter(String filterName, String className) {
    if (status == SERVICING) {
        throw new IllegalStateException("Cannot call this after web application has started");
    }

    if (filterName == null || filterName.trim().equals("")) {
        throw new IllegalArgumentException("Filter name cannot be null or empty");
    }

    DefaultFilterEnvironment defaultFilterEnvironment;
    if (filters.containsKey(filterName)) {
        defaultFilterEnvironment = filters.get(filterName);
    } else {
        defaultFilterEnvironment = new DefaultFilterEnvironment();
        defaultFilterEnvironment.setFilterName(filterName);
        defaultFilterEnvironment.setWebApplication(this);
        filters.put(filterName, defaultFilterEnvironment);
    }
    defaultFilterEnvironment.setClassName(className);

    return defaultFilterEnvironment;
}
 
Example 6
Source File: ServletContextImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public FilterRegistration.Dynamic addFilter(final String filterName, final Class<? extends Filter> filterClass) {
    ensureNotProgramaticListener();
    ensureNotInitialized();
    if (deploymentInfo.getFilters().containsKey(filterName)) {
        return null;
    }
    try {
        FilterInfo filter = new FilterInfo(filterName, filterClass,deploymentInfo.getClassIntrospecter().createInstanceFactory(filterClass));
        deploymentInfo.addFilter(filter);
        deployment.getFilters().addFilter(filter);
        return new FilterRegistrationImpl(filter, deployment, this);
    } catch (NoSuchMethodException e) {
        throw UndertowServletMessages.MESSAGES.couldNotCreateFactory(filterClass.getName(),e);
    }
}
 
Example 7
Source File: WebConfigurer.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
/**
 * 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 8
Source File: FilterHelper.java    From jee-pac4j with Apache License 2.0 5 votes vote down vote up
/**
 * Add a filter mapping.
 *
 * @param name the name fo the filter
 * @param filter the filter
 * @param parameters the URLs on which it applies and the supported dispatcher types
 */
public void addFilterMapping(final String name, final Filter filter, final Object... parameters) {
    assertNotBlank("name", name);
    assertNotNull("filter", filter);
    assertNotNull("parameters", parameters);

    final List<String> urls = new ArrayList<>();
    final List<DispatcherType> types = new ArrayList<>();
    for (final Object parameter : parameters) {
        if (parameter instanceof String) {
            urls.add((String) parameter);
        } else if (parameter instanceof DispatcherType) {
            types.add((DispatcherType) parameter);
        } else {
            throw new TechnicalException("Unsupported parameter type: " + parameter);
        }
    }
    if (urls.isEmpty()) {
        throw new TechnicalException("No URL mapping defined for filter: " + name);
    }
    if (types.isEmpty()) {
        types.add(DispatcherType.REQUEST);
    }

    final FilterRegistration.Dynamic registration = servletContext.addFilter(name, filter);
    registration.addMappingForUrlPatterns(EnumSet.copyOf(types), true, urls.toArray(new String[urls.size()]));
}
 
Example 9
Source File: WebConfigurer.java    From jhipster-registry 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, "/i18n/*");
    cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/content/*");
    cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/app/*");
    cachingHttpHeadersFilter.setAsyncSupported(true);
}
 
Example 10
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 11
Source File: StreamlineApplication.java    From streamline with Apache License 2.0 5 votes vote down vote up
private void enableCORS(Environment environment, List<String> urlPatterns) {
    // 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
    String[] urls = urlPatterns.toArray(new String[urlPatterns.size()]);
    cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, urls);
}
 
Example 12
Source File: ApplicationContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public FilterRegistration.Dynamic addFilter(String filterName,
        Class<? extends Filter> filterClass) {
    return addFilter(filterName, filterClass.getName(), null);
}
 
Example 13
Source File: ParserServletContext.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public FilterRegistration.Dynamic addFilter(String string, Class<? extends Filter> type) {
    return null;
}
 
Example 14
Source File: MockServletContext.java    From para with Apache License 2.0 4 votes vote down vote up
@Override
public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) {
	throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 15
Source File: MockServletContext.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) {
	throw new UnsupportedOperationException();
}
 
Example 16
Source File: NettyEmbeddedContext.java    From Jinx with Apache License 2.0 4 votes vote down vote up
private FilterRegistration.Dynamic addFilter(String filterName, String className, Filter filter) {
    NettyFilterRegistration filterRegistration = new NettyFilterRegistration(this, filterName, className, filter);
    filters.put(filterName, filterRegistration);
    return filterRegistration;
}
 
Example 17
Source File: ThreadLocalServletContext.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public FilterRegistration.Dynamic addFilter(final String filterName, final Class<? extends Filter> filterClass) throws IllegalArgumentException, IllegalStateException {
    return get().addFilter(filterName, filterClass);
}
 
Example 18
Source File: EmptyServletContext.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public FilterRegistration.Dynamic addFilter(String string, Filter filter) {
    return null;
}
 
Example 19
Source File: MockServletContext.java    From deltaspike with Apache License 2.0 4 votes vote down vote up
@Override
public FilterRegistration.Dynamic addFilter(String filterName, Filter filter)
    throws IllegalArgumentException, IllegalStateException
{
    return null;
}
 
Example 20
Source File: ApplicationContext.java    From Tomcat7.0.67 with Apache License 2.0 3 votes vote down vote up
/**
 * Add filter to context.
 * @param   filterName  Name of filter to add
 * @param   filterClass Class of filter to add
 * @return  <code>null</code> if the filter has already been fully defined,
 *          else a {@link javax.servlet.FilterRegistration.Dynamic} object
 *          that can be used to further configure the filter
 * @throws IllegalStateException if the context has already been initialised
 * @throws UnsupportedOperationException - if this context was passed to the
 *         {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)}
 *         method of a {@link ServletContextListener} that was not declared
 *         in web.xml, a web-fragment or annotated with
 *         {@link javax.servlet.annotation.WebListener}.
 */
@Override
public FilterRegistration.Dynamic addFilter(String filterName,
        Class<? extends Filter> filterClass) throws IllegalStateException {

    return addFilter(filterName, filterClass.getName(), null);
}