Example usage for javax.servlet FilterRegistration.Dynamic addMappingForServletNames

List of usage examples for javax.servlet FilterRegistration.Dynamic addMappingForServletNames

Introduction

In this page you can find the example usage for javax.servlet FilterRegistration.Dynamic addMappingForServletNames.

Prototype

public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter,
        String... servletNames);

Source Link

Document

Adds a filter mapping with the given servlet names and dispatcher types for the Filter represented by this FilterRegistration.

Usage

From source file:com.nebhale.cyclinglibrary.web.ApplicationInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(UtilConfiguration.class, RepositoryConfiguration.class);

    servletContext.addListener(new ContextLoaderListener(rootContext));

    AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
    webContext.register(WebConfiguration.class);

    ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher",
            new DispatcherServlet(webContext));
    dispatcherServlet.setLoadOnStartup(1);
    dispatcherServlet.addMapping("/");

    FilterRegistration.Dynamic gzipFilter = servletContext.addFilter("gzip", new GzipFilter());
    gzipFilter.addMappingForServletNames(null, false, "dispatcher");

    FilterRegistration.Dynamic eTagFilter = servletContext.addFilter("etag", new ShallowEtagHeaderFilter());
    eTagFilter.addMappingForServletNames(null, false, "dispatcher");
}

From source file:io.springagora.store.AppInitializer.java

/**
 * Web Application.//www  . j  a v a  2  s. c  om
 * 
 * @param container
 *      {@code ServletContext}. Representation of the context that is serving
 *      the JEE application. Servlets, filters and listeners are registered
 *      via this interface.
 */
private void initializeWebApplication(ServletContext container) {
    AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(WebConfig.class);

    DispatcherServlet webDispatcher = new DispatcherServlet(dispatcherContext);
    ServletRegistration.Dynamic servletReg = container.addServlet(dispatcherWebName, webDispatcher);
    servletReg.setLoadOnStartup(1);
    servletReg.addMapping(URL_PATTERN_WEB);

    HiddenHttpMethodFilter filter = new HiddenHttpMethodFilter();
    FilterRegistration.Dynamic filterReg = container.addFilter("Hidden HTTP Method Filter", filter);
    filterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, dispatcherWebName);
}

From source file:eu.enhan.timelord.web.init.TimelordWebInit.java

/**
 * @see org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet.ServletContext)
 *///from   w w  w .j av  a 2  s  .  c o m
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext rootCtx = new AnnotationConfigWebApplicationContext();
    rootCtx.register(AppConfig.class);
    servletContext.addListener(new ContextLoaderListener(rootCtx));

    AnnotationConfigWebApplicationContext webAppCtx = new AnnotationConfigWebApplicationContext();
    webAppCtx.setParent(rootCtx);
    webAppCtx.register(WebConfig.class);

    XmlWebApplicationContext securityCtx = new XmlWebApplicationContext();
    securityCtx.setServletContext(servletContext);
    securityCtx.setParent(rootCtx);
    securityCtx.setConfigLocation("classpath:/spring/security.xml");

    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(webAppCtx));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");

    FilterRegistration.Dynamic securityFilter = servletContext.addFilter("springSecurityFilterChain",
            new DelegatingFilterProxy("springSecurityFilterChain", securityCtx));
    //   securityFilter.addMappingForUrlPatterns(null, false, "/**");
    securityFilter.addMappingForServletNames(null, false, "dispatcher");

}

From source file:com.jsmartframework.web.manager.ContextControl.java

@Override
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    try {/* w w w . ja v  a 2  s.  co m*/
        ServletContext servletContext = event.getServletContext();

        CONFIG.init(servletContext);
        if (CONFIG.getContent() == null) {
            throw new RuntimeException("Configuration file " + Constants.WEB_CONFIG_XML
                    + " was not found in WEB-INF resources folder!");
        }

        String contextConfigLocation = "com.jsmartframework.web.manager";
        if (CONFIG.getContent().getPackageScan() != null) {
            contextConfigLocation += "," + CONFIG.getContent().getPackageScan();
        }

        // Configure necessary parameters in the ServletContext to set Spring configuration without needing an XML file
        AnnotationConfigWebApplicationContext configWebAppContext = new AnnotationConfigWebApplicationContext();
        configWebAppContext.setConfigLocation(contextConfigLocation);

        CONTEXT_LOADER = new ContextLoader(configWebAppContext);
        CONTEXT_LOADER.initWebApplicationContext(servletContext);

        TagEncrypter.init();
        TEXTS.init();
        IMAGES.init(servletContext);
        HANDLER.init(servletContext);

        // ServletControl -> @MultipartConfig @WebServlet(name = "ServletControl", displayName = "ServletControl", loadOnStartup = 1)
        Servlet servletControl = servletContext.createServlet(
                (Class<? extends Servlet>) Class.forName("com.jsmartframework.web.manager.ServletControl"));
        ServletRegistration.Dynamic servletControlReg = (ServletRegistration.Dynamic) servletContext
                .addServlet("ServletControl", servletControl);
        servletControlReg.setAsyncSupported(true);
        servletControlReg.setLoadOnStartup(1);

        // ServletControl Initial Parameters
        InitParam[] initParams = CONFIG.getContent().getInitParams();
        if (initParams != null) {
            for (InitParam initParam : initParams) {
                servletControlReg.setInitParameter(initParam.getName(), initParam.getValue());
            }
        }

        // MultiPart to allow file upload on ServletControl
        MultipartConfigElement multipartElement = getServletMultipartElement();
        if (multipartElement != null) {
            servletControlReg.setMultipartConfig(multipartElement);
        }

        // Security constraint to ServletControl
        ServletSecurityElement servletSecurityElement = getServletSecurityElement(servletContext);
        if (servletSecurityElement != null) {
            servletControlReg.setServletSecurity(servletSecurityElement);
        }

        // TODO: Fix problem related to authentication by container to use SSL dynamically (Maybe create more than one servlet for secure and non-secure patterns)
        // Check also the use of request.login(user, pswd)
        // Check the HttpServletRequest.BASIC_AUTH, CLIENT_CERT_AUTH, FORM_AUTH, DIGEST_AUTH
        // servletReg.setRunAsRole("admin");
        // servletContext.declareRoles("admin");

        // ServletControl URL mapping
        String[] servletMapping = getServletMapping();
        servletControlReg.addMapping(servletMapping);

        // ErrorFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter errorFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.ErrorFilter"));
        FilterRegistration.Dynamic errorFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("ErrorFilter", errorFilter);

        errorFilterReg.setAsyncSupported(true);
        errorFilterReg.addMappingForUrlPatterns(
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR), true, "/*");

        // EncodeFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter encodeFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.EncodeFilter"));
        FilterRegistration.Dynamic encodeFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("EncodeFilter", encodeFilter);

        encodeFilterReg.setAsyncSupported(true);
        encodeFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // CacheFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter cacheFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.CacheFilter"));
        FilterRegistration.Dynamic cacheFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("CacheFilter", cacheFilter);

        cacheFilterReg.setAsyncSupported(true);
        cacheFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // Add custom filters defined by client
        for (String filterName : sortCustomFilters()) {
            Filter customFilter = servletContext
                    .createFilter((Class<? extends Filter>) HANDLER.webFilters.get(filterName));
            HANDLER.executeInjection(customFilter);

            WebFilter webFilter = customFilter.getClass().getAnnotation(WebFilter.class);
            FilterRegistration.Dynamic customFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter(filterName, customFilter);

            if (webFilter.initParams() != null) {
                for (WebInitParam initParam : webFilter.initParams()) {
                    customFilterReg.setInitParameter(initParam.name(), initParam.value());
                }
            }
            customFilterReg.setAsyncSupported(webFilter.asyncSupported());
            customFilterReg.addMappingForUrlPatterns(EnumSet.copyOf(Arrays.asList(webFilter.dispatcherTypes())),
                    true, webFilter.urlPatterns());
        }

        // FilterControl -> @WebFilter(servletNames = {"ServletControl"})
        Filter filterControl = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.FilterControl"));
        FilterRegistration.Dynamic filterControlReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("FilterControl", filterControl);

        filterControlReg.setAsyncSupported(true);
        filterControlReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // OutputFilter -> @WebFilter(servletNames = {"ServletControl"})
        Filter outputFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.OutputFilter"));
        FilterRegistration.Dynamic outputFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("OutputFilter", outputFilter);

        outputFilterReg.setAsyncSupported(true);
        outputFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // AsyncFilter -> @WebFilter(servletNames = {"ServletControl"})
        // Filter used case AsyncContext is dispatched internally by AsyncBean implementation
        Filter asyncFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.AsyncFilter"));
        FilterRegistration.Dynamic asyncFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("AsyncFilter", asyncFilter);

        asyncFilterReg.setAsyncSupported(true);
        asyncFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.ASYNC), true, "ServletControl");

        // SessionControl -> @WebListener
        EventListener sessionListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.SessionControl"));
        servletContext.addListener(sessionListener);

        // RequestControl -> @WebListener
        EventListener requestListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.RequestControl"));
        servletContext.addListener(requestListener);

        // Custom WebServlet -> Custom Servlets created by application
        for (String servletName : HANDLER.webServlets.keySet()) {
            Servlet customServlet = servletContext
                    .createServlet((Class<? extends Servlet>) HANDLER.webServlets.get(servletName));
            HANDLER.executeInjection(customServlet);

            WebServlet webServlet = customServlet.getClass().getAnnotation(WebServlet.class);
            ServletRegistration.Dynamic customReg = (ServletRegistration.Dynamic) servletContext
                    .addServlet(servletName, customServlet);

            customReg.setLoadOnStartup(webServlet.loadOnStartup());
            customReg.setAsyncSupported(webServlet.asyncSupported());

            WebInitParam[] customInitParams = webServlet.initParams();
            if (customInitParams != null) {
                for (WebInitParam customInitParam : customInitParams) {
                    customReg.setInitParameter(customInitParam.name(), customInitParam.value());
                }
            }

            // Add mapping url for custom servlet
            customReg.addMapping(webServlet.urlPatterns());

            if (customServlet.getClass().isAnnotationPresent(MultipartConfig.class)) {
                customReg.setMultipartConfig(new MultipartConfigElement(
                        customServlet.getClass().getAnnotation(MultipartConfig.class)));
            }
        }

        // Controller Dispatcher for Spring MVC
        Set<String> requestPaths = HANDLER.requestPaths.keySet();
        if (!requestPaths.isEmpty()) {
            ServletRegistration.Dynamic mvcDispatcherReg = servletContext.addServlet("DispatcherServlet",
                    new DispatcherServlet(configWebAppContext));
            mvcDispatcherReg.setLoadOnStartup(1);
            mvcDispatcherReg.addMapping(requestPaths.toArray(new String[requestPaths.size()]));

            // RequestPathFilter -> @WebFilter(servletNames = {"DispatcherServlet"})
            Filter requestPathFilter = servletContext.createFilter((Class<? extends Filter>) Class
                    .forName("com.jsmartframework.web.manager.RequestPathFilter"));
            FilterRegistration.Dynamic reqPathFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter("RequestPathFilter", requestPathFilter);

            reqPathFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST,
                    DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.INCLUDE, DispatcherType.ASYNC),
                    true, "DispatcherServlet");
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.ops4j.pax.web.service.tomcat.internal.TomcatServerWrapper.java

@Override
public void addFilter(final FilterModel filterModel) {
    LOG.debug("add filter [{}]", filterModel);

    final Context context = findOrCreateContext(filterModel);
    LifecycleState state = ((HttpServiceContext) context).getState();
    boolean restartContext = false;
    if ((LifecycleState.STARTING.equals(state) || LifecycleState.STARTED.equals(state))
            && !filterModel.getContextModel().isWebBundle()) {
        try {/*from  w ww  .ja v  a 2s  . c o m*/
            restartContext = true;
            ((HttpServiceContext) context).stop();
        } catch (LifecycleException e) {
            LOG.warn("Can't reset the Lifecycle ... ", e);
        }
    }
    context.addLifecycleListener(new LifecycleListener() {

        @Override
        public void lifecycleEvent(LifecycleEvent event) {
            if (Lifecycle.BEFORE_START_EVENT.equalsIgnoreCase(event.getType())) {
                FilterRegistration.Dynamic filterRegistration = null;
                if (filterModel.getFilter() != null) {
                    filterRegistration = context.getServletContext().addFilter(filterModel.getName(),
                            filterModel.getFilter());

                } else if (filterModel.getFilterClass() != null) {
                    filterRegistration = context.getServletContext().addFilter(filterModel.getName(),
                            filterModel.getFilterClass());
                }

                if (filterRegistration == null) {
                    filterRegistration = (Dynamic) context.getServletContext()
                            .getFilterRegistration(filterModel.getName());
                    if (filterRegistration == null) {
                        LOG.error("Can't register Filter due to unknown reason!");
                    }
                }

                filterRegistration.setAsyncSupported(filterModel.isAsyncSupported());

                if (filterModel.getServletNames() != null && filterModel.getServletNames().length > 0) {
                    filterRegistration.addMappingForServletNames(getDispatcherTypes(filterModel), /*
                                                                                                  * TODO get
                                                                                                  * asynch
                                                                                                  * supported?
                                                                                                  */false,
                            filterModel.getServletNames());
                } else if (filterModel.getUrlPatterns() != null && filterModel.getUrlPatterns().length > 0) {
                    filterRegistration.addMappingForUrlPatterns(getDispatcherTypes(filterModel), /*
                                                                                                 * TODO get
                                                                                                 * asynch
                                                                                                 * supported?
                                                                                                 */false,
                            filterModel.getUrlPatterns());
                } else {
                    throw new AddFilterException(
                            "cannot add filter to the context; at least a not empty list of servlet names or URL patterns in exclusive mode must be provided: "
                                    + filterModel);
                }
                filterRegistration.setInitParameters(filterModel.getInitParams());
            }
        }
    });

    if (restartContext) {
        try {
            ((HttpServiceContext) context).start();
        } catch (LifecycleException e) {
            LOG.warn("Can't reset the Lifecycle ... ", e);
        }
    }

}

From source file:org.kuali.coeus.sys.framework.config.KcConfigurer.java

@Override
protected void doAdditionalModuleStartLogic() throws Exception {
    if (StringUtils.isNotBlank(dispatchServletName)) {
        DispatcherServlet loaderServlet = new DispatcherServlet(
                (WebApplicationContext) ((SpringResourceLoader) rootResourceLoader.getResourceLoaders().get(0))
                        .getContext());/*  w w  w.  j av a 2  s  .c  om*/
        ServletRegistration registration = getServletContext().addServlet(dispatchServletName, loaderServlet);
        registration.addMapping("/" + dispatchServletName + "/*");
        for (String filterName : filtersToMap) {
            FilterRegistration filter = getServletContext().getFilterRegistration(filterName);
            filter.addMappingForServletNames(null, true, dispatchServletName);
        }
        if (enableSpringSecurity) {
            DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(SPRING_SECURITY_FILTER_CHAIN,
                    (WebApplicationContext) ((SpringResourceLoader) rootResourceLoader.getResourceLoaders()
                            .get(0)).getContext());
            FilterRegistration.Dynamic securityFilter = getServletContext()
                    .addFilter(KC_PREFIX + getModuleName() + SPRING_SECURITY_FILTER_PROXY, filterProxy);
            securityFilter.addMappingForServletNames(null, true, dispatchServletName);
        }
    }
}

From source file:org.springframework.boot.context.embedded.AbstractFilterRegistrationBean.java

/**
 * Configure registration settings. Subclasses can override this method to perform
 * additional configuration if required.
 * @param registration the registration/*from  w  w  w  .  ja  va 2 s.  c o m*/
 */
protected void configure(FilterRegistration.Dynamic registration) {
    super.configure(registration);
    EnumSet<DispatcherType> dispatcherTypes = this.dispatcherTypes;
    if (dispatcherTypes == null) {
        dispatcherTypes = (isAsyncSupported() ? ASYNC_DISPATCHER_TYPES : NON_ASYNC_DISPATCHER_TYPES);
    }
    Set<String> servletNames = new LinkedHashSet<String>();
    for (ServletRegistrationBean servletRegistrationBean : this.servletRegistrationBeans) {
        servletNames.add(servletRegistrationBean.getServletName());
    }
    servletNames.addAll(this.servletNames);
    if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
        this.logger.info(
                "Mapping filter: '" + registration.getName() + "' to: " + Arrays.asList(DEFAULT_URL_MAPPINGS));
        registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS);
    } else {
        if (servletNames.size() > 0) {
            this.logger.info("Mapping filter: '" + registration.getName() + "' to servlets: " + servletNames);
            registration.addMappingForServletNames(dispatcherTypes, this.matchAfter,
                    servletNames.toArray(new String[servletNames.size()]));
        }
        if (this.urlPatterns.size() > 0) {
            this.logger.info("Mapping filter: '" + registration.getName() + "' to urls: " + this.urlPatterns);
            registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter,
                    this.urlPatterns.toArray(new String[this.urlPatterns.size()]));
        }
    }
}

From source file:org.springframework.boot.context.embedded.FilterRegistrationBean.java

/**
 * Configure registration settings. Subclasses can override this method to perform
 * additional configuration if required.
 * @param registration the registration//from ww w .  jav a  2 s .  co m
 */
protected void configure(FilterRegistration.Dynamic registration) {
    super.configure(registration);
    EnumSet<DispatcherType> dispatcherTypes = this.dispatcherTypes;
    if (dispatcherTypes == null) {
        dispatcherTypes = (isAsyncSupported() ? ASYNC_DISPATCHER_TYPES : NON_ASYNC_DISPATCHER_TYPES);
    }

    Set<String> servletNames = new LinkedHashSet<String>();
    for (ServletRegistrationBean servletRegistrationBean : this.servletRegistrationBeans) {
        servletNames.add(servletRegistrationBean.getServletName());
    }
    servletNames.addAll(this.servletNames);

    if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
        logger.info(
                "Mapping filter: '" + registration.getName() + "' to: " + Arrays.asList(DEFAULT_URL_MAPPINGS));
        registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS);
    } else {
        if (servletNames.size() > 0) {
            logger.info("Mapping filter: '" + registration.getName() + "' to servlets: " + servletNames);
            registration.addMappingForServletNames(dispatcherTypes, this.matchAfter,
                    servletNames.toArray(new String[servletNames.size()]));
        }
        if (this.urlPatterns.size() > 0) {
            logger.info("Mapping filter: '" + registration.getName() + "' to urls: " + this.urlPatterns);
            registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter,
                    this.urlPatterns.toArray(new String[this.urlPatterns.size()]));
        }
    }
}

From source file:org.springframework.boot.web.servlet.AbstractFilterRegistrationBean.java

/**
 * Configure registration settings. Subclasses can override this method to perform
 * additional configuration if required.
 * @param registration the registration/*from   w ww  .j  a v  a 2  s  .  co m*/
 */
protected void configure(FilterRegistration.Dynamic registration) {
    super.configure(registration);
    EnumSet<DispatcherType> dispatcherTypes = this.dispatcherTypes;
    if (dispatcherTypes == null) {
        dispatcherTypes = (isAsyncSupported() ? ASYNC_DISPATCHER_TYPES : NON_ASYNC_DISPATCHER_TYPES);
    }
    Set<String> servletNames = new LinkedHashSet<String>();
    for (ServletRegistrationBean servletRegistrationBean : this.servletRegistrationBeans) {
        servletNames.add(servletRegistrationBean.getServletName());
    }
    servletNames.addAll(this.servletNames);
    if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
        this.logger.info(
                "Mapping filter: '" + registration.getName() + "' to: " + Arrays.asList(DEFAULT_URL_MAPPINGS));
        registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS);
    } else {
        if (!servletNames.isEmpty()) {
            this.logger.info("Mapping filter: '" + registration.getName() + "' to servlets: " + servletNames);
            registration.addMappingForServletNames(dispatcherTypes, this.matchAfter,
                    servletNames.toArray(new String[servletNames.size()]));
        }
        if (!this.urlPatterns.isEmpty()) {
            this.logger.info("Mapping filter: '" + registration.getName() + "' to urls: " + this.urlPatterns);
            registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter,
                    this.urlPatterns.toArray(new String[this.urlPatterns.size()]));
        }
    }
}