Example usage for javax.servlet DispatcherType REQUEST

List of usage examples for javax.servlet DispatcherType REQUEST

Introduction

In this page you can find the example usage for javax.servlet DispatcherType REQUEST.

Prototype

DispatcherType REQUEST

To view the source code for javax.servlet DispatcherType REQUEST.

Click Source Link

Usage

From source file:org.picketlink.test.identity.federation.bindings.wildfly.SPInitiatedSSOWorkflowTestCase.java

public void deployIDP() throws Exception {
    final ServletContainer container = ServletContainer.Factory.newInstance();
    FilterInfo idpFilterInfo = new FilterInfo("IDPFilter", IDPFilter.class);

    ServletInfo regularServletInfo = new ServletInfo("servlet", SendUsernameServlet.class)
            .setServletSecurityInfo(new ServletSecurityInfo().addRoleAllowed("role1")).addMapping("/*");

    ServletInfo formServletInfo = new ServletInfo("loginPage", FormLoginServlet.class)
            .setServletSecurityInfo(new ServletSecurityInfo().addRoleAllowed("group1"))
            .addMapping("/FormLoginServlet");

    TestIdentityManager identityManager = new TestIdentityManager();
    identityManager.addUser("user1", "password1", "role1");

    LoginConfig loginConfig = new LoginConfig("FORM", "Test Realm", "/FormLoginServlet", "/error.html");

    DeploymentInfo deploymentInfo = new DeploymentInfo()
            .setClassLoader(SPInitiatedSSOWorkflowTestCase.class.getClassLoader()).setContextPath("/idp")
            .setDeploymentName("idp.war").setClassIntrospecter(TestClassIntrospector.INSTANCE)
            .setIdentityManager(identityManager).setLoginConfig(loginConfig)
            .setResourceManager(new TestResourceManager("idp")).addServlets(regularServletInfo, formServletInfo)
            .addFilter(idpFilterInfo)/*www .j a  v a  2 s .c o  m*/
            .addFilterUrlMapping(idpFilterInfo.getName(), "/*", DispatcherType.REQUEST);

    DeploymentManager manager = container.addDeployment(deploymentInfo);
    manager.deploy();

    try {
        path.addPath(deploymentInfo.getContextPath(), manager.start());
    } catch (ServletException se) {
        throw new RuntimeException(se);
    }
    System.out.println("Deployment success:" + deploymentInfo.getContextPath());
}

From source file:com.liferay.portal.http.service.internal.servlet.BundleServletContextTest.java

@Test
public void testGetFilterChain() throws Exception {
    mockBundleWiring();/*from ww  w  .  j av a2s  . c o m*/

    List<LogRecord> logFilterRecords = JDKLoggerTestUtil.configureJDKLogger(MockLoggingFilter.class.getName(),
            Level.INFO);

    String cssFilterName = "CSS Filter";

    registerFilter(cssFilterName, new MockLoggingFilter(cssFilterName), null, "/css/*");

    String jsFilterName = "JS Filter";

    registerFilter(jsFilterName, new MockLoggingFilter(jsFilterName), null, "/js/*");

    registerServlet("Sample Servlet", "/");

    FilterChain filterChain = _bundleServletContext.getFilterChain("/js/main.js", DispatcherType.REQUEST);

    Assert.assertNotNull(filterChain);

    filterChain.doFilter(new MockHttpServletRequest(), new MockHttpServletResponse());

    Assert.assertEquals(1, logFilterRecords.size());

    LogRecord logRecord = logFilterRecords.get(0);

    Assert.assertEquals(jsFilterName, logRecord.getMessage());

    verifyBundleWiring();
}

From source file:io.undertow.servlet.test.handlers.MarkSecureHandlerTestCase.java

@Test
public void testMarkSecureHandlerWithSecureCookieHandler()
        throws IOException, GeneralSecurityException, ServletException {

    final PathHandler root = new PathHandler();
    final ServletContainer container = ServletContainer.Factory.newInstance();

    ServletInfo s = new ServletInfo("servlet", MessageServlet.class)
            .addInitParam(MessageServlet.MESSAGE, HELLO_WORLD).addMapping("/issecure");
    DeploymentInfo builder = new DeploymentInfo()
            .setClassLoader(MarkSecureHandlerTestCase.class.getClassLoader()).setContextPath("/servletContext")
            .setClassIntrospecter(TestClassIntrospector.INSTANCE).setDeploymentName("servletContext.war")
            .addServlet(s);//from ww  w .jav  a  2s . c  o  m

    builder.addFilter(new FilterInfo("issecure-filter", IsSecureFilter.class));
    builder.addFilterUrlMapping("issecure-filter", "/*", DispatcherType.REQUEST);

    DeploymentManager manager = container.addDeployment(builder);
    manager.deploy();
    root.addPrefixPath(builder.getContextPath(), manager.start());

    DefaultServer.setRootHandler(new MarkSecureHandler(new SecureCookieHandler(root)));

    TestHttpClient client = new TestHttpClient();
    try {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/issecure");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        // When MarkSecureHandler is enabled, req.isSecure() should be true
        Assert.assertEquals("true", result.getHeaders("issecure")[0].getValue());
        // When SecureCookieHandler is enabled with MarkSecureHandler, secure cookie is enabled as this channel is treated as secure
        Header header = result.getFirstHeader("set-cookie");
        Assert.assertEquals("foo=bar; secure", header.getValue());
        final String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals(HELLO_WORLD, response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:io.fabric8.apiman.Fabric8ManagerApiMicroService.java

@Override
protected void addModulesToJetty(HandlerCollection handlers) throws Exception {
    super.addModulesToJetty(handlers);
    //override the apimanUiServer handler 
    ServletContextHandler apimanUiServer = new ServletContextHandler(ServletContextHandler.SESSIONS);

    addSecurityHandler(apimanUiServer);//from ww  w .j  a v a  2 s  .  c  o  m
    apimanUiServer.setContextPath("/apimanui");
    apimanUiServer.addFilter(ApimanCorsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    //add the servlets before the static content
    LinkServlet parseServlet = new LinkServlet();
    apimanUiServer.addServlet(new ServletHolder(parseServlet), "/link");
    ConfigurationServlet configServlet = new ConfigurationServlet();
    apimanUiServer.addServlet(new ServletHolder(configServlet), "/apiman/config.js");
    TranslationServlet translationServlet = new TranslationServlet();
    apimanUiServer.addServlet(new ServletHolder(translationServlet), "/apiman/translations.js");

    //figuring out from where to load the static content in the apimanui war
    String indexFile = this.getClass().getClassLoader().getResource("apimanui/index.html").toExternalForm();
    String webDir = indexFile.substring(0, indexFile.length() - 10);
    apimanUiServer.setInitParameter("org.eclipse.jetty.servlet.Default.resourceBase", webDir);
    apimanUiServer.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    DefaultServlet defaultServlet = new DefaultServlet();
    ServletHolder holder = new ServletHolder("default", defaultServlet);
    apimanUiServer.addServlet(holder, "/*");

    //rewriting some paths to angularjs index.html app
    RewriteHandler rewriter = new RewriteHandler();
    rewriter.setRewriteRequestURI(true);
    rewriter.setRewritePathInfo(false);
    rewriter.setOriginalPathAttribute("requestedPath");
    RewriteRegexRule rule1 = new RewriteRegexRule();
    rule1.setRegex("/apimanui/api-manager/.*");
    rule1.setReplacement("/apimanui/index.html");
    rewriter.addRule(rule1);
    RewriteRegexRule rule2 = new RewriteRegexRule();
    rule2.setRegex("/apimanui/api-manager/|/apimanui/|/apimanui");
    rule2.setReplacement("/apimanui/index.html");
    rewriter.addRule(rule2);

    rewriter.setHandler(apimanUiServer);

    Handler[] newHandlers = new Handler[] { handlers.getHandlers()[0], rewriter };
    handlers.setHandlers(newHandlers);
}

From source file:com.dm.estore.config.WebAppInitializer.java

private void registerFilters(ServletContext servletContext) {
    FilterRegistration.Dynamic securityFilter = servletContext.addFilter(SECURITY_FILTER_NAME,
            new DelegatingFilterProxy());
    securityFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, REST_SERVLET_MAPPING);
    securityFilter.setAsyncSupported(true);

    FilterRegistration.Dynamic applicationFilter = servletContext.addFilter(APP_FILTER_NAME,
            new ApplicationFilter());
    applicationFilter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD),
            false, APP_FILTER_MAPPING);/*w ww .jav a2s .  c  o m*/
    applicationFilter.setAsyncSupported(true);
}

From source file:net.bull.javamelody.JavaMelodyAutoConfiguration.java

/**
 * Registers the JavaMelody {@link MonitoringFilter}. The filter can be overridden completely by creating a custom
 * {@link FilterRegistrationBean} with the name "javamelody-registration" in the application context.
 * @param properties JavaMelodyConfigurationProperties
 * @param servletContext ServletContext// ww  w  .  java2 s. c  o m
 * @return FilterRegistrationBean
 */
@Bean(name = REGISTRATION_BEAN_NAME)
@ConditionalOnMissingBean(name = REGISTRATION_BEAN_NAME)
public FilterRegistrationBean monitoringFilter(JavaMelodyConfigurationProperties properties,
        ServletContext servletContext) {
    final FilterRegistrationBean registrationBean = new FilterRegistrationBean();

    // Create the monitoring filter and set its configuration parameters.
    final MonitoringFilter filter = new MonitoringFilter();
    filter.setApplicationType("Spring Boot");

    // Wrap the monitoring filter in the registration bean.
    registrationBean.setFilter(filter);
    registrationBean.setAsyncSupported(true);
    registrationBean.setName("javamelody");
    registrationBean.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);

    // Set the initialization parameter for the monitoring filter.
    for (final Entry<String, String> parameter : properties.getInitParameters().entrySet()) {
        registrationBean.addInitParameter(parameter.getKey(), parameter.getValue());
    }

    // Set the URL patterns to activate the monitoring filter for.
    registrationBean.addUrlPatterns("/*");

    final FilterRegistration filterRegistration = servletContext.getFilterRegistration("javamelody");
    if (filterRegistration != null) {
        // if webapp deployed as war in a container with MonitoringFilter already added by web-fragment.xml,
        // do not try to add it again
        registrationBean.setEnabled(false);
        for (final Map.Entry<String, String> entry : registrationBean.getInitParameters().entrySet()) {
            filterRegistration.setInitParameter(entry.getKey(), entry.getValue());
        }
    }
    return registrationBean;
}

From source file:com.jivesoftware.os.server.http.jetty.jersey.server.JerseyEndpoints.java

@Override
public Handler getHandler(final Server server, String context, String applicationName) {
    ResourceConfig rc = new ResourceConfig().registerClasses(allClasses)
            .register(HttpMethodOverrideFilter.class).register(new JacksonFeature().withMapper(mapper))
            .register(MultiPartFeature.class) // adds support for multi-part API requests
            .registerInstances(allBinders)
            .registerInstances(new InjectableBinder(allInjectables), new AbstractBinder() {
                @Override/*from   w  w w  .ja  va 2  s.  c  om*/
                protected void configure() {
                    bind(server).to(Server.class);
                }
            });

    if (supportCORS) {
        rc.register(CorsContainerResponseFilter.class);
    }

    ServletHolder servletHolder = new ServletHolder(new ServletContainer(rc));
    ServletContextHandler servletContextHandler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
    servletContextHandler.setContextPath(context);
    if (!applicationName.isEmpty()) {
        servletContextHandler.setDisplayName(applicationName);
    }
    servletContextHandler.addServlet(servletHolder, "/");
    servletContextHandler.addFilter(NewRelicRequestFilter.class, "/", EnumSet.of(DispatcherType.REQUEST));

    return servletContextHandler;
}

From source file:io.paradoxical.cassieq.ServiceConfigurator.java

private void enableCors(ServiceConfiguration config, Environment environment) {
    FilterRegistration.Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class);

    filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false,
            environment.getApplicationContext().getContextPath() + "*");
    filter.setInitParameter("allowedOrigins", String.join(",", config.getWeb().getAllowedOrigins())); // allowed origins comma separated
    filter.setInitParameter("allowedHeaders",
            "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
    filter.setInitParameter("allowedMethods", "GET,PUT,POST,DELETE,OPTIONS");
}

From source file:ua.com.rocketlv.spb.Application.java

@Bean
public ServletContextInitializer servletContextInitializer() {
    return (ServletContext servletContext) -> {
        final CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(false);

        // TODO Blog
        servletContext.addFilter("characterEncodingFilter", characterEncodingFilter)
                .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
    };//  ww w  .  j a  v a2s  . c o m
}

From source file:io.apiman.manager.test.server.ManagerApiTestServer.java

/**
 * Configure the web application(s)./*from w w w .j av  a 2 s .  c o  m*/
 * @param handlers
 * @throws Exception
 */
protected void addModulesToJetty(ContextHandlerCollection handlers) throws Exception {
    /* *************
     * APIMan DT API
     * ************* */
    ServletContextHandler apiManServer = new ServletContextHandler(ServletContextHandler.SESSIONS);
    apiManServer.setSecurityHandler(createSecurityHandler());
    apiManServer.setContextPath("/apiman"); //$NON-NLS-1$
    apiManServer.addEventListener(new Listener());
    apiManServer.addEventListener(new BeanManagerResourceBindingListener());
    apiManServer.addEventListener(new ResteasyBootstrap());
    apiManServer.addFilter(DatabaseSeedFilter.class, "/db-seeder", EnumSet.of(DispatcherType.REQUEST)); //$NON-NLS-1$
    apiManServer.addFilter(LocaleFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); //$NON-NLS-1$
    apiManServer.addFilter(SimpleCorsFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); //$NON-NLS-1$
    apiManServer.addFilter(AuthenticationFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); //$NON-NLS-1$
    apiManServer.addFilter(DefaultSecurityContextFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); //$NON-NLS-1$
    ServletHolder resteasyServlet = new ServletHolder(new HttpServletDispatcher());
    resteasyServlet.setInitParameter("javax.ws.rs.Application", JettyDtApiApplication.class.getName()); //$NON-NLS-1$
    apiManServer.addServlet(resteasyServlet, "/*"); //$NON-NLS-1$

    apiManServer.setInitParameter("resteasy.injector.factory", "org.jboss.resteasy.cdi.CdiInjectorFactory"); //$NON-NLS-1$ //$NON-NLS-2$
    apiManServer.setInitParameter("resteasy.scan", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    apiManServer.setInitParameter("resteasy.servlet.mapping.prefix", ""); //$NON-NLS-1$ //$NON-NLS-2$

    // Add the web contexts to jetty
    handlers.addHandler(apiManServer);

    /* *************
     * Mock Gateway (to test publishing of Services from dt to rt)
     * ************* */
    ServletContextHandler mockGatewayServer = new ServletContextHandler(ServletContextHandler.SESSIONS);
    mockGatewayServer.setSecurityHandler(createSecurityHandler());
    mockGatewayServer.setContextPath("/mock-gateway"); //$NON-NLS-1$
    ServletHolder mockGatewayServlet = new ServletHolder(new MockGatewayServlet());
    mockGatewayServer.addServlet(mockGatewayServlet, "/*"); //$NON-NLS-1$

    // Add the web contexts to jetty
    handlers.addHandler(mockGatewayServer);
}