Search in sources :

Example 96 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project jetty.project by eclipse.

the class ServerTimeoutsTest method testAsyncWriteIdleTimeoutFires.

@Test
public void testAsyncWriteIdleTimeoutFires() throws Exception {
    CountDownLatch handlerLatch = new CountDownLatch(1);
    start(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            AsyncContext asyncContext = request.startAsync();
            asyncContext.setTimeout(0);
            ServletOutputStream output = response.getOutputStream();
            output.setWriteListener(new WriteListener() {

                @Override
                public void onWritePossible() throws IOException {
                    output.write(new byte[64 * 1024 * 1024]);
                }

                @Override
                public void onError(Throwable failure) {
                    if (failure instanceof TimeoutException) {
                        asyncContext.complete();
                        handlerLatch.countDown();
                    }
                }
            });
        }
    });
    long idleTimeout = 2500;
    setServerIdleTimeout(idleTimeout);
    BlockingQueue<Callback> callbacks = new LinkedBlockingQueue<>();
    CountDownLatch resultLatch = new CountDownLatch(1);
    client.newRequest(newURI()).onResponseContentAsync((response, content, callback) -> {
        // Do not succeed the callback so the server will block writing.
        callbacks.offer(callback);
    }).send(result -> {
        if (result.isFailed())
            resultLatch.countDown();
    });
    // Async write should timeout.
    Assert.assertTrue(handlerLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
    // After the server stopped sending, consume on the client to read the early EOF.
    while (true) {
        Callback callback = callbacks.poll(1, TimeUnit.SECONDS);
        if (callback == null)
            break;
        callback.succeeded();
    }
    Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS));
}
Also used : BadMessageException(org.eclipse.jetty.http.BadMessageException) Request(org.eclipse.jetty.server.Request) ServletException(javax.servlet.ServletException) HttpChannel(org.eclipse.jetty.server.HttpChannel) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) ServletInputStream(javax.servlet.ServletInputStream) AbstractHTTP2ServerConnectionFactory(org.eclipse.jetty.http2.server.AbstractHTTP2ServerConnectionFactory) TimeoutException(java.util.concurrent.TimeoutException) ByteBuffer(java.nio.ByteBuffer) AsyncContext(javax.servlet.AsyncContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) WriteListener(javax.servlet.WriteListener) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) HttpStatus(org.eclipse.jetty.http.HttpStatus) Callback(org.eclipse.jetty.util.Callback) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) BlockingQueue(java.util.concurrent.BlockingQueue) Test(org.junit.Test) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) ReadListener(javax.servlet.ReadListener) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) Assert(org.junit.Assert) ServletOutputStream(javax.servlet.ServletOutputStream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Callback(org.eclipse.jetty.util.Callback) WriteListener(javax.servlet.WriteListener) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 97 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project jetty.project by eclipse.

the class ServerTimeoutsTest method testAsyncReadHttpIdleTimeoutOverridesIdleTimeout.

@Test
public void testAsyncReadHttpIdleTimeoutOverridesIdleTimeout() throws Exception {
    long httpIdleTimeout = 2500;
    long idleTimeout = 3 * httpIdleTimeout;
    httpConfig.setIdleTimeout(httpIdleTimeout);
    CountDownLatch handlerLatch = new CountDownLatch(1);
    start(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            AsyncContext asyncContext = request.startAsync();
            asyncContext.setTimeout(0);
            ServletInputStream input = request.getInputStream();
            input.setReadListener(new ReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    Assert.assertEquals(0, input.read());
                    Assert.assertFalse(input.isReady());
                }

                @Override
                public void onAllDataRead() throws IOException {
                }

                @Override
                public void onError(Throwable failure) {
                    if (failure instanceof TimeoutException) {
                        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
                        asyncContext.complete();
                        handlerLatch.countDown();
                    }
                }
            });
        }
    });
    setServerIdleTimeout(idleTimeout);
    DeferredContentProvider contentProvider = new DeferredContentProvider(ByteBuffer.allocate(1));
    CountDownLatch resultLatch = new CountDownLatch(1);
    client.POST(newURI()).content(contentProvider).send(result -> {
        if (result.getResponse().getStatus() == HttpStatus.INTERNAL_SERVER_ERROR_500)
            resultLatch.countDown();
    });
    // Async read should timeout.
    Assert.assertTrue(handlerLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
    // Complete the request.
    contentProvider.close();
    Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS));
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ReadListener(javax.servlet.ReadListener) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 98 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project jetty.project by eclipse.

the class ServerTimeoutsTest method testBlockingReadWithMinimumDataRateBelowLimit.

@Test
public void testBlockingReadWithMinimumDataRateBelowLimit() throws Exception {
    int bytesPerSecond = 20;
    httpConfig.setMinRequestDataRate(bytesPerSecond);
    CountDownLatch handlerLatch = new CountDownLatch(1);
    start(new AbstractHandler.ErrorDispatchHandler() {

        @Override
        public void doNonErrorHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            try {
                baseRequest.setHandled(true);
                ServletInputStream input = request.getInputStream();
                while (true) {
                    int read = input.read();
                    if (read < 0)
                        break;
                }
            } catch (BadMessageException x) {
                handlerLatch.countDown();
                throw x;
            }
        }
    });
    DeferredContentProvider contentProvider = new DeferredContentProvider();
    CountDownLatch resultLatch = new CountDownLatch(1);
    client.newRequest(newURI()).content(contentProvider).send(result -> {
        if (result.getResponse().getStatus() == HttpStatus.REQUEST_TIMEOUT_408)
            resultLatch.countDown();
    });
    for (int i = 0; i < 3; ++i) {
        contentProvider.offer(ByteBuffer.allocate(bytesPerSecond / 2));
        Thread.sleep(2500);
    }
    contentProvider.close();
    // Request should timeout.
    Assert.assertTrue(handlerLatch.await(5, TimeUnit.SECONDS));
    Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS));
}
Also used : BadMessageException(org.eclipse.jetty.http.BadMessageException) 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) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) Test(org.junit.Test)

Example 99 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project jetty.project by eclipse.

the class AsyncIOServletTest method testAsyncIntercepted.

@Test
public void testAsyncIntercepted() throws Exception {
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.err.println("Service " + request);
            final HttpInput httpInput = ((Request) request).getHttpInput();
            httpInput.addInterceptor(new HttpInput.Interceptor() {

                int state = 0;

                Content saved;

                @Override
                public Content readFrom(Content content) {
                    // System.err.printf("readFrom s=%d saved=%b %s%n",state,saved!=null,content);
                    switch(state) {
                        case 0:
                            // null transform
                            if (content.isEmpty())
                                state++;
                            return null;
                        case 1:
                            {
                                // copy transform
                                if (content.isEmpty()) {
                                    state++;
                                    return content;
                                }
                                ByteBuffer copy = wrap(toArray(content.getByteBuffer()));
                                content.skip(copy.remaining());
                                return new Content(copy);
                            }
                        case 2:
                            // byte by byte
                            if (content.isEmpty()) {
                                state++;
                                return content;
                            }
                            byte[] b = new byte[1];
                            int l = content.get(b, 0, 1);
                            return new Content(wrap(b, 0, l));
                        case 3:
                            {
                                // double vision
                                if (content.isEmpty()) {
                                    if (saved == null) {
                                        state++;
                                        return content;
                                    }
                                    Content copy = saved;
                                    saved = null;
                                    return copy;
                                }
                                byte[] data = toArray(content.getByteBuffer());
                                content.skip(data.length);
                                saved = new Content(wrap(data));
                                return new Content(wrap(data));
                            }
                        default:
                            return null;
                    }
                }
            });
            AsyncContext asyncContext = request.startAsync();
            ServletInputStream input = request.getInputStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            input.setReadListener(new ReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    while (input.isReady()) {
                        int b = input.read();
                        if (b > 0) {
                            // System.err.printf("0x%2x %s %n", b, Character.isISOControl(b)?"?":(""+(char)b));
                            out.write(b);
                        } else if (b < 0)
                            return;
                    }
                }

                @Override
                public void onAllDataRead() throws IOException {
                    response.getOutputStream().write(out.toByteArray());
                    asyncContext.complete();
                }

                @Override
                public void onError(Throwable x) {
                }
            });
        }
    });
    DeferredContentProvider contentProvider = new DeferredContentProvider();
    CountDownLatch clientLatch = new CountDownLatch(1);
    String expected = "S0" + "S1" + "S2" + "S3S3" + "S4" + "S5" + "S6";
    client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).content(contentProvider).send(new BufferingResponseListener() {

        @Override
        public void onComplete(Result result) {
            if (result.isSucceeded()) {
                Response response = result.getResponse();
                assertThat(response.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
                assertThat(getContentAsString(), Matchers.equalTo(expected));
                clientLatch.countDown();
            }
        }
    });
    contentProvider.offer(BufferUtil.toBuffer("S0"));
    contentProvider.flush();
    contentProvider.offer(BufferUtil.toBuffer("S1"));
    contentProvider.flush();
    contentProvider.offer(BufferUtil.toBuffer("S2"));
    contentProvider.flush();
    contentProvider.offer(BufferUtil.toBuffer("S3"));
    contentProvider.flush();
    contentProvider.offer(BufferUtil.toBuffer("S4"));
    contentProvider.flush();
    contentProvider.offer(BufferUtil.toBuffer("S5"));
    contentProvider.flush();
    contentProvider.offer(BufferUtil.toBuffer("S6"));
    contentProvider.close();
    Assert.assertTrue(clientLatch.await(10, TimeUnit.SECONDS));
}
Also used : HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Matchers.containsString(org.hamcrest.Matchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) ReadListener(javax.servlet.ReadListener) Result(org.eclipse.jetty.client.api.Result) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpInput(org.eclipse.jetty.server.HttpInput) ServletInputStream(javax.servlet.ServletInputStream) Content(org.eclipse.jetty.server.HttpInput.Content) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Test(org.junit.Test)

Example 100 with HttpServletResponse

use of javax.servlet.http.HttpServletResponse in project jetty.project by eclipse.

the class AsyncIOServletTest method testAsyncReadIdleTimeout.

@Test
public void testAsyncReadIdleTimeout() throws Exception {
    int status = 567;
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            assertScope();
            AsyncContext asyncContext = request.startAsync(request, response);
            asyncContext.setTimeout(0);
            ServletInputStream inputStream = request.getInputStream();
            inputStream.setReadListener(new ReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    assertScope();
                    while (inputStream.isReady() && !inputStream.isFinished()) inputStream.read();
                }

                @Override
                public void onAllDataRead() throws IOException {
                    assertScope();
                }

                @Override
                public void onError(Throwable t) {
                    assertScope();
                    response.setStatus(status);
                    // Do not put Connection: close header here, the test
                    // verifies that the server closes no matter what.
                    asyncContext.complete();
                }
            });
        }
    });
    connector.setIdleTimeout(1000);
    CountDownLatch closeLatch = new CountDownLatch(1);
    connector.addBean(new Connection.Listener() {

        @Override
        public void onOpened(Connection connection) {
        }

        @Override
        public void onClosed(Connection connection) {
            closeLatch.countDown();
        }
    });
    String data = "0123456789";
    DeferredContentProvider content = new DeferredContentProvider();
    content.offer(ByteBuffer.wrap(data.getBytes(StandardCharsets.UTF_8)));
    CountDownLatch responseLatch = new CountDownLatch(1);
    CountDownLatch clientLatch = new CountDownLatch(1);
    client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).content(content).onResponseSuccess(r -> responseLatch.countDown()).timeout(5, TimeUnit.SECONDS).send(result -> {
        assertEquals(status, result.getResponse().getStatus());
        clientLatch.countDown();
    });
    assertTrue(closeLatch.await(5, TimeUnit.SECONDS));
    assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
    content.close();
    assertTrue(clientLatch.await(5, TimeUnit.SECONDS));
}
Also used : HttpServlet(javax.servlet.http.HttpServlet) Connection(org.eclipse.jetty.io.Connection) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) Matchers.containsString(org.hamcrest.Matchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) ReadListener(javax.servlet.ReadListener) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) Test(org.junit.Test)

Aggregations

HttpServletResponse (javax.servlet.http.HttpServletResponse)1635 HttpServletRequest (javax.servlet.http.HttpServletRequest)1312 Test (org.junit.Test)705 IOException (java.io.IOException)576 ServletException (javax.servlet.ServletException)491 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)223 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)195 Request (org.eclipse.jetty.server.Request)186 HttpServlet (javax.servlet.http.HttpServlet)157 CountDownLatch (java.util.concurrent.CountDownLatch)156 FilterChain (javax.servlet.FilterChain)148 PrintWriter (java.io.PrintWriter)138 Test (org.testng.annotations.Test)127 HashMap (java.util.HashMap)106 ServletOutputStream (javax.servlet.ServletOutputStream)105 InterruptedIOException (java.io.InterruptedIOException)97 InputStream (java.io.InputStream)85 OutputStream (java.io.OutputStream)81 HttpSession (javax.servlet.http.HttpSession)75 ServletResponse (javax.servlet.ServletResponse)74