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);
}
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));
}
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();
}
}
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;
}
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();
}
}
};
}
Aggregations