use of javax.servlet.AsyncListener in project pinpoint by naver.
the class ServletRequestImplStartAsyncInterceptor method doInAfterTrace.
@Override
protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
if (validate(target, result, throwable)) {
final AsyncContext asyncContext = (AsyncContext) result;
final AsyncListener asyncListener = new WeblogicAsyncListener(this.traceContext, recorder.recordNextAsyncContext(true));
asyncContext.addListener(asyncListener);
if (isDebug) {
logger.debug("Add async listener {}", asyncListener);
}
}
recorder.recordServiceType(WeblogicConstants.WEBLOGIC_METHOD);
recorder.recordApi(methodDescriptor);
recorder.recordException(throwable);
}
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)) {
com.navercorp.pinpoint.bootstrap.context.AsyncContext nextAsyncContext = recorder.recordNextAsyncContext(true);
// Add async listener
final AsyncContext asyncContext = (AsyncContext) result;
final AsyncListener asyncListener = new TomcatAsyncListener(this.traceContext, nextAsyncContext);
asyncContext.addListener(asyncListener);
// Set AsyncContext, AsyncListener
final HttpServletRequest request = (HttpServletRequest) target;
request.setAttribute(com.navercorp.pinpoint.bootstrap.context.AsyncContext.class.getName(), nextAsyncContext);
request.setAttribute(TomcatConstants.TOMCAT_SERVLET_REQUEST_TRACE, asyncListener);
if (isDebug) {
logger.debug("Add async listener {}", asyncListener);
}
}
recorder.recordServiceType(TomcatConstants.TOMCAT_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 pinpoint by naver.
the class HttpServletRequestImplStartAsyncInterceptor method doInAfterTrace.
@Override
protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
if (validate(target, result, throwable)) {
final AsyncContext asyncContext = (AsyncContext) result;
final AsyncListener asyncListener = new UndertowAsyncListener(this.traceContext, recorder.recordNextAsyncContext(true));
asyncContext.addListener(asyncListener);
if (isDebug) {
logger.debug("Add async listener {}", asyncListener);
}
}
recorder.recordServiceType(UndertowServletConstants.UNDERTOW_SERVLET_METHOD);
recorder.recordApi(methodDescriptor);
recorder.recordException(throwable);
}
use of javax.servlet.AsyncListener 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(), req.getRemoteAddr(), wrappedCtx, MAX_BUFFERED_CHUNKS, _logServletExceptions);
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();
}
}
});
}
use of javax.servlet.AsyncListener in project druid by druid-io.
the class SegmentListerResource method applyDataSegmentChangeRequests.
/**
* This endpoint is used by HttpLoadQueuePeon to assign segment load/drop requests batch. This endpoint makes the
* client wait till one of the following events occur. Note that this is implemented using async IO so no jetty
* threads are held while in wait.
*
* (1) Given timeout elapses.
* (2) Some load/drop request completed.
*
* It returns a map of "load/drop request -> SUCCESS/FAILED/PENDING status" for each request in the batch.
*/
@POST
@Path("/changeRequests")
@Produces({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
@Consumes({ MediaType.APPLICATION_JSON, SmileMediaTypes.APPLICATION_JACKSON_SMILE })
public void applyDataSegmentChangeRequests(@QueryParam("timeout") long timeout, List<DataSegmentChangeRequest> changeRequestList, @Context final HttpServletRequest req) throws IOException {
if (loadDropRequestHandler == null) {
sendErrorResponse(req, HttpServletResponse.SC_NOT_FOUND, "load/drop handler is not available.");
return;
}
if (timeout <= 0) {
sendErrorResponse(req, HttpServletResponse.SC_BAD_REQUEST, "timeout must be positive.");
return;
}
if (changeRequestList == null || changeRequestList.isEmpty()) {
sendErrorResponse(req, HttpServletResponse.SC_BAD_REQUEST, "No change requests provided.");
return;
}
final ResponseContext context = createContext(req.getHeader("Accept"));
final ListenableFuture<List<SegmentLoadDropHandler.DataSegmentChangeRequestAndStatus>> future = loadDropRequestHandler.processBatch(changeRequestList);
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<List<SegmentLoadDropHandler.DataSegmentChangeRequestAndStatus>>() {
@Override
public void onSuccess(List<SegmentLoadDropHandler.DataSegmentChangeRequestAndStatus> result) {
try {
HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
response.setStatus(HttpServletResponse.SC_OK);
context.inputMapper.writerWithType(HttpLoadQueuePeon.RESPONSE_ENTITY_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);
}
Aggregations