Search in sources :

Example 11 with Request

use of org.eclipse.jetty.server.Request in project jetty.project by eclipse.

the class StatisticsHandlerTest method testSuspendComplete.

@Test
public void testSuspendComplete() throws Exception {
    final long dispatchTime = 10;
    final AtomicReference<AsyncContext> asyncHolder = new AtomicReference<>();
    final CyclicBarrier[] barrier = { new CyclicBarrier(2), new CyclicBarrier(2) };
    final CountDownLatch latch = new CountDownLatch(1);
    _statsHandler.setHandler(new AbstractHandler() {

        @Override
        public void handle(String path, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException {
            request.setHandled(true);
            try {
                barrier[0].await();
                Thread.sleep(dispatchTime);
                if (asyncHolder.get() == null) {
                    AsyncContext async = request.startAsync();
                    asyncHolder.set(async);
                }
            } catch (Exception x) {
                throw new ServletException(x);
            } finally {
                try {
                    barrier[1].await();
                } catch (Exception ignored) {
                }
            }
        }
    });
    _server.start();
    String request = "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n";
    _connector.executeRequest(request);
    barrier[0].await();
    assertEquals(1, _statistics.getConnections());
    assertEquals(1, _statsHandler.getRequests());
    assertEquals(1, _statsHandler.getRequestsActive());
    assertEquals(1, _statsHandler.getDispatched());
    assertEquals(1, _statsHandler.getDispatchedActive());
    barrier[1].await();
    assertTrue(_latchHandler.await());
    assertNotNull(asyncHolder.get());
    assertEquals(1, _statsHandler.getRequests());
    assertEquals(1, _statsHandler.getRequestsActive());
    assertEquals(1, _statsHandler.getDispatched());
    assertEquals(0, _statsHandler.getDispatchedActive());
    asyncHolder.get().addListener(new AsyncListener() {

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

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

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

        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            try {
                latch.countDown();
            } catch (Exception ignored) {
            }
        }
    });
    long requestTime = 20;
    Thread.sleep(requestTime);
    asyncHolder.get().complete();
    latch.await();
    assertEquals(1, _statsHandler.getRequests());
    assertEquals(0, _statsHandler.getRequestsActive());
    assertEquals(1, _statsHandler.getDispatched());
    assertEquals(0, _statsHandler.getDispatchedActive());
    assertEquals(1, _statsHandler.getAsyncRequests());
    assertEquals(0, _statsHandler.getAsyncDispatches());
    assertEquals(0, _statsHandler.getExpires());
    assertEquals(1, _statsHandler.getResponses2xx());
    assertTrue(_statsHandler.getRequestTimeTotal() >= (dispatchTime + requestTime) * 3 / 4);
    assertEquals(_statsHandler.getRequestTimeTotal(), _statsHandler.getRequestTimeMax());
    assertEquals(_statsHandler.getRequestTimeTotal(), _statsHandler.getRequestTimeMean(), 0.01);
    assertTrue(_statsHandler.getDispatchedTimeTotal() >= dispatchTime * 3 / 4);
    assertTrue(_statsHandler.getDispatchedTimeTotal() < _statsHandler.getRequestTimeTotal());
    assertEquals(_statsHandler.getDispatchedTimeTotal(), _statsHandler.getDispatchedTimeMax());
    assertEquals(_statsHandler.getDispatchedTimeTotal(), _statsHandler.getDispatchedTimeMean(), 0.01);
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncEvent(javax.servlet.AsyncEvent) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) CyclicBarrier(java.util.concurrent.CyclicBarrier) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AsyncListener(javax.servlet.AsyncListener) Test(org.junit.Test)

Example 12 with Request

use of org.eclipse.jetty.server.Request in project jetty.project by eclipse.

the class ThreadLimitHandlerTest method testLimit.

@Test
public void testLimit() throws Exception {
    ThreadLimitHandler handler = new ThreadLimitHandler("Forwarded");
    handler.setThreadLimit(4);
    AtomicInteger count = new AtomicInteger(0);
    AtomicInteger total = new AtomicInteger(0);
    CountDownLatch latch = new CountDownLatch(1);
    handler.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            response.setStatus(HttpStatus.OK_200);
            if ("/other".equals(target))
                return;
            try {
                count.incrementAndGet();
                total.incrementAndGet();
                latch.await();
            } catch (InterruptedException e) {
                throw new ServletException(e);
            } finally {
                count.decrementAndGet();
            }
        }
    });
    _server.setHandler(handler);
    _server.start();
    Socket[] client = new Socket[10];
    for (int i = 0; i < client.length; i++) {
        client[i] = new Socket("127.0.0.1", _connector.getLocalPort());
        client[i].getOutputStream().write(("GET /" + i + " HTTP/1.0\r\nForwarded: for=1.2.3.4\r\n\r\n").getBytes());
        client[i].getOutputStream().flush();
    }
    long wait = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
    while (count.get() < 4 && System.nanoTime() < wait) Thread.sleep(1);
    assertThat(count.get(), is(4));
    // check that other requests are not blocked
    assertThat(_local.getResponse("GET /other HTTP/1.0\r\nForwarded: for=6.6.6.6\r\n\r\n"), Matchers.containsString(" 200 OK"));
    // let the other requests go
    latch.countDown();
    while (total.get() < 10 && System.nanoTime() < wait) Thread.sleep(10);
    assertThat(total.get(), is(10));
    while (count.get() > 0 && System.nanoTime() < wait) Thread.sleep(10);
    assertThat(count.get(), is(0));
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Socket(java.net.Socket) Test(org.junit.Test)

Example 13 with Request

use of org.eclipse.jetty.server.Request in project jetty.project by eclipse.

the class SlowClientsTest method testSlowClientsWithSmallThreadPool.

@Test(timeout = 10000)
public void testSlowClientsWithSmallThreadPool() throws Exception {
    File keystore = MavenTestingUtils.getTestResourceFile("keystore");
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(keystore.getAbsolutePath());
    sslContextFactory.setKeyStorePassword("storepwd");
    sslContextFactory.setKeyManagerPassword("keypwd");
    int maxThreads = 6;
    int contentLength = 8 * 1024 * 1024;
    QueuedThreadPool serverThreads = new QueuedThreadPool(maxThreads);
    serverThreads.setDetailedDump(true);
    Server server = new Server(serverThreads);
    try {
        ServerConnector connector = new ServerConnector(server, 1, 1, sslContextFactory);
        connector.setPort(8888);
        server.addConnector(connector);
        server.setHandler(new AbstractHandler() {

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                baseRequest.setHandled(true);
                logger.info("SERVING {}", target);
                // Write some big content.
                response.getOutputStream().write(new byte[contentLength]);
                logger.info("SERVED {}", target);
            }
        });
        server.start();
        SSLContext sslContext = sslContextFactory.getSslContext();
        CompletableFuture[] futures = new CompletableFuture[2 * maxThreads];
        ExecutorService executor = Executors.newFixedThreadPool(futures.length);
        for (int i = 0; i < futures.length; i++) {
            int k = i;
            futures[i] = CompletableFuture.runAsync(() -> {
                try (SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket("localhost", connector.getLocalPort())) {
                    socket.setSoTimeout(contentLength / 1024);
                    OutputStream output = socket.getOutputStream();
                    String target = "/" + k;
                    String request = "GET " + target + " HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n";
                    output.write(request.getBytes(StandardCharsets.UTF_8));
                    output.flush();
                    while (serverThreads.getIdleThreads() > 0) Thread.sleep(50);
                    InputStream input = socket.getInputStream();
                    while (true) {
                        int read = input.read();
                        if (read < 0)
                            break;
                    }
                    logger.info("FINISHED {}", target);
                } catch (IOException x) {
                    throw new UncheckedIOException(x);
                } catch (InterruptedException x) {
                    throw new UncheckedIOException(new InterruptedIOException());
                }
            }, executor);
        }
        CompletableFuture.allOf(futures).join();
    } finally {
        server.stop();
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) Server(org.eclipse.jetty.server.Server) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) OutputStream(java.io.OutputStream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) SSLContext(javax.net.ssl.SSLContext) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) CompletableFuture(java.util.concurrent.CompletableFuture) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ExecutorService(java.util.concurrent.ExecutorService) File(java.io.File) Test(org.junit.Test)

Example 14 with Request

use of org.eclipse.jetty.server.Request in project jetty.project by eclipse.

the class ClientConnectionCloseTest method test_ClientConnectionClose_ServerConnectionClose_ClientClosesAfterExchange.

@Test
public void test_ClientConnectionClose_ServerConnectionClose_ClientClosesAfterExchange() throws Exception {
    byte[] data = new byte[128 * 1024];
    start(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            ServletInputStream input = request.getInputStream();
            while (true) {
                int read = input.read();
                if (read < 0)
                    break;
            }
            response.setContentLength(data.length);
            response.getOutputStream().write(data);
            try {
                // Delay the server from sending the TCP FIN.
                Thread.sleep(1000);
            } catch (InterruptedException x) {
                throw new InterruptedIOException();
            }
        }
    });
    String host = "localhost";
    int port = connector.getLocalPort();
    HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP) client.getDestination(scheme, host, port);
    DuplexConnectionPool connectionPool = (DuplexConnectionPool) destination.getConnectionPool();
    ContentResponse response = client.newRequest(host, port).scheme(scheme).header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()).content(new StringContentProvider("0")).onRequestSuccess(request -> {
        HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP) connectionPool.getActiveConnections().iterator().next();
        Assert.assertFalse(connection.getEndPoint().isOutputShutdown());
    }).send();
    Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    Assert.assertArrayEquals(data, response.getContent());
    Assert.assertEquals(0, connectionPool.getConnectionCount());
}
Also used : Request(org.eclipse.jetty.server.Request) HttpHeaderValue(org.eclipse.jetty.http.HttpHeaderValue) ServletException(javax.servlet.ServletException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) ServletInputStream(javax.servlet.ServletInputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Test(org.junit.Test) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) InterruptedIOException(java.io.InterruptedIOException) ByteBuffer(java.nio.ByteBuffer) TimeUnit(java.util.concurrent.TimeUnit) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) CountDownLatch(java.util.concurrent.CountDownLatch) HttpHeader(org.eclipse.jetty.http.HttpHeader) HttpServletRequest(javax.servlet.http.HttpServletRequest) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) HttpStatus(org.eclipse.jetty.http.HttpStatus) Assert(org.junit.Assert) HttpConnectionOverHTTP(org.eclipse.jetty.client.http.HttpConnectionOverHTTP) InterruptedIOException(java.io.InterruptedIOException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpConnectionOverHTTP(org.eclipse.jetty.client.http.HttpConnectionOverHTTP) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) Test(org.junit.Test)

Example 15 with Request

use of org.eclipse.jetty.server.Request in project jetty.project by eclipse.

the class ClientConnectionCloseTest method test_ClientConnectionClose_ServerNoConnectionClose_ClientCloses.

@Test
public void test_ClientConnectionClose_ServerNoConnectionClose_ClientCloses() throws Exception {
    start(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            response.setContentLength(0);
            response.flushBuffer();
            try {
                // Delay the server from sending the TCP FIN.
                Thread.sleep(1000);
            } catch (InterruptedException x) {
                throw new InterruptedIOException();
            }
        }
    });
    String host = "localhost";
    int port = connector.getLocalPort();
    HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP) client.getDestination(scheme, host, port);
    DuplexConnectionPool connectionPool = (DuplexConnectionPool) destination.getConnectionPool();
    ContentResponse response = client.newRequest(host, port).scheme(scheme).header(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.asString()).onRequestSuccess(request -> {
        HttpConnectionOverHTTP connection = (HttpConnectionOverHTTP) connectionPool.getActiveConnections().iterator().next();
        Assert.assertFalse(connection.getEndPoint().isOutputShutdown());
    }).onResponseHeaders(r -> r.getHeaders().remove(HttpHeader.CONNECTION)).send();
    Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    Assert.assertEquals(0, connectionPool.getConnectionCount());
}
Also used : Request(org.eclipse.jetty.server.Request) HttpHeaderValue(org.eclipse.jetty.http.HttpHeaderValue) ServletException(javax.servlet.ServletException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) ServletInputStream(javax.servlet.ServletInputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Test(org.junit.Test) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) InterruptedIOException(java.io.InterruptedIOException) ByteBuffer(java.nio.ByteBuffer) TimeUnit(java.util.concurrent.TimeUnit) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) CountDownLatch(java.util.concurrent.CountDownLatch) HttpHeader(org.eclipse.jetty.http.HttpHeader) HttpServletRequest(javax.servlet.http.HttpServletRequest) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) HttpStatus(org.eclipse.jetty.http.HttpStatus) Assert(org.junit.Assert) HttpConnectionOverHTTP(org.eclipse.jetty.client.http.HttpConnectionOverHTTP) InterruptedIOException(java.io.InterruptedIOException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) InterruptedIOException(java.io.InterruptedIOException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpConnectionOverHTTP(org.eclipse.jetty.client.http.HttpConnectionOverHTTP) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) Test(org.junit.Test)

Aggregations

Request (org.eclipse.jetty.server.Request)248 HttpServletRequest (javax.servlet.http.HttpServletRequest)223 HttpServletResponse (javax.servlet.http.HttpServletResponse)200 Test (org.junit.Test)182 IOException (java.io.IOException)151 ServletException (javax.servlet.ServletException)137 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)129 CountDownLatch (java.util.concurrent.CountDownLatch)65 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)64 InterruptedIOException (java.io.InterruptedIOException)45 InputStream (java.io.InputStream)36 AtomicReference (java.util.concurrent.atomic.AtomicReference)34 Server (org.eclipse.jetty.server.Server)29 Response (org.eclipse.jetty.client.api.Response)27 Result (org.eclipse.jetty.client.api.Result)27 ByteArrayInputStream (java.io.ByteArrayInputStream)26 ServletInputStream (javax.servlet.ServletInputStream)23 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)23 ServletOutputStream (javax.servlet.ServletOutputStream)22 ByteArrayOutputStream (java.io.ByteArrayOutputStream)21