Search in sources :

Example 11 with DeferredContentProvider

use of org.eclipse.jetty.client.util.DeferredContentProvider 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 12 with DeferredContentProvider

use of org.eclipse.jetty.client.util.DeferredContentProvider in project jetty.project by eclipse.

the class ServerTimeoutsTest method testBlockingTimeoutLargerThanIdleTimeoutBlockingReadIdleTimeoutFires.

@Test
public void testBlockingTimeoutLargerThanIdleTimeoutBlockingReadIdleTimeoutFires() throws Exception {
    long idleTimeout = 2500;
    long blockingTimeout = 3 * idleTimeout;
    httpConfig.setBlockingTimeout(blockingTimeout);
    CountDownLatch handlerLatch = new CountDownLatch(1);
    start(new BlockingReadHandler(handlerLatch));
    setServerIdleTimeout(idleTimeout);
    try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class)) {
        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();
        });
        // Blocking 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 : DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 13 with DeferredContentProvider

use of org.eclipse.jetty.client.util.DeferredContentProvider 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 14 with DeferredContentProvider

use of org.eclipse.jetty.client.util.DeferredContentProvider 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 15 with DeferredContentProvider

use of org.eclipse.jetty.client.util.DeferredContentProvider 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

DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)46 Test (org.junit.Test)41 CountDownLatch (java.util.concurrent.CountDownLatch)38 HttpServletRequest (javax.servlet.http.HttpServletRequest)35 HttpServletResponse (javax.servlet.http.HttpServletResponse)34 IOException (java.io.IOException)33 ServletException (javax.servlet.ServletException)28 ServletInputStream (javax.servlet.ServletInputStream)18 AbstractHandler (org.eclipse.jetty.server.handler.AbstractHandler)18 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)17 Request (org.eclipse.jetty.server.Request)16 Result (org.eclipse.jetty.client.api.Result)15 InterruptedIOException (java.io.InterruptedIOException)14 BufferingResponseListener (org.eclipse.jetty.client.util.BufferingResponseListener)12 AsyncContext (javax.servlet.AsyncContext)11 Request (org.eclipse.jetty.client.api.Request)11 ByteBuffer (java.nio.ByteBuffer)10 Response (org.eclipse.jetty.client.api.Response)9 StacklessLogging (org.eclipse.jetty.util.log.StacklessLogging)8 ReadListener (javax.servlet.ReadListener)7