Search in sources :

Example 26 with AsyncEvent

use of javax.servlet.AsyncEvent in project tomcat by apache.

the class AsyncContextImpl method setErrorState.

public void setErrorState(Throwable t, boolean fireOnError) {
    if (t != null)
        request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
    request.getCoyoteRequest().action(ActionCode.ASYNC_ERROR, null);
    if (fireOnError) {
        AsyncEvent errorEvent = new AsyncEvent(event.getAsyncContext(), event.getSuppliedRequest(), event.getSuppliedResponse(), t);
        List<AsyncListenerWrapper> listenersCopy = new ArrayList<>();
        listenersCopy.addAll(listeners);
        for (AsyncListenerWrapper listener : listenersCopy) {
            try {
                listener.fireOnError(errorEvent);
            } catch (Throwable t2) {
                ExceptionUtils.handleThrowable(t);
                log.warn("onError() failed for listener of type [" + listener.getClass().getName() + "]", t2);
            }
        }
    }
    AtomicBoolean result = new AtomicBoolean();
    request.getCoyoteRequest().action(ActionCode.ASYNC_IS_ERROR, result);
    if (result.get()) {
        // SRV.2.3.3.3 (search for "error dispatch")
        if (servletResponse instanceof HttpServletResponse) {
            ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
        Host host = (Host) context.getParent();
        Valve stdHostValve = host.getPipeline().getBasic();
        if (stdHostValve instanceof StandardHostValve) {
            ((StandardHostValve) stdHostValve).throwable(request, request.getResponse(), t);
        }
        request.getCoyoteRequest().action(ActionCode.ASYNC_IS_ERROR, result);
        if (result.get()) {
            // Still in the error state. The error page did not call
            // complete() or dispatch(). Complete the async processing.
            complete();
        }
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) Valve(org.apache.catalina.Valve) Host(org.apache.catalina.Host) AsyncEvent(javax.servlet.AsyncEvent)

Example 27 with AsyncEvent

use of javax.servlet.AsyncEvent in project tomcat by apache.

the class TestAsyncContextImpl method testAsyncListenerSupplyRequestResponse.

@Test
public void testAsyncListenerSupplyRequestResponse() {
    final ServletRequest servletRequest = EasyMock.createMock(ServletRequest.class);
    final ServletResponse servletResponse = EasyMock.createMock(ServletResponse.class);
    final AsyncListener listener = new AsyncListener() {

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

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

        @Override
        public void onError(AsyncEvent event) throws IOException {
            checkRequestResponse(event);
        }

        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            checkRequestResponse(event);
        }

        private void checkRequestResponse(AsyncEvent event) {
            assertEquals(servletRequest, event.getSuppliedRequest());
            assertEquals(servletResponse, event.getSuppliedResponse());
        }
    };
    final Context context = new TesterContext();
    final Response response = new Response();
    final Request request = new Request(null);
    request.setCoyoteRequest(new org.apache.coyote.Request());
    request.getMappingData().context = context;
    final AsyncContextImpl ac = new AsyncContextImpl(request);
    ac.addListener(listener, servletRequest, servletResponse);
    ac.setStarted(context, request, response, true);
    ac.addListener(listener, servletRequest, servletResponse);
    ac.setErrorState(new Exception(), true);
    ac.fireOnComplete();
}
Also used : AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) TesterContext(org.apache.tomcat.unittest.TesterContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) HttpServletRequest(javax.servlet.http.HttpServletRequest) Request(org.apache.catalina.connector.Request) ServletRequest(javax.servlet.ServletRequest) AsyncEvent(javax.servlet.AsyncEvent) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.apache.catalina.connector.Response) ServletResponse(javax.servlet.ServletResponse) AsyncListener(javax.servlet.AsyncListener) TesterContext(org.apache.tomcat.unittest.TesterContext) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 28 with AsyncEvent

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

the class IdleTimeoutHandler method handle.

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    final HttpChannel channel = baseRequest.getHttpChannel();
    final long idle_timeout = baseRequest.getHttpChannel().getIdleTimeout();
    channel.setIdleTimeout(_idleTimeoutMs);
    try {
        super.handle(target, baseRequest, request, response);
    } finally {
        if (_applyToAsync && request.isAsyncStarted()) {
            request.getAsyncContext().addListener(new AsyncListener() {

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

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

                @Override
                public void onError(AsyncEvent event) throws IOException {
                    channel.setIdleTimeout(idle_timeout);
                }

                @Override
                public void onComplete(AsyncEvent event) throws IOException {
                    channel.setIdleTimeout(idle_timeout);
                }
            });
        } else
            channel.setIdleTimeout(idle_timeout);
    }
}
Also used : AsyncListener(javax.servlet.AsyncListener) HttpChannel(org.eclipse.jetty.server.HttpChannel) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent)

Example 29 with AsyncEvent

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

the class StatisticsHandlerTest method testSuspendExpire.

@Test
public void testSuspendExpire() throws Exception {
    final long dispatchTime = 10;
    final long timeout = 100;
    final AtomicReference<AsyncContext> asyncHolder = new AtomicReference<>();
    final CyclicBarrier[] barrier = { new CyclicBarrier(2), new CyclicBarrier(2), new CyclicBarrier(2) };
    _statsHandler.setHandler(new AbstractHandler() {

        @Override
        public void handle(String path, Request request, HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException {
            request.setHandled(true);
            try {
                barrier[0].await();
                Thread.sleep(dispatchTime);
                if (asyncHolder.get() == null) {
                    AsyncContext async = request.startAsync();
                    asyncHolder.set(async);
                    async.setTimeout(timeout);
                }
            } catch (Exception x) {
                throw new ServletException(x);
            } finally {
                try {
                    barrier[1].await();
                } catch (Exception ignored) {
                }
            }
        }
    });
    _server.start();
    String request = "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n";
    _connector.executeRequest(request);
    barrier[0].await();
    assertEquals(1, _statistics.getConnections());
    assertEquals(1, _statsHandler.getRequests());
    assertEquals(1, _statsHandler.getRequestsActive());
    assertEquals(1, _statsHandler.getDispatched());
    assertEquals(1, _statsHandler.getDispatchedActive());
    barrier[1].await();
    assertTrue(_latchHandler.await());
    assertNotNull(asyncHolder.get());
    asyncHolder.get().addListener(new AsyncListener() {

        @Override
        public void onTimeout(AsyncEvent event) throws IOException {
            event.getAsyncContext().complete();
        }

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

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

        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            try {
                barrier[2].await();
            } catch (Exception ignored) {
            }
        }
    });
    assertEquals(1, _statsHandler.getRequests());
    assertEquals(1, _statsHandler.getRequestsActive());
    assertEquals(1, _statsHandler.getDispatched());
    assertEquals(0, _statsHandler.getDispatchedActive());
    barrier[2].await();
    assertEquals(1, _statsHandler.getRequests());
    assertEquals(0, _statsHandler.getRequestsActive());
    assertEquals(1, _statsHandler.getDispatched());
    assertEquals(0, _statsHandler.getDispatchedActive());
    assertEquals(1, _statsHandler.getAsyncRequests());
    assertEquals(0, _statsHandler.getAsyncDispatches());
    assertEquals(1, _statsHandler.getExpires());
    assertEquals(1, _statsHandler.getResponses2xx());
    assertTrue(_statsHandler.getRequestTimeTotal() >= (timeout + dispatchTime) * 3 / 4);
    assertEquals(_statsHandler.getRequestTimeTotal(), _statsHandler.getRequestTimeMax());
    assertEquals(_statsHandler.getRequestTimeTotal(), _statsHandler.getRequestTimeMean(), 0.01);
    assertThat(_statsHandler.getDispatchedTimeTotal(), greaterThanOrEqualTo(dispatchTime * 3 / 4));
}
Also used : Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) CyclicBarrier(java.util.concurrent.CyclicBarrier) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AsyncListener(javax.servlet.AsyncListener) Test(org.junit.Test)

Example 30 with AsyncEvent

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

Aggregations

AsyncEvent (javax.servlet.AsyncEvent)39 IOException (java.io.IOException)27 Test (org.junit.Test)21 AsyncListener (javax.servlet.AsyncListener)20 AsyncContext (javax.servlet.AsyncContext)19 HttpServletResponse (javax.servlet.http.HttpServletResponse)17 HttpServletRequest (javax.servlet.http.HttpServletRequest)16 ServletException (javax.servlet.ServletException)12 HttpServlet (javax.servlet.http.HttpServlet)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 OutputStream (java.io.OutputStream)4 Request (org.eclipse.jetty.server.Request)4 Socket (java.net.Socket)3 URISyntaxException (java.net.URISyntaxException)3 CyclicBarrier (java.util.concurrent.CyclicBarrier)3 ServletResponse (javax.servlet.ServletResponse)3 HttpTester (org.eclipse.jetty.http.HttpTester)3 MockAsyncContext (org.springframework.mock.web.test.MockAsyncContext)3 RequestContext (com.linkedin.r2.message.RequestContext)2