Search in sources :

Example 26 with ServletContextHandler

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

the class IdleSessionTest method testSessionIdle.

/**
     * @throws Exception
     */
@Test
public void testSessionIdle() throws Exception {
    String contextPath = "";
    String servletMapping = "/server";
    int inactivePeriod = 20;
    int scavengePeriod = 3;
    int evictionSec = 5;
    DefaultSessionCacheFactory cacheFactory = new DefaultSessionCacheFactory();
    cacheFactory.setEvictionPolicy(evictionSec);
    SessionDataStoreFactory storeFactory = new TestSessionDataStoreFactory();
    _server1 = new TestServer(0, inactivePeriod, scavengePeriod, cacheFactory, storeFactory);
    ServletHolder holder = new ServletHolder(_servlet);
    ServletContextHandler contextHandler = _server1.addContext(contextPath);
    contextHandler.addServlet(holder, servletMapping);
    _server1.start();
    int port1 = _server1.getPort();
    try (StacklessLogging stackless = new StacklessLogging(Log.getLogger("org.eclipse.jetty.server.session"))) {
        HttpClient client = new HttpClient();
        client.start();
        String url = "http://localhost:" + port1 + contextPath + servletMapping;
        //make a request to set up a session on the server
        ContentResponse response = client.GET(url + "?action=init");
        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=");
        //and wait until the session should be idled out
        pause(evictionSec * 3);
        //check that the session has been idled
        String id = TestServer.extractSessionId(sessionCookie);
        assertFalse(contextHandler.getSessionHandler().getSessionCache().contains(id));
        assertTrue(contextHandler.getSessionHandler().getSessionCache().getSessionDataStore().exists(id));
        //make another request to de-idle the session
        Request request = client.newRequest(url + "?action=test");
        request.getHeaders().add("Cookie", sessionCookie);
        ContentResponse response2 = request.send();
        assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
        //check session de-idled
        assertTrue(contextHandler.getSessionHandler().getSessionCache().contains(id));
        //wait again for the session to be idled
        pause(evictionSec * 3);
        //check that it is
        assertFalse(contextHandler.getSessionHandler().getSessionCache().contains(id));
        assertTrue(contextHandler.getSessionHandler().getSessionCache().getSessionDataStore().exists(id));
        //While idle, take some action to ensure that a deidle won't work, like
        //deleting the sessions in the store
        ((TestSessionDataStore) contextHandler.getSessionHandler().getSessionCache().getSessionDataStore())._map.clear();
        //make a request
        request = client.newRequest(url + "?action=testfail");
        request.getHeaders().add("Cookie", sessionCookie);
        response2 = request.send();
        assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
        //Test trying to de-idle an expired session (ie before the scavenger can get to it)
        //make a request to set up a session on the server
        response = client.GET(url + "?action=init");
        assertEquals(HttpServletResponse.SC_OK, response.getStatus());
        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=");
        id = TestServer.extractSessionId(sessionCookie);
        //and wait until the session should be idled out
        pause(evictionSec * 3);
        //stop the scavenger
        if (_server1.getHouseKeeper() != null)
            _server1.getHouseKeeper().stop();
        //check that the session is idle
        assertFalse(contextHandler.getSessionHandler().getSessionCache().contains(id));
        assertTrue(contextHandler.getSessionHandler().getSessionCache().getSessionDataStore().exists(id));
        //wait until the session should be expired
        pause(inactivePeriod + (3 * scavengePeriod));
        //make another request to de-idle the session
        request = client.newRequest(url + "?action=testfail");
        request.getHeaders().add("Cookie", sessionCookie);
        response2 = request.send();
        assertEquals(HttpServletResponse.SC_OK, response2.getStatus());
        assertFalse(contextHandler.getSessionHandler().getSessionCache().contains(id));
        assertFalse(contextHandler.getSessionHandler().getSessionCache().getSessionDataStore().exists(id));
    } finally {
        _server1.stop();
    }
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) HttpClient(org.eclipse.jetty.client.HttpClient) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Test(org.junit.Test)

Example 27 with ServletContextHandler

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

the class ProxyTest method startProxy.

private void startProxy(HttpServlet proxyServlet, Map<String, String> initParams) throws Exception {
    QueuedThreadPool proxyPool = new QueuedThreadPool();
    proxyPool.setName("proxy");
    proxy = new Server(proxyPool);
    HttpConfiguration configuration = new HttpConfiguration();
    configuration.setSendDateHeader(false);
    configuration.setSendServerVersion(false);
    String value = initParams.get("outputBufferSize");
    if (value != null)
        configuration.setOutputBufferSize(Integer.valueOf(value));
    proxyConnector = new ServerConnector(proxy, new HTTP2ServerConnectionFactory(configuration));
    proxy.addConnector(proxyConnector);
    ServletContextHandler proxyContext = new ServletContextHandler(proxy, "/", true, false);
    ServletHolder proxyServletHolder = new ServletHolder(proxyServlet);
    proxyServletHolder.setInitParameters(initParams);
    proxyContext.addServlet(proxyServletHolder, "/*");
    proxy.start();
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) Server(org.eclipse.jetty.server.Server) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) HTTP2ServerConnectionFactory(org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler)

Example 28 with ServletContextHandler

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

the class AsyncServletTest method testStartAsyncThenServerIdleTimeout.

private void testStartAsyncThenServerIdleTimeout(long sessionTimeout, long streamTimeout) throws Exception {
    prepareServer(new HTTP2ServerConnectionFactory(new HttpConfiguration()) {

        @Override
        protected ServerSessionListener newSessionListener(Connector connector, EndPoint endPoint) {
            return new HTTPServerSessionListener(connector, endPoint) {

                @Override
                public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
                    stream.setIdleTimeout(streamTimeout);
                    return super.onNewStream(stream, frame);
                }
            };
        }
    });
    connector.setIdleTimeout(sessionTimeout);
    ServletContextHandler context = new ServletContextHandler(server, "/");
    long timeout = Math.min(sessionTimeout, streamTimeout);
    CountDownLatch errorLatch = new CountDownLatch(1);
    context.addServlet(new ServletHolder(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            AsyncContext asyncContext = (AsyncContext) request.getAttribute(AsyncContext.class.getName());
            if (asyncContext == null) {
                AsyncContext context = request.startAsync();
                context.setTimeout(2 * timeout);
                request.setAttribute(AsyncContext.class.getName(), context);
                context.addListener(new AsyncListener() {

                    @Override
                    public void onComplete(AsyncEvent event) throws IOException {
                    }

                    @Override
                    public void onTimeout(AsyncEvent event) throws IOException {
                        event.getAsyncContext().complete();
                    }

                    @Override
                    public void onError(AsyncEvent event) throws IOException {
                        errorLatch.countDown();
                    }

                    @Override
                    public void onStartAsync(AsyncEvent event) throws IOException {
                    }
                });
            } else {
                throw new ServletException();
            }
        }
    }), servletPath + "/*");
    server.start();
    prepareClient();
    client.start();
    Session session = newClient(new Session.Listener.Adapter());
    HttpFields fields = new HttpFields();
    MetaData.Request metaData = newRequest("GET", fields);
    HeadersFrame frame = new HeadersFrame(metaData, null, true);
    CountDownLatch clientLatch = new CountDownLatch(1);
    session.newStream(frame, new Promise.Adapter<>(), new Stream.Listener.Adapter() {

        @Override
        public void onHeaders(Stream stream, HeadersFrame frame) {
            MetaData.Response response = (MetaData.Response) frame.getMetaData();
            if (response.getStatus() == HttpStatus.OK_200 && frame.isEndStream())
                clientLatch.countDown();
        }
    });
    // When the server idle times out, but the request has been dispatched
    // then the server must ignore the idle timeout as per Servlet semantic.
    Assert.assertFalse(errorLatch.await(2 * timeout, TimeUnit.MILLISECONDS));
    Assert.assertTrue(clientLatch.await(2 * timeout, TimeUnit.MILLISECONDS));
}
Also used : Connector(org.eclipse.jetty.server.Connector) AsyncListener(javax.servlet.AsyncListener) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) AsyncContext(javax.servlet.AsyncContext) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) EndPoint(org.eclipse.jetty.io.EndPoint) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Stream(org.eclipse.jetty.http2.api.Stream) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) HTTP2ServerConnectionFactory(org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncEvent(javax.servlet.AsyncEvent) HttpServletResponse(javax.servlet.http.HttpServletResponse) Promise(org.eclipse.jetty.util.Promise) FuturePromise(org.eclipse.jetty.util.FuturePromise) AsyncListener(javax.servlet.AsyncListener) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Session(org.eclipse.jetty.http2.api.Session)

Example 29 with ServletContextHandler

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

the class TestMemcachedSessions method testMemcached.

@Test
public void testMemcached() throws Exception {
    String contextPath = "/";
    Server server = new Server(0);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.setResourceBase(System.getProperty("java.io.tmpdir"));
    server.setHandler(context);
    NullSessionCache dsc = new NullSessionCache(context.getSessionHandler());
    dsc.setSessionDataStore(new CachingSessionDataStore(new MemcachedSessionDataMap("localhost", "11211"), new NullSessionDataStore()));
    context.getSessionHandler().setSessionCache(dsc);
    // Add a test servlet
    ServletHolder h = new ServletHolder();
    h.setServlet(new TestServlet());
    context.addServlet(h, "/");
    try {
        server.start();
        int port = ((NetworkConnector) server.getConnectors()[0]).getLocalPort();
        HttpClient client = new HttpClient();
        client.start();
        try {
            int value = 42;
            ContentResponse response = client.GET("http://localhost:" + port + contextPath + "?action=set&value=" + value);
            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=");
            String resp = response.getContentAsString();
            assertEquals(resp.trim(), String.valueOf(value));
            // Be sure the session value is still there
            Request request = client.newRequest("http://localhost:" + port + contextPath + "?action=get");
            request.header("Cookie", sessionCookie);
            response = request.send();
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            resp = response.getContentAsString();
            assertEquals(String.valueOf(value), resp.trim());
            //Delete the session
            request = client.newRequest("http://localhost:" + port + contextPath + "?action=del");
            request.header("Cookie", sessionCookie);
            response = request.send();
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            //Check that the session is gone
            request = client.newRequest("http://localhost:" + port + contextPath + "?action=get");
            request.header("Cookie", sessionCookie);
            response = request.send();
            assertEquals(HttpServletResponse.SC_OK, response.getStatus());
            resp = response.getContentAsString();
            assertEquals("No session", resp.trim());
        } finally {
            client.stop();
        }
    } finally {
        server.stop();
    }
}
Also used : Server(org.eclipse.jetty.server.Server) CachingSessionDataStore(org.eclipse.jetty.server.session.CachingSessionDataStore) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpClient(org.eclipse.jetty.client.HttpClient) NullSessionDataStore(org.eclipse.jetty.server.session.NullSessionDataStore) NetworkConnector(org.eclipse.jetty.server.NetworkConnector) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) Test(org.junit.Test)

Example 30 with ServletContextHandler

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

the class ThreadStarvationTest method testDefaultServletSuccess.

@Test
@Slow
public void testDefaultServletSuccess() throws Exception {
    int maxThreads = 10;
    QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads, maxThreads);
    threadPool.setDetailedDump(true);
    _server = new Server(threadPool);
    // Prepare a big file to download.
    File directory = MavenTestingUtils.getTargetTestingDir();
    Files.createDirectories(directory.toPath());
    String resourceName = "resource.bin";
    Path resourcePath = Paths.get(directory.getPath(), resourceName);
    try (OutputStream output = Files.newOutputStream(resourcePath, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
        byte[] chunk = new byte[1024];
        Arrays.fill(chunk, (byte) 'X');
        chunk[chunk.length - 2] = '\r';
        chunk[chunk.length - 1] = '\n';
        for (int i = 0; i < 256 * 1024; ++i) output.write(chunk);
    }
    final CountDownLatch writePending = new CountDownLatch(1);
    ServerConnector connector = new ServerConnector(_server, 0, 1) {

        @Override
        protected ChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException {
            return new SocketChannelEndPoint(channel, selectSet, key, getScheduler()) {

                @Override
                protected void onIncompleteFlush() {
                    super.onIncompleteFlush();
                    writePending.countDown();
                }
            };
        }
    };
    connector.setIdleTimeout(Long.MAX_VALUE);
    _server.addConnector(connector);
    ServletContextHandler context = new ServletContextHandler(_server, "/");
    context.setResourceBase(directory.toURI().toString());
    context.addServlet(DefaultServlet.class, "/*").setAsyncSupported(false);
    _server.setHandler(context);
    _server.start();
    List<Socket> sockets = new ArrayList<>();
    for (int i = 0; i < maxThreads * 2; ++i) {
        Socket socket = new Socket("localhost", connector.getLocalPort());
        sockets.add(socket);
        OutputStream output = socket.getOutputStream();
        String request = "" + "GET /" + resourceName + " HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n";
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        Thread.sleep(100);
    }
    // Wait for a the servlet to block.
    Assert.assertTrue(writePending.await(5, TimeUnit.SECONDS));
    long expected = Files.size(resourcePath);
    byte[] buffer = new byte[48 * 1024];
    List<Exchanger<Long>> totals = new ArrayList<>();
    for (Socket socket : sockets) {
        final Exchanger<Long> x = new Exchanger<>();
        totals.add(x);
        final InputStream input = socket.getInputStream();
        new Thread() {

            @Override
            public void run() {
                long total = 0;
                try {
                    // look for CRLFCRLF
                    StringBuilder header = new StringBuilder();
                    int state = 0;
                    while (state < 4 && header.length() < 2048) {
                        int ch = input.read();
                        if (ch < 0)
                            break;
                        header.append((char) ch);
                        switch(state) {
                            case 0:
                                if (ch == '\r')
                                    state = 1;
                                break;
                            case 1:
                                if (ch == '\n')
                                    state = 2;
                                else
                                    state = 0;
                                break;
                            case 2:
                                if (ch == '\r')
                                    state = 3;
                                else
                                    state = 0;
                                break;
                            case 3:
                                if (ch == '\n')
                                    state = 4;
                                else
                                    state = 0;
                                break;
                        }
                    }
                    while (total < expected) {
                        int read = input.read(buffer);
                        if (read < 0)
                            break;
                        total += read;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        x.exchange(total);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
    for (Exchanger<Long> x : totals) {
        Long total = x.exchange(-1L, 10000, TimeUnit.SECONDS);
        Assert.assertEquals(expected, total.longValue());
    }
    // We could read everything, good.
    for (Socket socket : sockets) socket.close();
}
Also used : ManagedSelector(org.eclipse.jetty.io.ManagedSelector) SocketChannel(java.nio.channels.SocketChannel) Server(org.eclipse.jetty.server.Server) Exchanger(java.util.concurrent.Exchanger) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) ServerConnector(org.eclipse.jetty.server.ServerConnector) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) DefaultServlet(org.eclipse.jetty.servlet.DefaultServlet) Path(java.nio.file.Path) SelectionKey(java.nio.channels.SelectionKey) InputStream(java.io.InputStream) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelEndPoint(org.eclipse.jetty.io.ChannelEndPoint) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) File(java.io.File) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint) Socket(java.net.Socket) Test(org.junit.Test) Slow(org.eclipse.jetty.toolchain.test.annotation.Slow)

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