Search in sources :

Example 6 with ReadListener

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

use of javax.servlet.ReadListener 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)

Example 8 with ReadListener

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

the class AsyncIOServletTest method testOtherThreadOnAllDataRead.

@Test
public void testOtherThreadOnAllDataRead() throws Exception {
    String success = "SUCCESS";
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            assertScope();
            response.flushBuffer();
            AsyncContext async = request.startAsync();
            async.setTimeout(0);
            ServletInputStream input = request.getInputStream();
            ServletOutputStream output = response.getOutputStream();
            if (request.getDispatcherType() == DispatcherType.ERROR)
                throw new IllegalStateException();
            input.setReadListener(new ReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    assertScope();
                    async.start(() -> {
                        assertScope();
                        try {
                            sleep(1000);
                            if (!input.isReady())
                                throw new IllegalStateException();
                            if (input.read() != 'X')
                                throw new IllegalStateException();
                            if (!input.isReady())
                                throw new IllegalStateException();
                            if (input.read() != -1)
                                throw new IllegalStateException();
                        } catch (IOException x) {
                            throw new UncheckedIOException(x);
                        }
                    });
                }

                @Override
                public void onAllDataRead() throws IOException {
                    output.write(success.getBytes(StandardCharsets.UTF_8));
                    async.complete();
                }

                @Override
                public void onError(Throwable t) {
                    assertScope();
                    t.printStackTrace();
                    async.complete();
                }
            });
        }
    });
    byte[] data = "X".getBytes(StandardCharsets.UTF_8);
    CountDownLatch clientLatch = new CountDownLatch(1);
    DeferredContentProvider content = new DeferredContentProvider();
    client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).content(content).timeout(5, TimeUnit.SECONDS).send(new BufferingResponseListener() {

        @Override
        public void onComplete(Result result) {
            if (result.isSucceeded()) {
                Response response = result.getResponse();
                String content = getContentAsString();
                if (response.getStatus() == HttpStatus.OK_200 && success.equals(content))
                    clientLatch.countDown();
            }
        }
    });
    sleep(100);
    content.offer(ByteBuffer.wrap(data));
    content.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) Matchers.containsString(org.hamcrest.Matchers.containsString) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) 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) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Test(org.junit.Test)

Example 9 with ReadListener

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

the class AsyncIOServletTest method testOnAllDataRead.

@Test
public void testOnAllDataRead() throws Exception {
    String success = "SUCCESS";
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            assertScope();
            response.flushBuffer();
            AsyncContext async = request.startAsync();
            async.setTimeout(5000);
            ServletInputStream in = request.getInputStream();
            ServletOutputStream out = response.getOutputStream();
            in.setReadListener(new ReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    assertScope();
                    try {
                        sleep(1000);
                        if (!in.isReady())
                            throw new IllegalStateException();
                        if (in.read() != 'X')
                            throw new IllegalStateException();
                        if (!in.isReady())
                            throw new IllegalStateException();
                        if (in.read() != -1)
                            throw new IllegalStateException();
                    } catch (IOException x) {
                        throw new UncheckedIOException(x);
                    }
                }

                @Override
                public void onAllDataRead() throws IOException {
                    assertScope();
                    out.write(success.getBytes(StandardCharsets.UTF_8));
                    async.complete();
                }

                @Override
                public void onError(Throwable t) {
                    assertScope();
                    t.printStackTrace();
                    async.complete();
                }
            });
        }
    });
    byte[] data = "X".getBytes(StandardCharsets.UTF_8);
    CountDownLatch clientLatch = new CountDownLatch(1);
    DeferredContentProvider content = new DeferredContentProvider() {

        @Override
        public long getLength() {
            return data.length;
        }
    };
    client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).content(content).timeout(5, TimeUnit.SECONDS).send(new BufferingResponseListener() {

        @Override
        public void onComplete(Result result) {
            if (result.isSucceeded()) {
                Response response = result.getResponse();
                String content = getContentAsString();
                if (response.getStatus() == HttpStatus.OK_200 && success.equals(content))
                    clientLatch.countDown();
            }
        }
    });
    sleep(100);
    content.offer(ByteBuffer.wrap(data));
    content.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) Matchers.containsString(org.hamcrest.Matchers.containsString) UncheckedIOException(java.io.UncheckedIOException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) 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) BufferingResponseListener(org.eclipse.jetty.client.util.BufferingResponseListener) Test(org.junit.Test)

Example 10 with ReadListener

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

the class AsyncIOServletTest method testCompleteBeforeOnAllDataRead.

@Test
public void testCompleteBeforeOnAllDataRead() throws Exception {
    String success = "SUCCESS";
    AtomicBoolean allDataRead = new AtomicBoolean(false);
    start(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            assertScope();
            response.flushBuffer();
            AsyncContext async = request.startAsync();
            ServletInputStream input = request.getInputStream();
            ServletOutputStream output = response.getOutputStream();
            input.setReadListener(new ReadListener() {

                @Override
                public void onDataAvailable() throws IOException {
                    assertScope();
                    while (input.isReady()) {
                        int b = input.read();
                        if (b < 0) {
                            output.write(success.getBytes(StandardCharsets.UTF_8));
                            async.complete();
                            return;
                        }
                    }
                }

                @Override
                public void onAllDataRead() throws IOException {
                    assertScope();
                    output.write("FAILURE".getBytes(StandardCharsets.UTF_8));
                    allDataRead.set(true);
                    throw new IllegalStateException();
                }

                @Override
                public void onError(Throwable t) {
                    assertScope();
                    t.printStackTrace();
                }
            });
        }
    });
    ContentResponse response = client.newRequest(newURI()).method(HttpMethod.POST).path(servletPath).header(HttpHeader.CONNECTION, "close").content(new StringContentProvider("XYZ")).timeout(5, TimeUnit.SECONDS).send();
    assertThat(response.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
    assertThat(response.getContentAsString(), Matchers.equalTo(success));
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) StringContentProvider(org.eclipse.jetty.client.util.StringContentProvider) 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) ReadListener(javax.servlet.ReadListener) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServletInputStream(javax.servlet.ServletInputStream) Test(org.junit.Test)

Aggregations

ReadListener (javax.servlet.ReadListener)27 ServletInputStream (javax.servlet.ServletInputStream)22 HttpServletRequest (javax.servlet.http.HttpServletRequest)19 IOException (java.io.IOException)18 HttpServletResponse (javax.servlet.http.HttpServletResponse)18 ServletException (javax.servlet.ServletException)14 Test (org.junit.Test)14 AsyncContext (javax.servlet.AsyncContext)13 HttpServlet (javax.servlet.http.HttpServlet)12 InterruptedIOException (java.io.InterruptedIOException)11 UncheckedIOException (java.io.UncheckedIOException)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)9 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)7 Matchers.containsString (org.hamcrest.Matchers.containsString)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ServletOutputStream (javax.servlet.ServletOutputStream)5 Response (org.eclipse.jetty.client.api.Response)4 Result (org.eclipse.jetty.client.api.Result)4 BufferingResponseListener (org.eclipse.jetty.client.util.BufferingResponseListener)4