Search in sources :

Example 41 with ServletContextHandler

use of org.eclipse.jetty.servlet.ServletContextHandler in project jetty.project by eclipse.

the class WebSocketUpgradeFilterTest method data.

@Parameterized.Parameters(name = "{0}")
public static List<Object[]> data() {
    final WebSocketCreator infoCreator = (req, resp) -> new InfoSocket();
    List<Object[]> cases = new ArrayList<>();
    // Embedded WSUF.configureContext(), directly app-ws configuration
    cases.add(new Object[] { "wsuf.configureContext/Direct configure", (ServerProvider) () -> {
        Server server1 = new Server();
        ServerConnector connector = new ServerConnector(server1);
        connector.setPort(0);
        server1.addConnector(connector);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        server1.setHandler(context);
        WebSocketUpgradeFilter wsuf = WebSocketUpgradeFilter.configureContext(context);
        wsuf.getFactory().getPolicy().setMaxTextMessageSize(10 * 1024 * 1024);
        wsuf.addMapping("/info/*", infoCreator);
        server1.start();
        return server1;
    } });
    // Embedded WSUF.configureContext(), apply app-ws configuration via attribute
    cases.add(new Object[] { "wsuf.configureContext/Attribute based configure", (ServerProvider) () -> {
        Server server12 = new Server();
        ServerConnector connector = new ServerConnector(server12);
        connector.setPort(0);
        server12.addConnector(connector);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        server12.setHandler(context);
        WebSocketUpgradeFilter.configureContext(context);
        NativeWebSocketConfiguration configuration = (NativeWebSocketConfiguration) context.getServletContext().getAttribute(NativeWebSocketConfiguration.class.getName());
        assertThat("NativeWebSocketConfiguration", configuration, notNullValue());
        configuration.getFactory().getPolicy().setMaxTextMessageSize(10 * 1024 * 1024);
        configuration.addMapping("/info/*", infoCreator);
        server12.start();
        return server12;
    } });
    // Embedded WSUF, added as filter, apply app-ws configuration via attribute
    cases.add(new Object[] { "wsuf/addFilter/Attribute based configure", (ServerProvider) () -> {
        Server server13 = new Server();
        ServerConnector connector = new ServerConnector(server13);
        connector.setPort(0);
        server13.addConnector(connector);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        server13.setHandler(context);
        context.addFilter(WebSocketUpgradeFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        NativeWebSocketConfiguration configuration = new NativeWebSocketConfiguration(context.getServletContext());
        configuration.getFactory().getPolicy().setMaxTextMessageSize(10 * 1024 * 1024);
        configuration.addMapping("/info/*", infoCreator);
        context.setAttribute(NativeWebSocketConfiguration.class.getName(), configuration);
        server13.start();
        return server13;
    } });
    // Embedded WSUF, added as filter, apply app-ws configuration via wsuf constructor
    cases.add(new Object[] { "wsuf/addFilter/WSUF Constructor configure", new ServerProvider() {

        @Override
        public Server newServer() throws Exception {
            Server server = new Server();
            ServerConnector connector = new ServerConnector(server);
            connector.setPort(0);
            server.addConnector(connector);
            ServletContextHandler context = new ServletContextHandler();
            context.setContextPath("/");
            server.setHandler(context);
            NativeWebSocketConfiguration configuration = new NativeWebSocketConfiguration(context.getServletContext());
            configuration.getFactory().getPolicy().setMaxTextMessageSize(10 * 1024 * 1024);
            configuration.addMapping("/info/*", infoCreator);
            context.addBean(configuration, true);
            FilterHolder wsufHolder = new FilterHolder(new WebSocketUpgradeFilter(configuration));
            context.addFilter(wsufHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
            server.start();
            return server;
        }
    } });
    // Embedded WSUF, added as filter, apply app-ws configuration via ServletContextListener
    cases.add(new Object[] { "wsuf.configureContext/ServletContextListener configure", (ServerProvider) () -> {
        Server server14 = new Server();
        ServerConnector connector = new ServerConnector(server14);
        connector.setPort(0);
        server14.addConnector(connector);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        server14.setHandler(context);
        context.addFilter(WebSocketUpgradeFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
        context.addEventListener(new InfoContextListener());
        server14.start();
        return server14;
    } });
    // WSUF from web.xml, SCI active, apply app-ws configuration via ServletContextListener
    cases.add(new Object[] { "wsuf/WebAppContext/web.xml/ServletContextListener", (ServerProvider) () -> {
        File testDir = getNewTestDir();
        WSServer server15 = new WSServer(testDir, "/");
        server15.copyWebInf("wsuf-config-via-listener.xml");
        server15.copyClass(InfoSocket.class);
        server15.copyClass(InfoContextAttributeListener.class);
        server15.start();
        WebAppContext webapp = server15.createWebAppContext();
        server15.deployWebapp(webapp);
        return server15.getServer();
    } });
    // WSUF from web.xml, SCI active, apply app-ws configuration via ServletContextListener with WEB-INF/lib/jetty-http.jar
    cases.add(new Object[] { "wsuf/WebAppContext/web.xml/ServletContextListener/jetty-http.jar", new ServerProvider() {

        @Override
        public Server newServer() throws Exception {
            File testDir = getNewTestDir();
            WSServer server = new WSServer(testDir, "/");
            server.copyWebInf("wsuf-config-via-listener.xml");
            server.copyClass(InfoSocket.class);
            server.copyClass(InfoContextAttributeListener.class);
            // Add a jetty-http.jar to ensure that the classloader constraints
            // and the WebAppClassloader setup is sane and correct
            // The odd version string is present to capture bad regex behavior in Jetty
            server.copyLib(org.eclipse.jetty.http.pathmap.PathSpec.class, "jetty-http-9.99.999.jar");
            server.start();
            WebAppContext webapp = server.createWebAppContext();
            server.deployWebapp(webapp);
            return server.getServer();
        }
    } });
    // WSUF from web.xml, SCI active, apply app-ws configuration via Servlet.init
    cases.add(new Object[] { "wsuf/WebAppContext/web.xml/Servlet.init", (ServerProvider) () -> {
        File testDir = getNewTestDir();
        WSServer server16 = new WSServer(testDir, "/");
        server16.copyWebInf("wsuf-config-via-servlet-init.xml");
        server16.copyClass(InfoSocket.class);
        server16.copyClass(InfoServlet.class);
        server16.start();
        WebAppContext webapp = server16.createWebAppContext();
        server16.deployWebapp(webapp);
        return server16.getServer();
    } });
    // xml based, wsuf, on alternate url-pattern and config attribute location
    cases.add(new Object[] { "wsuf/WebAppContext/web.xml/ServletContextListener/alt-config", (ServerProvider) () -> {
        File testDir = getNewTestDir();
        WSServer server17 = new WSServer(testDir, "/");
        server17.copyWebInf("wsuf-alt-config-via-listener.xml");
        server17.copyClass(InfoSocket.class);
        server17.copyClass(InfoContextAltAttributeListener.class);
        server17.start();
        WebAppContext webapp = server17.createWebAppContext();
        server17.deployWebapp(webapp);
        return server17.getServer();
    } });
    return cases;
}
Also used : ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) MavenTestingUtils(org.eclipse.jetty.toolchain.test.MavenTestingUtils) RunWith(org.junit.runner.RunWith) ArrayList(java.util.ArrayList) Assert.assertThat(org.junit.Assert.assertThat) WebSocketFrame(org.eclipse.jetty.websocket.common.WebSocketFrame) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) TextFrame(org.eclipse.jetty.websocket.common.frames.TextFrame) URI(java.net.URI) Server(org.eclipse.jetty.server.Server) EnumSet(java.util.EnumSet) Parameterized(org.junit.runners.Parameterized) EventQueue(org.eclipse.jetty.toolchain.test.EventQueue) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Test(org.junit.Test) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) ServerConnector(org.eclipse.jetty.server.ServerConnector) DispatcherType(javax.servlet.DispatcherType) BlockheadClient(org.eclipse.jetty.websocket.common.test.BlockheadClient) Matchers.containsString(org.hamcrest.Matchers.containsString) WebSocketCreator(org.eclipse.jetty.websocket.servlet.WebSocketCreator) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) Server(org.eclipse.jetty.server.Server) ArrayList(java.util.ArrayList) ServerConnector(org.eclipse.jetty.server.ServerConnector) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) WebSocketCreator(org.eclipse.jetty.websocket.servlet.WebSocketCreator) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) File(java.io.File)

Example 42 with ServletContextHandler

use of org.eclipse.jetty.servlet.ServletContextHandler in project jetty.project by eclipse.

the class SimpleServletServer method start.

public void start() throws Exception {
    // Configure Server
    server = new Server();
    if (ssl) {
        // HTTP Configuration
        HttpConfiguration http_config = new HttpConfiguration();
        http_config.setSecureScheme("https");
        http_config.setSecurePort(0);
        http_config.setOutputBufferSize(32768);
        http_config.setRequestHeaderSize(8192);
        http_config.setResponseHeaderSize(8192);
        http_config.setSendServerVersion(true);
        http_config.setSendDateHeader(false);
        sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(MavenTestingUtils.getTestResourceFile("keystore").getAbsolutePath());
        sslContextFactory.setKeyStorePassword("storepwd");
        sslContextFactory.setKeyManagerPassword("keypwd");
        sslContextFactory.setExcludeCipherSuites("SSL_RSA_WITH_DES_CBC_SHA", "SSL_DHE_RSA_WITH_DES_CBC_SHA", "SSL_DHE_DSS_WITH_DES_CBC_SHA", "SSL_RSA_EXPORT_WITH_RC4_40_MD5", "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
        // SSL HTTP Configuration
        HttpConfiguration https_config = new HttpConfiguration(http_config);
        https_config.addCustomizer(new SecureRequestCustomizer());
        // SSL Connector
        connector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(https_config));
        connector.setPort(0);
    } else {
        // Basic HTTP connector
        connector = new ServerConnector(server);
        connector.setPort(0);
    }
    server.addConnector(connector);
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    configureServletContextHandler(context);
    server.setHandler(context);
    // Serve capture servlet
    context.addServlet(new ServletHolder(servlet), "/*");
    // Start Server
    server.start();
    // Establish the Server URI
    String host = connector.getHost();
    if (host == null) {
        host = "localhost";
    }
    int port = connector.getLocalPort();
    serverUri = new URI(String.format("%s://%s:%d/", ssl ? "wss" : "ws", host, port));
    // Some debugging
    if (LOG.isDebugEnabled()) {
        LOG.debug(server.dump());
    }
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) URI(java.net.URI)

Example 43 with ServletContextHandler

use of org.eclipse.jetty.servlet.ServletContextHandler in project jetty.project by eclipse.

the class RemoveSessionTest method testRemoveSession.

@Test
public void testRemoveSession() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    DefaultSessionCacheFactory cacheFactory = new DefaultSessionCacheFactory();
    cacheFactory.setEvictionPolicy(SessionCache.NEVER_EVICT);
    SessionDataStoreFactory storeFactory = new TestSessionDataStoreFactory();
    TestServer server = new TestServer(0, -1, -1, cacheFactory, storeFactory);
    ServletContextHandler context = server.addContext(contextPath);
    context.addServlet(TestServlet.class, servletMapping);
    TestEventListener testListener = new TestEventListener();
    context.getSessionHandler().addEventListener(testListener);
    SessionHandler m = context.getSessionHandler();
    try {
        server.start();
        int port = server.getPort();
        HttpClient client = new HttpClient();
        client.start();
        try {
            ContentResponse response = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            String sessionCookie = response.getHeaders().get("Set-Cookie");
            assertTrue(sessionCookie != null);
            // Mangle the cookie, replacing Path with $Path, etc.
            sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
            //ensure sessionCreated listener is called
            assertTrue(testListener.isCreated());
            assertEquals(1, m.getSessionsCreated());
            assertEquals(1, ((DefaultSessionCache) m.getSessionCache()).getSessionsMax());
            assertEquals(1, ((DefaultSessionCache) m.getSessionCache()).getSessionsTotal());
            //now delete the session
            Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=delete");
            request.header("Cookie", sessionCookie);
            response = request.send();
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            //ensure sessionDestroyed listener is called
            assertTrue(testListener.isDestroyed());
            assertEquals(0, ((DefaultSessionCache) m.getSessionCache()).getSessionsCurrent());
            assertEquals(1, ((DefaultSessionCache) m.getSessionCache()).getSessionsMax());
            assertEquals(1, ((DefaultSessionCache) m.getSessionCache()).getSessionsTotal());
            //check the session is not persisted any more
            assertFalse(m.getSessionCache().getSessionDataStore().exists(TestServer.extractSessionId(sessionCookie)));
            // The session is not there anymore, even if we present an old cookie
            request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=check");
            request.header("Cookie", sessionCookie);
            response = request.send();
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            assertEquals(0, ((DefaultSessionCache) m.getSessionCache()).getSessionsCurrent());
            assertEquals(1, ((DefaultSessionCache) m.getSessionCache()).getSessionsMax());
            assertEquals(1, ((DefaultSessionCache) m.getSessionCache()).getSessionsTotal());
        } finally {
            client.stop();
        }
    } finally {
        server.stop();
    }
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpClient(org.eclipse.jetty.client.HttpClient) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Test(org.junit.Test)

Example 44 with ServletContextHandler

use of org.eclipse.jetty.servlet.ServletContextHandler in project jetty.project by eclipse.

the class ExampleServer method main.

public static void main(String[] args) throws Exception {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(8080);
    server.setConnectors(new Connector[] { connector });
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(HelloServlet.class, "/hello");
    context.addServlet(AsyncEchoServlet.class, "/echo/*");
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
    server.setHandler(handlers);
    server.start();
    server.join();
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) Server(org.eclipse.jetty.server.Server) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler)

Example 45 with ServletContextHandler

use of org.eclipse.jetty.servlet.ServletContextHandler in project jetty.project by eclipse.

the class RewriteServer method main.

public static void main(String[] args) throws Exception {
    Server server = new Server(8080);
    HttpConfiguration config = server.getConnectors()[0].getConnectionFactory(HttpConnectionFactory.class).getHttpConfiguration();
    RewriteCustomizer rewrite = new RewriteCustomizer();
    config.addCustomizer(rewrite);
    rewrite.addRule(new CompactPathRule());
    rewrite.addRule(new RewriteRegexRule("(.*)foo(.*)", "$1FOO$2"));
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(DumpServlet.class, "/*");
    server.start();
    server.join();
}
Also used : CompactPathRule(org.eclipse.jetty.rewrite.handler.CompactPathRule) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) RewriteRegexRule(org.eclipse.jetty.rewrite.handler.RewriteRegexRule) RewriteCustomizer(org.eclipse.jetty.rewrite.RewriteCustomizer) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Aggregations

ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)385 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)249 Server (org.eclipse.jetty.server.Server)216 ServerConnector (org.eclipse.jetty.server.ServerConnector)98 Test (org.junit.Test)70 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)55 IOException (java.io.IOException)42 HttpClient (org.eclipse.jetty.client.HttpClient)39 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)39 HttpServletRequest (javax.servlet.http.HttpServletRequest)38 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)37 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)37 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)32 Connector (org.eclipse.jetty.server.Connector)29 Request (org.eclipse.jetty.client.api.Request)27 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)25 ServletContainer (org.glassfish.jersey.servlet.ServletContainer)24 ServletException (javax.servlet.ServletException)22 ContextHandlerCollection (org.eclipse.jetty.server.handler.ContextHandlerCollection)22 HandlerCollection (org.eclipse.jetty.server.handler.HandlerCollection)22