Search in sources :

Example 6 with DeferredContentProvider

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

the class AsyncIOServletTest method testWriteFromOnDataAvailable.

@Test
public void testWriteFromOnDataAvailable() throws Exception {
    Queue<Throwable> errors = new ConcurrentLinkedQueue<>();
    CountDownLatch writeLatch = new CountDownLatch(1);
    start(new HttpServlet() {

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

                @Override
                public void onDataAvailable() throws IOException {
                    ServletInputStream input = request.getInputStream();
                    ServletOutputStream output = response.getOutputStream();
                    while (input.isReady()) {
                        byte[] buffer = new byte[512];
                        int read = input.read(buffer);
                        if (read < 0) {
                            asyncContext.complete();
                            break;
                        }
                        if (output.isReady())
                            output.write(buffer, 0, read);
                        else
                            Assert.fail();
                    }
                }

                @Override
                public void onAllDataRead() throws IOException {
                    asyncContext.complete();
                }

                @Override
                public void onError(Throwable t) {
                    errors.offer(t);
                }
            });
            response.getOutputStream().setWriteListener(new WriteListener() {

                @Override
                public void onWritePossible() throws IOException {
                    writeLatch.countDown();
                }

                @Override
                public void onError(Throwable t) {
                    errors.offer(t);
                }
            });
        }
    });
    String content = "0123456789ABCDEF";
    DeferredContentProvider contentProvider = new DeferredContentProvider();
    contentProvider.offer(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
    CountDownLatch clientLatch = new CountDownLatch(1);
    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(content));
                assertThat(errors, Matchers.hasSize(0));
                clientLatch.countDown();
            }
        }
    });
    assertTrue(writeLatch.await(5, TimeUnit.SECONDS));
    contentProvider.close();
    assertTrue(clientLatch.await(5, TimeUnit.SECONDS));
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) 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) Matchers.containsString(org.hamcrest.Matchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) 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) ServletInputStream(javax.servlet.ServletInputStream) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) WriteListener(javax.servlet.WriteListener) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Test(org.junit.Test)

Example 7 with DeferredContentProvider

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

the class AsyncIOServletTest method testAsyncReadEarlyEOF.

@Test
public void testAsyncReadEarlyEOF() throws Exception {
    // SSLEngine receives the close alert from the client, and when
    // the server passes the response to encrypt and write, SSLEngine
    // only generates the close alert back, without encrypting the
    // response, so we need to skip the transports over TLS.
    Assume.assumeThat(transport, Matchers.not(Matchers.isOneOf(Transport.HTTPS, Transport.H2)));
    String content = "jetty";
    int responseCode = HttpStatus.NO_CONTENT_204;
    CountDownLatch readLatch = new CountDownLatch(content.length());
    CountDownLatch errorLatch = new CountDownLatch(1);
    start(new HttpServlet() {

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

                @Override
                public void onDataAvailable() throws IOException {
                    while (input.isReady() && !input.isFinished()) {
                        int read = input.read();
                        // System.err.printf("%x%n", read);
                        readLatch.countDown();
                    }
                }

                @Override
                public void onAllDataRead() throws IOException {
                }

                @Override
                public void onError(Throwable x) {
                    response.setStatus(responseCode);
                    asyncContext.complete();
                    errorLatch.countDown();
                }
            });
        }
    });
    CountDownLatch responseLatch = new CountDownLatch(1);
    DeferredContentProvider contentProvider = new DeferredContentProvider();
    contentProvider.offer(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
    org.eclipse.jetty.client.api.Request request = client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).content(contentProvider).onResponseSuccess(response -> responseLatch.countDown());
    Destination destination = client.getDestination(getScheme(), "localhost", connector.getLocalPort());
    FuturePromise<org.eclipse.jetty.client.api.Connection> promise = new FuturePromise<>();
    destination.newConnection(promise);
    org.eclipse.jetty.client.api.Connection connection = promise.get(5, TimeUnit.SECONDS);
    CountDownLatch clientLatch = new CountDownLatch(1);
    connection.send(request, result -> {
        assertThat(result.getResponse().getStatus(), Matchers.equalTo(responseCode));
        clientLatch.countDown();
    });
    assertTrue(readLatch.await(5, TimeUnit.SECONDS));
    switch(transport) {
        case HTTP:
        case HTTPS:
            ((HttpConnectionOverHTTP) connection).getEndPoint().shutdownOutput();
            break;
        case H2C:
        case H2:
            // In case of HTTP/2, we not only send the request, but also the preface and
            // SETTINGS frames. SETTINGS frame need to be replied, so we want to wait to
            // write the reply before shutting output down, so that the test does not fail.
            Thread.sleep(1000);
            Session session = ((HttpConnectionOverHTTP2) connection).getSession();
            ((HTTP2Session) session).getEndPoint().shutdownOutput();
            break;
        default:
            Assert.fail();
    }
    // Wait for the response to arrive before finishing the request.
    assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
    contentProvider.close();
    assertTrue(errorLatch.await(5, TimeUnit.SECONDS));
    assertTrue(clientLatch.await(5, TimeUnit.SECONDS));
}
Also used : Destination(org.eclipse.jetty.client.api.Destination) AsyncContext(javax.servlet.AsyncContext) HttpConnectionOverHTTP2(org.eclipse.jetty.http2.client.http.HttpConnectionOverHTTP2) Matchers.containsString(org.hamcrest.Matchers.containsString) ReadListener(javax.servlet.ReadListener) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServletInputStream(javax.servlet.ServletInputStream) HttpServlet(javax.servlet.http.HttpServlet) FuturePromise(org.eclipse.jetty.util.FuturePromise) Connection(org.eclipse.jetty.io.Connection) HttpServletResponse(javax.servlet.http.HttpServletResponse) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 8 with DeferredContentProvider

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

the class ServerTimeoutsTest method testBlockingReadHttpIdleTimeoutOverridesIdleTimeout.

@Test
public void testBlockingReadHttpIdleTimeoutOverridesIdleTimeout() throws Exception {
    long httpIdleTimeout = 2500;
    long idleTimeout = 3 * httpIdleTimeout;
    httpConfig.setIdleTimeout(httpIdleTimeout);
    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 * httpIdleTimeout, 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 9 with DeferredContentProvider

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

the class ServerTimeoutsTest method testDelayedDispatchRequestWithDelayedFirstContentIdleTimeoutFires.

@Test
public void testDelayedDispatchRequestWithDelayedFirstContentIdleTimeoutFires() throws Exception {
    httpConfig.setDelayDispatchUntilContent(true);
    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);
            handlerLatch.countDown();
        }
    });
    long idleTimeout = 2500;
    setServerIdleTimeout(idleTimeout);
    CountDownLatch resultLatch = new CountDownLatch(1);
    client.POST(newURI()).content(new DeferredContentProvider()).send(result -> {
        if (result.isFailed())
            resultLatch.countDown();
    });
    // We did not send the content, the request was not
    // dispatched, the server should have idle timed out.
    Assert.assertFalse(handlerLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
    Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) 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) Test(org.junit.Test)

Example 10 with DeferredContentProvider

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

the class ServerTimeoutsTest method testBlockingTimeoutWithSlowRead.

@Test
public void testBlockingTimeoutWithSlowRead() throws Exception {
    long idleTimeout = 2500;
    long blockingTimeout = 2 * idleTimeout;
    httpConfig.setBlockingTimeout(blockingTimeout);
    CountDownLatch handlerLatch = new CountDownLatch(1);
    start(new AbstractHandler() {

        @Override
        public void handle(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 (IOException x) {
                handlerLatch.countDown();
                throw x;
            }
        }
    });
    setServerIdleTimeout(idleTimeout);
    try (StacklessLogging stackless = new StacklessLogging(HttpChannel.class)) {
        DeferredContentProvider contentProvider = new DeferredContentProvider();
        CountDownLatch resultLatch = new CountDownLatch(1);
        client.newRequest(newURI()).content(contentProvider).send(result -> {
            if (result.getResponse().getStatus() == HttpStatus.INTERNAL_SERVER_ERROR_500)
                resultLatch.countDown();
        });
        // The writes should be slow but not trigger the idle timeout.
        long period = idleTimeout / 2;
        long writes = 2 * (blockingTimeout / period);
        for (long i = 0; i < writes; ++i) {
            contentProvider.offer(ByteBuffer.allocate(1));
            Thread.sleep(period);
        }
        contentProvider.close();
        // Blocking read should timeout.
        Assert.assertTrue(handlerLatch.await(2 * idleTimeout, TimeUnit.MILLISECONDS));
        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) 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) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) 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