Search in sources :

Example 11 with AsyncListener

use of javax.servlet.AsyncListener in project tomcat70 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) {
            Assert.assertEquals(servletRequest, event.getSuppliedRequest());
            Assert.assertEquals(servletResponse, event.getSuppliedResponse());
        }
    };
    final Context context = EasyMock.createMock(Context.class);
    final Loader loader = EasyMock.createMock(Loader.class);
    final Response response = new Response();
    final Request request = new Request();
    request.setCoyoteRequest(new org.apache.coyote.Request());
    request.setContext(context);
    final AsyncContextImpl ac = new AsyncContextImpl(request);
    EasyMock.expect(context.getApplicationEventListeners()).andReturn(null);
    EasyMock.expect(context.getLoader()).andReturn(loader);
    EasyMock.expect(loader.getClassLoader()).andReturn(null);
    EasyMock.expect(Boolean.valueOf(context.fireRequestDestroyEvent(request.getRequest()))).andReturn(Boolean.TRUE);
    EasyMock.replay(context, loader);
    ac.addListener(listener, servletRequest, servletResponse);
    ac.setStarted(context, request, response, true);
    ac.addListener(listener, servletRequest, servletResponse);
    ac.setErrorState(new Exception(), true);
    ac.fireOnComplete();
    EasyMock.verify(context, loader);
}
Also used : AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) 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) Loader(org.apache.catalina.Loader) 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) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 12 with AsyncListener

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

the class MyAsyncServlet method processRequest.

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    AsyncContext asyncContext = request.startAsync();
    asyncContext.addListener(new AsyncListener() {

        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            event.getSuppliedResponse().getWriter().println("onComplete");
        }

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

        @Override
        public void onError(AsyncEvent event) throws IOException {
            event.getSuppliedResponse().getWriter().println("onError");
        }

        @Override
        public void onStartAsync(AsyncEvent event) throws IOException {
            event.getSuppliedResponse().getWriter().println("onStartAsync");
        }
    });
    executor.submit(new MyAsyncService(asyncContext));
}
Also used : AsyncListener(javax.servlet.AsyncListener) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent)

Example 13 with AsyncListener

use of javax.servlet.AsyncListener in project pinpoint by naver.

the class RequestStartAsyncInterceptor method after.

@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args, result, throwable);
    }
    final Trace trace = traceContext.currentTraceObject();
    if (trace == null) {
        return;
    }
    try {
        final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
        if (validate(target, result, throwable)) {
            // Add async listener. Servlet 3.0
            final AsyncContext asyncContext = (AsyncContext) result;
            final AsyncListener asyncListener = new JettyAsyncListener(this.traceContext, recorder.recordNextAsyncContext(true));
            asyncContext.addListener(asyncListener);
            if (isDebug) {
                logger.debug("Add async listener {}", asyncListener);
            }
        }
        recorder.recordServiceType(JettyConstants.JETTY_METHOD);
        recorder.recordApi(descriptor);
        recorder.recordException(throwable);
    } catch (Throwable t) {
        logger.warn("Failed to AFTER process. {}", t.getMessage(), t);
    } finally {
        trace.traceBlockEnd();
    }
}
Also used : Trace(com.navercorp.pinpoint.bootstrap.context.Trace) JettyAsyncListener(com.navercorp.pinpoint.plugin.jetty.JettyAsyncListener) SpanEventRecorder(com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder) AsyncListener(javax.servlet.AsyncListener) JettyAsyncListener(com.navercorp.pinpoint.plugin.jetty.JettyAsyncListener) AsyncContext(javax.servlet.AsyncContext)

Example 14 with AsyncListener

use of javax.servlet.AsyncListener in project druid by druid-io.

the class SegmentListerResource method getSegments.

/**
 * This endpoint is used by HttpServerInventoryView to keep an up-to-date list of segments served by
 * historical/realtime nodes.
 *
 * This endpoint lists segments served by this server and can also incrementally provide the segments added/dropped
 * since last response.
 *
 * Here is how, this is used.
 *
 * (1) Client sends first request /druid/internal/v1/segments?counter=-1&timeout=<timeout>
 * Server responds with list of segments currently served and a <counter,hash> pair.
 *
 * (2) Client sends subsequent requests /druid/internal/v1/segments?counter=<counter>&hash=<hash>&timeout=<timeout>
 * Where <counter,hash> values are used from the last response. Server responds with list of segment updates
 * since given counter.
 *
 * This endpoint makes the client wait till either there is some segment update or given timeout elapses.
 *
 * So, clients keep on sending next request immediately after receiving the response in order to keep the list
 * of segments served by this server up-to-date.
 *
 * @param counter counter received in last response.
 * @param hash hash received in last response.
 * @param timeout after which response is sent even if there are no new segment updates.
 * @param req
 * @return null to avoid "MUST return a non-void type" warning.
 * @throws IOException
 */
@GET
@Produces({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
@Consumes({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
public Void getSegments(@QueryParam("counter") long counter, @QueryParam("hash") long hash, @QueryParam("timeout") long timeout, @Context final HttpServletRequest req) throws IOException {
    if (announcer == null) {
        sendErrorResponse(req, HttpServletResponse.SC_NOT_FOUND, "announcer is not available.");
        return null;
    }
    if (timeout <= 0) {
        sendErrorResponse(req, HttpServletResponse.SC_BAD_REQUEST, "timeout must be positive.");
        return null;
    }
    final ResponseContext context = createContext(req.getHeader("Accept"));
    final ListenableFuture<ChangeRequestsSnapshot<DataSegmentChangeRequest>> future = announcer.getSegmentChangesSince(new ChangeRequestHistory.Counter(counter, hash));
    final AsyncContext asyncContext = req.startAsync();
    asyncContext.addListener(new AsyncListener() {

        @Override
        public void onComplete(AsyncEvent event) {
        }

        @Override
        public void onTimeout(AsyncEvent event) {
            // HTTP 204 NO_CONTENT is sent to the client.
            future.cancel(true);
            event.getAsyncContext().complete();
        }

        @Override
        public void onError(AsyncEvent event) {
        }

        @Override
        public void onStartAsync(AsyncEvent event) {
        }
    });
    Futures.addCallback(future, new FutureCallback<ChangeRequestsSnapshot<DataSegmentChangeRequest>>() {

        @Override
        public void onSuccess(ChangeRequestsSnapshot<DataSegmentChangeRequest> result) {
            try {
                HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
                response.setStatus(HttpServletResponse.SC_OK);
                context.inputMapper.writerWithType(HttpServerInventoryView.SEGMENT_LIST_RESP_TYPE_REF).writeValue(asyncContext.getResponse().getOutputStream(), result);
                asyncContext.complete();
            } catch (Exception ex) {
                log.debug(ex, "Request timed out or closed already.");
            }
        }

        @Override
        public void onFailure(Throwable th) {
            try {
                HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
                if (th instanceof IllegalArgumentException) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, th.getMessage());
                } else {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, th.getMessage());
                }
                asyncContext.complete();
            } catch (Exception ex) {
                log.debug(ex, "Request timed out or closed already.");
            }
        }
    });
    asyncContext.setTimeout(timeout);
    return null;
}
Also used : ChangeRequestHistory(org.apache.druid.server.coordination.ChangeRequestHistory) DataSegmentChangeRequest(org.apache.druid.server.coordination.DataSegmentChangeRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AsyncContext(javax.servlet.AsyncContext) AsyncEvent(javax.servlet.AsyncEvent) IOException(java.io.IOException) AsyncListener(javax.servlet.AsyncListener) ChangeRequestsSnapshot(org.apache.druid.server.coordination.ChangeRequestsSnapshot) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) GET(javax.ws.rs.GET)

Example 15 with AsyncListener

use of javax.servlet.AsyncListener in project chassis by Kixeye.

the class InstrumentedHandler method doStart.

@Override
protected void doStart() throws Exception {
    super.doStart();
    final String prefix = name(getHandler().getClass(), name);
    this.requests = timer(name(prefix, "requests"));
    this.dispatches = timer(name(prefix, "dispatches"));
    this.activeRequests = metricRegistry.counter(name(prefix, "active-requests"));
    this.activeDispatches = metricRegistry.counter(name(prefix, "active-dispatches"));
    this.activeSuspended = metricRegistry.counter(name(prefix, "active-suspended"));
    this.asyncDispatches = metricRegistry.meter(name(prefix, "async-dispatches"));
    this.asyncTimeouts = metricRegistry.meter(name(prefix, "async-timeouts"));
    this.responses = new Meter[] { // 1xx
    metricRegistry.meter(name(prefix, "1xx-responses")), // 2xx
    metricRegistry.meter(name(prefix, "2xx-responses")), // 3xx
    metricRegistry.meter(name(prefix, "3xx-responses")), // 4xx
    metricRegistry.meter(name(prefix, "4xx-responses")), // 5xx
    metricRegistry.meter(name(prefix, "5xx-responses")) };
    this.getRequests = timer(name(prefix, "get-requests"));
    this.postRequests = timer(name(prefix, "post-requests"));
    this.headRequests = timer(name(prefix, "head-requests"));
    this.putRequests = timer(name(prefix, "put-requests"));
    this.deleteRequests = timer(name(prefix, "delete-requests"));
    this.optionsRequests = timer(name(prefix, "options-requests"));
    this.traceRequests = timer(name(prefix, "trace-requests"));
    this.connectRequests = timer(name(prefix, "connect-requests"));
    this.moveRequests = timer(name(prefix, "move-requests"));
    this.otherRequests = timer(name(prefix, "other-requests"));
    this.listener = new AsyncListener() {

        @Override
        public void onTimeout(AsyncEvent event) throws IOException {
            asyncTimeouts.mark();
        }

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

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

        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            final AsyncContextState state = (AsyncContextState) event.getAsyncContext();
            final Request request = (Request) state.getRequest();
            updateResponses(request);
            if (!(state.getHttpChannelState().getState() == State.DISPATCHED)) {
                activeSuspended.dec();
            }
        }
    };
}
Also used : AsyncContextState(org.eclipse.jetty.server.AsyncContextState) AsyncListener(javax.servlet.AsyncListener) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent)

Aggregations

AsyncListener (javax.servlet.AsyncListener)45 AsyncContext (javax.servlet.AsyncContext)32 AsyncEvent (javax.servlet.AsyncEvent)30 IOException (java.io.IOException)28 HttpServletResponse (javax.servlet.http.HttpServletResponse)16 HttpServletRequest (javax.servlet.http.HttpServletRequest)14 ServletException (javax.servlet.ServletException)12 Test (org.junit.Test)12 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 CountDownLatch (java.util.concurrent.CountDownLatch)5 HttpServlet (javax.servlet.http.HttpServlet)5 OutputStream (java.io.OutputStream)4 Socket (java.net.Socket)3 URISyntaxException (java.net.URISyntaxException)3 CyclicBarrier (java.util.concurrent.CyclicBarrier)3 Request (org.eclipse.jetty.server.Request)3 Locker (org.eclipse.jetty.util.thread.Locker)3 RequestContext (com.linkedin.r2.message.RequestContext)2 TransportCallback (com.linkedin.r2.transport.common.bridge.common.TransportCallback)2 TransportResponse (com.linkedin.r2.transport.common.bridge.common.TransportResponse)2