Search in sources :

Example 41 with Callback

use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.

the class ServerTimeoutsTest method testBlockingTimeoutLargerThanIdleTimeoutBlockingWriteIdleTimeoutFires.

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

Example 42 with Callback

use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.

the class HttpClientStreamTest method testInputStreamResponseListenerClosedWhileWaiting.

@Test
public void testInputStreamResponseListenerClosedWhileWaiting() throws Exception {
    byte[] chunk1 = new byte[] { 0, 1 };
    byte[] chunk2 = new byte[] { 2, 3 };
    start(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            response.setContentLength(chunk1.length + chunk2.length);
            ServletOutputStream output = response.getOutputStream();
            output.write(chunk1);
            output.flush();
            output.write(chunk2);
        }
    });
    CountDownLatch failedLatch = new CountDownLatch(1);
    CountDownLatch contentLatch = new CountDownLatch(1);
    InputStreamResponseListener listener = new InputStreamResponseListener() {

        @Override
        public void onContent(Response response, ByteBuffer content, Callback callback) {
            super.onContent(response, content, new Callback() {

                @Override
                public void failed(Throwable x) {
                    failedLatch.countDown();
                    callback.failed(x);
                }
            });
            contentLatch.countDown();
        }
    };
    client.newRequest("localhost", connector.getLocalPort()).scheme(getScheme()).send(listener);
    Response response = listener.get(5, TimeUnit.SECONDS);
    Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    // Wait until we get some content.
    Assert.assertTrue(contentLatch.await(5, TimeUnit.SECONDS));
    // Close the stream.
    InputStream stream = listener.getInputStream();
    stream.close();
    // Make sure that the callback has been invoked.
    Assert.assertTrue(failedLatch.await(5, TimeUnit.SECONDS));
}
Also used : InputStreamResponseListener(org.eclipse.jetty.client.util.InputStreamResponseListener) ServletOutputStream(javax.servlet.ServletOutputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) 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) Callback(org.eclipse.jetty.util.Callback) Test(org.junit.Test)

Example 43 with Callback

use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.

the class HttpClientStreamTest method testUploadWithDeferredContentAvailableCallbacksNotifiedOnce.

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

        @Override
        public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            IO.copy(request.getInputStream(), new ByteArrayOutputStream());
        }
    });
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger succeeds = new AtomicInteger();
    try (DeferredContentProvider content = new DeferredContentProvider()) {
        // Make the content immediately available.
        content.offer(ByteBuffer.allocate(1024), new Callback() {

            @Override
            public void succeeded() {
                succeeds.incrementAndGet();
            }
        });
        client.newRequest("localhost", connector.getLocalPort()).scheme(getScheme()).content(content).send(result -> {
            if (result.isSucceeded() && result.getResponse().getStatus() == 200)
                latch.countDown();
        });
    }
    Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
    Assert.assertEquals(1, succeeds.get());
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CountDownLatch(java.util.concurrent.CountDownLatch) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Callback(org.eclipse.jetty.util.Callback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) Test(org.junit.Test)

Example 44 with Callback

use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.

the class HttpTransportOverHTTP2 method send.

@Override
public void send(MetaData.Response info, boolean isHeadRequest, ByteBuffer content, boolean lastContent, Callback callback) {
    boolean hasContent = BufferUtil.hasContent(content) && !isHeadRequest;
    if (info != null) {
        int status = info.getStatus();
        boolean informational = HttpStatus.isInformational(status) && status != HttpStatus.SWITCHING_PROTOCOLS_101;
        boolean committed = false;
        if (!informational)
            committed = commit.compareAndSet(false, true);
        if (committed || informational) {
            if (hasContent) {
                Callback commitCallback = new Callback.Nested(callback) {

                    @Override
                    public void succeeded() {
                        if (transportCallback.start(callback, false))
                            send(content, lastContent, transportCallback);
                    }
                };
                if (transportCallback.start(commitCallback, true))
                    commit(info, false, transportCallback);
            } else {
                if (transportCallback.start(callback, false))
                    commit(info, lastContent, transportCallback);
            }
        } else {
            callback.failed(new IllegalStateException("committed"));
        }
    } else {
        if (hasContent || lastContent) {
            if (transportCallback.start(callback, false))
                send(content, lastContent, transportCallback);
        } else {
            callback.succeeded();
        }
    }
}
Also used : Callback(org.eclipse.jetty.util.Callback)

Example 45 with Callback

use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.

the class HttpOutputTest method testWriteInterception.

@Test
public void testWriteInterception() throws Exception {
    final Resource big = Resource.newClassPathResource("simple/big.txt");
    _handler._writeLengthIfKnown = false;
    _handler._content = BufferUtil.toBuffer(big, false);
    _handler._arrayBuffer = new byte[1024];
    _handler._interceptor = new ChainedInterceptor() {

        Interceptor _next;

        @Override
        public void write(ByteBuffer content, boolean complete, Callback callback) {
            String s = BufferUtil.toString(content).toUpperCase().replaceAll("BIG", "BIGGER");
            _next.write(BufferUtil.toBuffer(s), complete, callback);
        }

        @Override
        public boolean isOptimizedForDirectBuffers() {
            return _next.isOptimizedForDirectBuffers();
        }

        @Override
        public Interceptor getNextInterceptor() {
            return _next;
        }

        @Override
        public void setNext(Interceptor interceptor) {
            _next = interceptor;
        }
    };
    String response = _connector.getResponse("GET / HTTP/1.0\nHost: localhost:80\n\n");
    assertThat(response, containsString("HTTP/1.1 200 OK"));
    assertThat(response, Matchers.not(containsString("Content-Length")));
    assertThat(response, containsString("400\tTHIS IS A BIGGER FILE"));
}
Also used : Callback(org.eclipse.jetty.util.Callback) Resource(org.eclipse.jetty.util.resource.Resource) Matchers.containsString(org.hamcrest.Matchers.containsString) Interceptor(org.eclipse.jetty.server.HttpOutput.Interceptor) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Aggregations

Callback (org.eclipse.jetty.util.Callback)81 Test (org.junit.Test)71 CountDownLatch (java.util.concurrent.CountDownLatch)68 HttpFields (org.eclipse.jetty.http.HttpFields)52 HeadersFrame (org.eclipse.jetty.http2.frames.HeadersFrame)52 Stream (org.eclipse.jetty.http2.api.Stream)51 MetaData (org.eclipse.jetty.http.MetaData)50 Session (org.eclipse.jetty.http2.api.Session)50 DataFrame (org.eclipse.jetty.http2.frames.DataFrame)46 HttpServletResponse (javax.servlet.http.HttpServletResponse)44 ServerSessionListener (org.eclipse.jetty.http2.api.server.ServerSessionListener)41 IOException (java.io.IOException)39 FuturePromise (org.eclipse.jetty.util.FuturePromise)39 ByteBuffer (java.nio.ByteBuffer)38 HttpServletRequest (javax.servlet.http.HttpServletRequest)37 ServletException (javax.servlet.ServletException)34 Promise (org.eclipse.jetty.util.Promise)30 ServletOutputStream (javax.servlet.ServletOutputStream)26 HttpServlet (javax.servlet.http.HttpServlet)21 HTTP2Session (org.eclipse.jetty.http2.HTTP2Session)20