Search in sources :

Example 91 with AsyncContext

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

the class AsyncListenerTest method test_StartAsync_OnTimeout_SendError_CustomErrorPage.

@Test
public void test_StartAsync_OnTimeout_SendError_CustomErrorPage() throws Exception {
    test_StartAsync_OnTimeout(500, event -> {
        AsyncContext asyncContext = event.getAsyncContext();
        HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
        response.sendError(HttpStatus.BAD_GATEWAY_502);
        asyncContext.complete();
    });
    // Add a custom error page.
    ErrorHandler errorHandler = new ErrorHandler() {

        @Override
        protected void writeErrorPageMessage(HttpServletRequest request, Writer writer, int code, String message, String uri) throws IOException {
            writer.write("CUSTOM\n");
            super.writeErrorPageMessage(request, writer, code, message, uri);
        }
    };
    errorHandler.setServer(server);
    server.setErrorHandler(errorHandler);
    String httpResponse = connector.getResponse("" + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n");
    assertThat(httpResponse, containsString("HTTP/1.1 502 "));
    assertThat(httpResponse, containsString("CUSTOM"));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ErrorHandler(org.eclipse.jetty.server.handler.ErrorHandler) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) Matchers.containsString(org.hamcrest.Matchers.containsString) Writer(java.io.Writer) Test(org.junit.Test)

Example 92 with AsyncContext

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

the class AsyncServletLongPollTest method testSuspendedRequestCompletedByAnotherRequest.

@Test
public void testSuspendedRequestCompletedByAnotherRequest() throws Exception {
    final CountDownLatch asyncLatch = new CountDownLatch(1);
    prepare(new HttpServlet() {

        private volatile AsyncContext asyncContext;

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            int suspend = 0;
            String param = request.getParameter("suspend");
            if (param != null)
                suspend = Integer.parseInt(param);
            if (suspend > 0) {
                asyncContext = request.startAsync();
                asyncLatch.countDown();
            }
        }

        @Override
        protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            int error = 0;
            String param = request.getParameter("error");
            if (param != null)
                error = Integer.parseInt(param);
            final AsyncContext asyncContext = this.asyncContext;
            if (asyncContext != null) {
                HttpServletResponse asyncResponse = (HttpServletResponse) asyncContext.getResponse();
                asyncResponse.sendError(error);
                asyncContext.complete();
            } else {
                response.sendError(404);
            }
        }
    });
    try (Socket socket1 = new Socket("localhost", connector.getLocalPort())) {
        int wait = 1000;
        String request1 = "GET " + uri + "?suspend=" + wait + " HTTP/1.1\r\n" + "Host: localhost:" + connector.getLocalPort() + "\r\n" + "\r\n";
        OutputStream output1 = socket1.getOutputStream();
        output1.write(request1.getBytes(StandardCharsets.UTF_8));
        output1.flush();
        Assert.assertTrue(asyncLatch.await(5, TimeUnit.SECONDS));
        int error = 408;
        try (Socket socket2 = new Socket("localhost", connector.getLocalPort())) {
            String request2 = "DELETE " + uri + "?error=" + error + " HTTP/1.1\r\n" + "Host: localhost:" + connector.getLocalPort() + "\r\n" + "\r\n";
            OutputStream output2 = socket2.getOutputStream();
            output2.write(request2.getBytes(StandardCharsets.UTF_8));
            output2.flush();
            HttpTester.Input input2 = HttpTester.from(socket2.getInputStream());
            HttpTester.Response response2 = HttpTester.parseResponse(input2);
            Assert.assertEquals(200, response2.getStatus());
        }
        socket1.setSoTimeout(2 * wait);
        HttpTester.Input input1 = HttpTester.from(socket1.getInputStream());
        HttpTester.Response response1 = HttpTester.parseResponse(input1);
        Assert.assertEquals(error, response1.getStatus());
        // Now try to make another request on the first connection
        // to verify that we set correctly the read interest (#409842)
        String request3 = "GET " + uri + " HTTP/1.1\r\n" + "Host: localhost:" + connector.getLocalPort() + "\r\n" + "\r\n";
        output1.write(request3.getBytes(StandardCharsets.UTF_8));
        output1.flush();
        HttpTester.Response response3 = HttpTester.parseResponse(input1);
        Assert.assertEquals(200, response3.getStatus());
    }
}
Also used : HttpServlet(javax.servlet.http.HttpServlet) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) HttpTester(org.eclipse.jetty.http.HttpTester) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Socket(java.net.Socket) Test(org.junit.Test)

Example 93 with AsyncContext

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

the class AsyncContextListenersTest method testListenerClearedOnSecondRequest.

@SuppressWarnings("Duplicates")
@Test
public void testListenerClearedOnSecondRequest() throws Exception {
    final AtomicReference<CountDownLatch> completes = new AtomicReference<>(new CountDownLatch(1));
    String path = "/path";
    prepare(path, new HttpServlet() {

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

                @Override
                public void onStartAsync(AsyncEvent event) throws IOException {
                }

                @Override
                public void onComplete(AsyncEvent event) throws IOException {
                    completes.get().countDown();
                }

                @Override
                public void onTimeout(AsyncEvent event) throws IOException {
                }

                @Override
                public void onError(AsyncEvent event) throws IOException {
                }
            });
            asyncContext.complete();
        }
    });
    try (Socket socket = new Socket("localhost", _connector.getLocalPort())) {
        OutputStream output = socket.getOutputStream();
        String request = "" + "GET " + path + " HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n";
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        HttpTester.Input input = HttpTester.from(socket.getInputStream());
        HttpTester.Response response = HttpTester.parseResponse(input);
        Assert.assertEquals(200, response.getStatus());
        completes.get().await(10, TimeUnit.SECONDS);
        // Send a second request
        completes.set(new CountDownLatch(1));
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        response = HttpTester.parseResponse(input);
        Assert.assertEquals(200, response.getStatus());
        completes.get().await(10, TimeUnit.SECONDS);
    }
}
Also used : HttpServlet(javax.servlet.http.HttpServlet) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncEvent(javax.servlet.AsyncEvent) HttpTester(org.eclipse.jetty.http.HttpTester) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AsyncListener(javax.servlet.AsyncListener) Socket(java.net.Socket) Test(org.junit.Test)

Example 94 with AsyncContext

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

the class AsyncContextListenersTest method testAsyncDispatchAsyncCompletePreservesListener.

@Test
public void testAsyncDispatchAsyncCompletePreservesListener() throws Exception {
    final AtomicReference<CountDownLatch> completes = new AtomicReference<>(new CountDownLatch(1));
    final String path = "/path";
    prepare(path + "/*", new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String requestURI = request.getRequestURI();
            if (requestURI.endsWith("/one")) {
                AsyncContext asyncContext = request.startAsync(request, response);
                asyncContext.addListener(new AsyncListener() {

                    @Override
                    public void onStartAsync(AsyncEvent event) throws IOException {
                        event.getAsyncContext().addListener(this);
                    }

                    @Override
                    public void onComplete(AsyncEvent event) throws IOException {
                        completes.get().countDown();
                    }

                    @Override
                    public void onTimeout(AsyncEvent event) throws IOException {
                    }

                    @Override
                    public void onError(AsyncEvent event) throws IOException {
                    }
                });
                // This dispatch() will call startAsync() again which will
                // clear the previous listeners (as per the specification)
                // but add a new listener from onStartAsync().
                asyncContext.dispatch(path + "/two");
            } else if (requestURI.endsWith("/two")) {
                AsyncContext asyncContext = request.startAsync(request, response);
                asyncContext.complete();
            }
        }
    });
    try (Socket socket = new Socket("localhost", _connector.getLocalPort())) {
        OutputStream output = socket.getOutputStream();
        String request = "" + "GET " + path + "/one HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n";
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        HttpTester.Input input = HttpTester.from(socket.getInputStream());
        HttpTester.Response response = HttpTester.parseResponse(input);
        Assert.assertEquals(200, response.getStatus());
        completes.get().await(10, TimeUnit.SECONDS);
        // Send a second request
        completes.set(new CountDownLatch(1));
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        response = HttpTester.parseResponse(input);
        Assert.assertEquals(200, response.getStatus());
        completes.get().await(10, TimeUnit.SECONDS);
    }
}
Also used : HttpServlet(javax.servlet.http.HttpServlet) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncEvent(javax.servlet.AsyncEvent) HttpTester(org.eclipse.jetty.http.HttpTester) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AsyncListener(javax.servlet.AsyncListener) Socket(java.net.Socket) Test(org.junit.Test)

Example 95 with AsyncContext

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

the class AsyncListenerTest method test_StartAsync_OnComplete_Throw.

@Test
public void test_StartAsync_OnComplete_Throw() throws Exception {
    ServletContextHandler context = new ServletContextHandler();
    context.addServlet(new ServletHolder(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            AsyncContext asyncContext = request.startAsync();
            asyncContext.setTimeout(0);
            asyncContext.addListener(new AsyncListenerAdapter() {

                @Override
                public void onComplete(AsyncEvent event) throws IOException {
                    throw new TestRuntimeException();
                }
            });
            response.getOutputStream().print("DATA");
            asyncContext.complete();
        }
    }), "/*");
    startServer(context);
    String httpResponse = connector.getResponse("" + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n");
    assertThat(httpResponse, containsString("HTTP/1.1 200 "));
    assertThat(httpResponse, containsString("DATA"));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) Matchers.containsString(org.hamcrest.Matchers.containsString) AsyncEvent(javax.servlet.AsyncEvent) Test(org.junit.Test)

Aggregations

AsyncContext (javax.servlet.AsyncContext)120 IOException (java.io.IOException)61 HttpServletRequest (javax.servlet.http.HttpServletRequest)53 ServletException (javax.servlet.ServletException)52 HttpServletResponse (javax.servlet.http.HttpServletResponse)50 Test (org.junit.Test)43 CountDownLatch (java.util.concurrent.CountDownLatch)33 HttpServlet (javax.servlet.http.HttpServlet)32 InterruptedIOException (java.io.InterruptedIOException)24 ServletOutputStream (javax.servlet.ServletOutputStream)20 ReadListener (javax.servlet.ReadListener)19 ServletInputStream (javax.servlet.ServletInputStream)19 AsyncEvent (javax.servlet.AsyncEvent)18 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)18 AsyncListener (javax.servlet.AsyncListener)15 UncheckedIOException (java.io.UncheckedIOException)14 DeferredContentProvider (org.eclipse.jetty.client.util.DeferredContentProvider)14 Request (org.eclipse.jetty.server.Request)13 Matchers.containsString (org.hamcrest.Matchers.containsString)13 WriteListener (javax.servlet.WriteListener)11