Search in sources :

Example 11 with DispatcherType

use of javax.servlet.DispatcherType in project spring-boot by spring-projects.

the class SecurityAutoConfigurationTests method customFilterDispatcherTypes.

@Test
public void customFilterDispatcherTypes() {
    this.context = new AnnotationConfigWebApplicationContext();
    this.context.setServletContext(new MockServletContext());
    this.context.register(SecurityAutoConfiguration.class, SecurityFilterAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
    EnvironmentTestUtils.addEnvironment(this.context, "security.filter-dispatcher-types:INCLUDE,ERROR");
    this.context.refresh();
    DelegatingFilterProxyRegistrationBean bean = this.context.getBean("securityFilterChainRegistration", DelegatingFilterProxyRegistrationBean.class);
    @SuppressWarnings("unchecked") EnumSet<DispatcherType> dispatcherTypes = (EnumSet<DispatcherType>) ReflectionTestUtils.getField(bean, "dispatcherTypes");
    assertThat(dispatcherTypes).containsOnly(DispatcherType.INCLUDE, DispatcherType.ERROR);
}
Also used : DelegatingFilterProxyRegistrationBean(org.springframework.boot.web.servlet.DelegatingFilterProxyRegistrationBean) EnumSet(java.util.EnumSet) DispatcherType(javax.servlet.DispatcherType) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) MockServletContext(org.springframework.mock.web.MockServletContext) Test(org.junit.Test)

Example 12 with DispatcherType

use of javax.servlet.DispatcherType in project felix by apache.

the class AsyncTest method testAsyncServletWithDispatchOk.

/**
 * Tests that we can use an asynchronous servlet (introduced in Servlet 3.0 spec) using the dispatching functionality.
 */
@Test
public void testAsyncServletWithDispatchOk() throws Exception {
    CountDownLatch initLatch = new CountDownLatch(1);
    CountDownLatch destroyLatch = new CountDownLatch(1);
    TestServlet servlet = new TestServlet(initLatch, destroyLatch) {

        private static final long serialVersionUID = 1L;

        @Override
        protected void doGet(final HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            DispatcherType dispatcherType = req.getDispatcherType();
            if (DispatcherType.REQUEST == dispatcherType) {
                final AsyncContext asyncContext = req.startAsync(req, resp);
                asyncContext.start(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            // Simulate a long running process...
                            Thread.sleep(1000);
                            asyncContext.getRequest().setAttribute("msg", "Hello Async world!");
                            asyncContext.dispatch();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                });
            } else if (DispatcherType.ASYNC == dispatcherType) {
                String response = (String) req.getAttribute("msg");
                resp.setStatus(SC_OK);
                resp.getWriter().printf(response);
                resp.flushBuffer();
            }
        }
    };
    register("/test", servlet);
    assertTrue(initLatch.await(5, TimeUnit.SECONDS));
    assertContent("Hello Async world!", createURL("/test"));
    unregister("/test");
    assertTrue(destroyLatch.await(5, TimeUnit.SECONDS));
    assertResponseCode(SC_NOT_FOUND, createURL("/test"));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) CountDownLatch(java.util.concurrent.CountDownLatch) DispatcherType(javax.servlet.DispatcherType) Test(org.junit.Test)

Example 13 with DispatcherType

use of javax.servlet.DispatcherType in project felix by apache.

the class JettyServiceTest method testInitBundleContextDeployIT.

/**
 * Tests to ensure the osgi-bundlecontext is available for init methods.
 *
 * @throws MalformedURLException
 * @throws InterruptedException
 */
@Test
public void testInitBundleContextDeployIT() throws Exception {
    // Setup mocks
    Deployment mockDeployment = mock(Deployment.class);
    Bundle mockBundle = mock(Bundle.class);
    BundleContext mockBundleContext = mock(BundleContext.class);
    // Setup behaviors
    when(mockDeployment.getBundle()).thenReturn(mockBundle);
    final org.osgi.framework.Filter f = mock(org.osgi.framework.Filter.class);
    when(f.toString()).thenReturn("(prop=*)");
    when(mockBundleContext.createFilter(anyString())).thenReturn(f);
    when(mockBundle.getBundleContext()).thenReturn(mockBundleContext);
    when(mockBundle.getSymbolicName()).thenReturn("test");
    when(mockBundle.getVersion()).thenReturn(new Version("0.0.1"));
    Dictionary<String, String> headerProperties = new Hashtable<String, String>();
    headerProperties.put("Web-ContextPath", "test");
    when(mockBundle.getHeaders()).thenReturn(headerProperties);
    when(mockDeployment.getContextPath()).thenReturn("test");
    when(mockBundle.getEntry("/")).thenReturn(new URL("http://www.apache.com"));
    when(mockBundle.getState()).thenReturn(Bundle.ACTIVE);
    EnumSet<DispatcherType> dispatcherSet = EnumSet.allOf(DispatcherType.class);
    dispatcherSet.add(DispatcherType.REQUEST);
    WebAppBundleContext webAppBundleContext = new WebAppBundleContext("/", mockBundle, this.getClass().getClassLoader());
    final CountDownLatch testLatch = new CountDownLatch(2);
    // Add a Filter to test whether the osgi-bundlecontext is available at init
    webAppBundleContext.addServlet(new ServletHolder(new Servlet() {

        @Override
        public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        // Do Nothing
        }

        @Override
        public void init(ServletConfig config) throws ServletException {
            ServletContext context = config.getServletContext();
            assertNotNull(context.getAttribute(OSGI_BUNDLECONTEXT));
            testLatch.countDown();
        }

        @Override
        public String getServletInfo() {
            return null;
        }

        @Override
        public ServletConfig getServletConfig() {
            return null;
        }

        @Override
        public void destroy() {
        // Do Nothing
        }
    }), "/test1");
    webAppBundleContext.addFilter(new FilterHolder(new Filter() {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            ServletContext context = filterConfig.getServletContext();
            assertNotNull(context.getAttribute(OSGI_BUNDLECONTEXT));
            testLatch.countDown();
        }

        @Override
        public void doFilter(ServletRequest arg0, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Do Nothing
        }

        @Override
        public void destroy() {
        // Do Nothing
        }
    }), "/test2", dispatcherSet);
    jettyService.deploy(mockDeployment, webAppBundleContext);
    // Fail if takes too long.
    if (!testLatch.await(10, TimeUnit.SECONDS)) {
        fail("Test Was not asserted");
    }
}
Also used : ServletRequest(javax.servlet.ServletRequest) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) FilterChain(javax.servlet.FilterChain) Deployment(org.apache.felix.http.jetty.internal.JettyService.Deployment) Matchers.anyString(org.mockito.Matchers.anyString) URL(java.net.URL) Version(org.osgi.framework.Version) Servlet(javax.servlet.Servlet) ServletContext(javax.servlet.ServletContext) FilterConfig(javax.servlet.FilterConfig) DispatcherType(javax.servlet.DispatcherType) ServletResponse(javax.servlet.ServletResponse) Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) ServletConfig(javax.servlet.ServletConfig) CountDownLatch(java.util.concurrent.CountDownLatch) Filter(javax.servlet.Filter) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 14 with DispatcherType

use of javax.servlet.DispatcherType in project dropwizard-guicey by xvik.

the class WebFilterInstaller method configure.

private void configure(final ServletEnvironment environment, final Filter filter, final String name, final WebFilter annotation) {
    final FilterRegistration.Dynamic mapping = environment.addFilter(name, filter);
    final EnumSet<DispatcherType> dispatcherTypes = EnumSet.copyOf(Arrays.asList(annotation.dispatcherTypes()));
    if (annotation.servletNames().length > 0) {
        mapping.addMappingForServletNames(dispatcherTypes, false, annotation.servletNames());
    } else {
        final String[] urlPatterns = annotation.urlPatterns().length > 0 ? annotation.urlPatterns() : annotation.value();
        mapping.addMappingForUrlPatterns(dispatcherTypes, false, urlPatterns);
    }
    if (annotation.initParams().length > 0) {
        for (WebInitParam param : annotation.initParams()) {
            mapping.setInitParameter(param.name(), param.value());
        }
    }
    mapping.setAsyncSupported(annotation.asyncSupported());
}
Also used : WebInitParam(javax.servlet.annotation.WebInitParam) DispatcherType(javax.servlet.DispatcherType) FilterRegistration(javax.servlet.FilterRegistration)

Example 15 with DispatcherType

use of javax.servlet.DispatcherType in project fabric8 by fabric8io.

the class Servers method startServer.

public static Server startServer(String appName, Function<ServletContextHandler, Void> contextCallback, String defaultPort) throws Exception {
    String port = Systems.getEnvVarOrSystemProperty("HTTP_PORT", "HTTP_PORT", defaultPort);
    Integer num = Integer.parseInt(port);
    String service = Systems.getEnvVarOrSystemProperty("WEB_CONTEXT_PATH", "WEB_CONTEXT_PATH", "");
    String servicesPath = "cxf/servicesList";
    String servletContextPath = "/" + service;
    ManagedApi.setSingletonCxfServletContext(servletContextPath);
    String url = "http://localhost:" + port + servletContextPath;
    if (!url.endsWith("/")) {
        url += "/";
    }
    System.out.println();
    System.out.println("-------------------------------------------------------------");
    System.out.println(appName + " is now running at: " + url);
    System.out.println("-------------------------------------------------------------");
    System.out.println();
    final Server server = new Server(num);
    // Register and map the dispatcher servlet
    final ServletHolder servletHolder = new ServletHolder(new CXFCdiServlet());
    // change default service list URI
    servletHolder.setInitParameter("service-list-path", "/" + servicesPath);
    final ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addEventListener(new Listener());
    context.addEventListener(new BeanManagerResourceBindingListener());
    String servletPath = "/*";
    if (Strings.isNotBlank(service)) {
        servletPath = servletContextPath + "/*";
    }
    context.addServlet(servletHolder, servletPath);
    server.setHandler(context);
    EnumSet<DispatcherType> dispatches = EnumSet.allOf(DispatcherType.class);
    context.addFilter(RestCorsFilter.class, "/*", dispatches);
    if (contextCallback != null) {
        contextCallback.apply(context);
    }
    server.start();
    return server;
}
Also used : Listener(org.jboss.weld.environment.servlet.Listener) BeanManagerResourceBindingListener(org.jboss.weld.environment.servlet.BeanManagerResourceBindingListener) Server(org.eclipse.jetty.server.Server) BeanManagerResourceBindingListener(org.jboss.weld.environment.servlet.BeanManagerResourceBindingListener) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) DispatcherType(javax.servlet.DispatcherType) CXFCdiServlet(org.apache.cxf.cdi.CXFCdiServlet)

Aggregations

DispatcherType (javax.servlet.DispatcherType)45 ServletContext (javax.servlet.ServletContext)6 ServletRequest (javax.servlet.ServletRequest)6 IOException (java.io.IOException)5 FilterMap (org.apache.catalina.deploy.FilterMap)5 ServletResponse (javax.servlet.ServletResponse)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 Server (org.eclipse.jetty.server.Server)4 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)4 AnnotationConfigWebApplicationContext (org.springframework.web.context.support.AnnotationConfigWebApplicationContext)4 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)3 File (java.io.File)3 WebInitParam (javax.servlet.annotation.WebInitParam)3 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)3 Test (org.junit.Test)3 ServletFilterMapping (com.sun.enterprise.deployment.web.ServletFilterMapping)2 ServletContainer (com.sun.jersey.spi.container.servlet.ServletContainer)2 ManagedFilter (io.undertow.servlet.core.ManagedFilter)2 ArrayList (java.util.ArrayList)2