Search in sources :

Example 1 with WriteListener

use of javax.servlet.WriteListener 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 2 with WriteListener

use of javax.servlet.WriteListener in project jetty.project by eclipse.

the class AsyncIOServletTest method testAsyncWriteThrows.

private void testAsyncWriteThrows(Throwable throwable) throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            assertScope();
            AsyncContext asyncContext = request.startAsync(request, response);
            response.getOutputStream().setWriteListener(new WriteListener() {

                @Override
                public void onWritePossible() throws IOException {
                    assertScope();
                    if (throwable instanceof RuntimeException)
                        throw (RuntimeException) throwable;
                    if (throwable instanceof Error)
                        throw (Error) throwable;
                    throw new IOException(throwable);
                }

                @Override
                public void onError(Throwable t) {
                    assertScope();
                    latch.countDown();
                    response.setStatus(500);
                    asyncContext.complete();
                    Assert.assertSame(throwable, t);
                }
            });
        }
    });
    ContentResponse response = client.newRequest(newURI()).path(servletPath).timeout(5, TimeUnit.SECONDS).send();
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertEquals(HttpStatus.INTERNAL_SERVER_ERROR_500, response.getStatus());
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) 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) CountDownLatch(java.util.concurrent.CountDownLatch) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) WriteListener(javax.servlet.WriteListener)

Example 3 with WriteListener

use of javax.servlet.WriteListener in project jetty.project by eclipse.

the class AsyncIOServletTest method testAsyncWriteClosed.

@Test
public void testAsyncWriteClosed() throws Exception {
    String text = "Now is the winter of our discontent. How Now Brown Cow. The quick brown fox jumped over the lazy dog.\n";
    for (int i = 0; i < 10; i++) text = text + text;
    byte[] data = text.getBytes(StandardCharsets.UTF_8);
    CountDownLatch errorLatch = new CountDownLatch(1);
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            assertScope();
            response.flushBuffer();
            AsyncContext async = request.startAsync();
            ServletOutputStream out = response.getOutputStream();
            out.setWriteListener(new WriteListener() {

                @Override
                public void onWritePossible() throws IOException {
                    assertScope();
                    // Wait for the failure to arrive to
                    // the server while we are about to write.
                    sleep(1000);
                    out.write(data);
                }

                @Override
                public void onError(Throwable t) {
                    assertScope();
                    async.complete();
                    errorLatch.countDown();
                }
            });
        }
    });
    CountDownLatch clientLatch = new CountDownLatch(1);
    client.newRequest(newURI()).path(servletPath).onResponseHeaders(response -> {
        if (response.getStatus() == HttpStatus.OK_200)
            response.abort(new IOException("explicitly_closed_by_test"));
    }).send(result -> {
        if (result.isFailed())
            clientLatch.countDown();
    });
    assertTrue(errorLatch.await(5, TimeUnit.SECONDS));
    assertTrue(clientLatch.await(5, TimeUnit.SECONDS));
}
Also used : Request(org.eclipse.jetty.server.Request) ServletException(javax.servlet.ServletException) Context(org.eclipse.jetty.server.handler.ContextHandler.Context) ByteBuffer(java.nio.ByteBuffer) Assert.assertThat(org.junit.Assert.assertThat) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) BufferUtil.toArray(org.eclipse.jetty.util.BufferUtil.toArray) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DeferredContentProvider(org.eclipse.jetty.client.util.DeferredContentProvider) HttpStatus(org.eclipse.jetty.http.HttpStatus) HttpInput(org.eclipse.jetty.server.HttpInput) Response(org.eclipse.jetty.client.api.Response) HttpServlet(javax.servlet.http.HttpServlet) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) UncheckedIOException(java.io.UncheckedIOException) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) Session(org.eclipse.jetty.http2.api.Session) FuturePromise(org.eclipse.jetty.util.FuturePromise) Content(org.eclipse.jetty.server.HttpInput.Content) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) Matchers.is(org.hamcrest.Matchers.is) Queue(java.util.Queue) Matchers.containsString(org.hamcrest.Matchers.containsString) HttpConnectionOverHTTP(org.eclipse.jetty.client.http.HttpConnectionOverHTTP) BufferUtil(org.eclipse.jetty.util.BufferUtil) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Result(org.eclipse.jetty.client.api.Result) Handler(org.eclipse.jetty.server.Handler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpChannel(org.eclipse.jetty.server.HttpChannel) ServletInputStream(javax.servlet.ServletInputStream) ByteBuffer.wrap(java.nio.ByteBuffer.wrap) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) Deque(java.util.Deque) InterruptedIOException(java.io.InterruptedIOException) AsyncContext(javax.servlet.AsyncContext) HttpHeader(org.eclipse.jetty.http.HttpHeader) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) WriteListener(javax.servlet.WriteListener) InputStreamContentProvider(org.eclipse.jetty.client.util.InputStreamContentProvider) HttpConnectionOverHTTP2(org.eclipse.jetty.http2.client.http.HttpConnectionOverHTTP2) Assume(org.junit.Assume) Executor(java.util.concurrent.Executor) HttpServletResponse(javax.servlet.http.HttpServletResponse) Matchers(org.hamcrest.Matchers) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) Test(org.junit.Test) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) TimeUnit(java.util.concurrent.TimeUnit) HttpMethod(org.eclipse.jetty.http.HttpMethod) Connection(org.eclipse.jetty.io.Connection) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) ReadListener(javax.servlet.ReadListener) DispatcherType(javax.servlet.DispatcherType) Destination(org.eclipse.jetty.client.api.Destination) Assert(org.junit.Assert) Assert.assertEquals(org.junit.Assert.assertEquals) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) Matchers.containsString(org.hamcrest.Matchers.containsString) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) WriteListener(javax.servlet.WriteListener) Test(org.junit.Test)

Example 4 with WriteListener

use of javax.servlet.WriteListener 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 5 with WriteListener

use of javax.servlet.WriteListener in project solo by b3log.

the class CaptchaProcessorTestCase method get.

/**
     * get.
     *
     * @throws Exception exception
     */
@Test(dependsOnMethods = "init")
public void get() throws Exception {
    final HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getServletContext()).thenReturn(mock(ServletContext.class));
    when(request.getRequestURI()).thenReturn("/captcha.do");
    when(request.getMethod()).thenReturn("GET");
    final MockDispatcherServlet dispatcherServlet = new MockDispatcherServlet();
    dispatcherServlet.init();
    final HttpServletResponse response = mock(HttpServletResponse.class);
    when(response.getOutputStream()).thenReturn(new ServletOutputStream() {

        private long size;

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setWriteListener(final WriteListener writeListener) {
        }

        @Override
        public void write(int b) throws IOException {
            size++;
        }

        @Override
        public String toString() {
            return "size: " + String.valueOf(size);
        }
    });
    dispatcherServlet.service(request, response);
    Assert.assertTrue(StringUtils.startsWith(response.getOutputStream().toString(), "size: "));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletOutputStream(javax.servlet.ServletOutputStream) ServletContext(javax.servlet.ServletContext) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) WriteListener(javax.servlet.WriteListener) Test(org.testng.annotations.Test)

Aggregations

WriteListener (javax.servlet.WriteListener)31 ServletOutputStream (javax.servlet.ServletOutputStream)27 IOException (java.io.IOException)22 HttpServletRequest (javax.servlet.http.HttpServletRequest)17 HttpServletResponse (javax.servlet.http.HttpServletResponse)17 AsyncContext (javax.servlet.AsyncContext)12 Test (org.junit.Test)11 ServletException (javax.servlet.ServletException)10 CountDownLatch (java.util.concurrent.CountDownLatch)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 HttpServlet (javax.servlet.http.HttpServlet)6 InterruptedIOException (java.io.InterruptedIOException)5 ByteBuffer (java.nio.ByteBuffer)5 ReadListener (javax.servlet.ReadListener)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 Request (org.eclipse.jetty.server.Request)4 Before (org.junit.Before)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 UncheckedIOException (java.io.UncheckedIOException)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3