Search in sources :

Example 96 with AsyncContext

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

the class AsyncListenerTest method test_StartAsync_OnTimeout_CalledBy_PooledThread.

@Test
public void test_StartAsync_OnTimeout_CalledBy_PooledThread() throws Exception {
    String threadNamePrefix = "async_listener";
    threadPool = new QueuedThreadPool();
    threadPool.setName(threadNamePrefix);
    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(1000);
            asyncContext.addListener(new AsyncListenerAdapter() {

                @Override
                public void onTimeout(AsyncEvent event) throws IOException {
                    if (Thread.currentThread().getName().startsWith(threadNamePrefix))
                        response.setStatus(HttpStatus.OK_200);
                    else
                        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
                    asyncContext.complete();
                }
            });
        }
    }), "/*");
    startServer(context);
    HttpTester.Response response = HttpTester.parseResponse(connector.getResponse("" + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "\r\n"));
    Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
}
Also used : HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent) HttpTester(org.eclipse.jetty.http.HttpTester) HttpServletRequest(javax.servlet.http.HttpServletRequest) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) Test(org.junit.Test)

Example 97 with AsyncContext

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

the class Servlet3Continuation method resume.

/* ------------------------------------------------------------ */
@Override
public void resume() {
    AsyncContext context = _context;
    if (context == null)
        throw new IllegalStateException();
    _resumed = true;
    _context.dispatch();
}
Also used : AsyncContext(javax.servlet.AsyncContext)

Example 98 with AsyncContext

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

the class ProxyServletTest method testProxyLongPoll.

@Test
public void testProxyLongPoll() throws Exception {
    final long timeout = 1000;
    startServer(new HttpServlet() {

        @Override
        protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
            if (!request.isAsyncStarted()) {
                final AsyncContext asyncContext = request.startAsync();
                asyncContext.setTimeout(timeout);
                asyncContext.addListener(new AsyncListener() {

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

                    @Override
                    public void onTimeout(AsyncEvent event) throws IOException {
                        if (request.getHeader("Via") != null)
                            response.addHeader(PROXIED_HEADER, "true");
                        asyncContext.complete();
                    }

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

                    @Override
                    public void onStartAsync(AsyncEvent event) throws IOException {
                    }
                });
            }
        }
    });
    startProxy();
    startClient();
    Response response = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(2 * timeout, TimeUnit.MILLISECONDS).send();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) HttpServlet(javax.servlet.http.HttpServlet) AsyncListener(javax.servlet.AsyncListener) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent) Test(org.junit.Test)

Example 99 with AsyncContext

use of javax.servlet.AsyncContext in project javaee7-samples by javaee-samples.

the class AsyncServlet method doGet.

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    AsyncContext asyncContext = request.startAsync();
    asyncContext.setTimeout(5000);
    asyncBean.doAsync(asyncContext);
}
Also used : AsyncContext(javax.servlet.AsyncContext)

Example 100 with AsyncContext

use of javax.servlet.AsyncContext in project rest.li by linkedin.

the class AbstractAsyncR2StreamServlet method service.

@Override
public void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    final AsyncContext ctx = req.startAsync(req, resp);
    ctx.setTimeout(_timeout);
    final WrappedAsyncContext wrappedCtx = new WrappedAsyncContext(ctx);
    final AsyncEventIOHandler ioHandler = new AsyncEventIOHandler(req.getInputStream(), resp.getOutputStream(), wrappedCtx, MAX_BUFFERED_CHUNKS);
    final RequestContext requestContext = ServletHelper.readRequestContext(req);
    final StreamRequest streamRequest;
    try {
        streamRequest = ServletHelper.readFromServletRequest(req, ioHandler);
    } catch (URISyntaxException e) {
        ServletHelper.writeToServletError(resp, RestStatus.BAD_REQUEST, e.toString());
        wrappedCtx.complete();
        return;
    }
    final AtomicBoolean startedResponding = new AtomicBoolean(false);
    ctx.addListener(new AsyncListener() {

        @Override
        public void onTimeout(AsyncEvent event) throws IOException {
            LOG.error("Server timeout for request: " + formatURI(req.getRequestURI()));
            if (startedResponding.compareAndSet(false, true)) {
                LOG.info("Returning server timeout response");
                ServletHelper.writeToServletError(resp, RestStatus.INTERNAL_SERVER_ERROR, "Server timeout");
            } else {
                req.setAttribute(ASYNC_IOEXCEPTION, new ServletException("Server timeout"));
            }
            ioHandler.exitLoop();
            wrappedCtx.complete();
        }

        @Override
        public void onStartAsync(AsyncEvent event) throws IOException {
        // Nothing to do here
        }

        @Override
        public void onError(AsyncEvent event) throws IOException {
            LOG.error("Server error for request: " + formatURI(req.getRequestURI()));
            if (startedResponding.compareAndSet(false, true)) {
                LOG.info("Returning server error response");
                ServletHelper.writeToServletError(resp, RestStatus.INTERNAL_SERVER_ERROR, "Server error");
            } else {
                req.setAttribute(ASYNC_IOEXCEPTION, new ServletException("Server error"));
            }
            ioHandler.exitLoop();
            wrappedCtx.complete();
        }

        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            Object exception = req.getAttribute(ASYNC_IOEXCEPTION);
            if (exception != null) {
                throw new IOException((Throwable) exception);
            }
        }
    });
    final TransportCallback<StreamResponse> callback = new TransportCallback<StreamResponse>() {

        @Override
        public void onResponse(final TransportResponse<StreamResponse> response) {
            if (startedResponding.compareAndSet(false, true)) {
                ctx.start(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            StreamResponse streamResponse = ServletHelper.writeResponseHeadersToServletResponse(response, resp);
                            streamResponse.getEntityStream().setReader(ioHandler);
                            ioHandler.loop();
                        } catch (Exception e) {
                            req.setAttribute(ASYNC_IOEXCEPTION, e);
                            wrappedCtx.complete();
                        }
                    }
                });
            } else {
                LOG.error("Dropped a response; this is mostly like because that AsyncContext timeout or error had already happened");
            }
        }
    };
    // we have to use a new thread and let this thread return to pool. otherwise the timeout won't start
    ctx.start(new Runnable() {

        @Override
        public void run() {
            try {
                getDispatcher().handleRequest(streamRequest, requestContext, callback);
                ioHandler.loop();
            } catch (Exception e) {
                req.setAttribute(ASYNC_IOEXCEPTION, e);
                wrappedCtx.complete();
            }
        }
    });
}
Also used : TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) AsyncContext(javax.servlet.AsyncContext) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent) TransportResponse(com.linkedin.r2.transport.common.bridge.common.TransportResponse) ServletException(javax.servlet.ServletException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) ServletException(javax.servlet.ServletException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AsyncListener(javax.servlet.AsyncListener) RequestContext(com.linkedin.r2.message.RequestContext)

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