use of javax.servlet.AsyncListener in project druid by druid-io.
the class TaskManagementResource method getWorkerState.
/**
* This endpoint is used by HttpRemoteTaskRunner to keep an up-to-date state of the worker wrt to the tasks it is
* running, completed etc and other metadata such as its enabled/disabled status.
*
* Here is how, this is used.
*
* (1) Client sends first request /druid/internal/v1/worker?counter=-1&timeout=<timeout>
* Server responds with current list of running/completed tasks and metadata. And, a <counter,hash> pair.
*
* (2) Client sends subsequent requests /druid/internal/v1/worker?counter=<counter>&hash=<hash>&timeout=<timeout>
* Where <counter,hash> values are used from the last response. Server responds with changes since then.
*
* This endpoint makes the client wait till either there is some update or given timeout elapses.
*
* So, clients keep on sending next request immediately after receiving the response in order to keep the state of
* 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 })
public Void getWorkerState(@QueryParam("counter") long counter, @QueryParam("hash") long hash, @QueryParam("timeout") long timeout, @Context final HttpServletRequest req) throws IOException {
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<WorkerHistoryItem>> future = workerTaskManager.getChangesSince(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>() {
@Override
public void onSuccess(ChangeRequestsSnapshot result) {
try {
HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
response.setStatus(HttpServletResponse.SC_OK);
context.inputMapper.writerWithType(WorkerHolder.WORKER_SYNC_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 undertow by undertow-io.
the class AsyncErrorListenerServlet method doGet.
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
AsyncContext ac = req.startAsync();
ac.addListener(new AsyncListener() {
@Override
public void onComplete(AsyncEvent event) throws IOException {
EVENTS.add("COMPLETED");
}
@Override
public void onTimeout(AsyncEvent event) throws IOException {
}
@Override
public void onError(AsyncEvent event) throws IOException {
EVENTS.add("ERROR");
}
@Override
public void onStartAsync(AsyncEvent event) throws IOException {
}
});
throw new RuntimeException("FAILED");
}
use of javax.servlet.AsyncListener in project ddf by codice.
the class ServletMetricsTest method asyncDoFilterError.
@Test
public void asyncDoFilterError() throws Exception {
when(mockRequest.isAsyncStarted()).thenReturn(true);
AsyncContext asyncContext = mock(AsyncContext.class);
when(mockRequest.getAsyncContext()).thenReturn(asyncContext);
AsyncEvent event = mock(AsyncEvent.class);
when(event.getSuppliedRequest()).thenReturn(mockRequest);
when(event.getSuppliedResponse()).thenReturn(mockResponse);
underTest.doFilter(mockRequest, mockResponse, mockFilterChain);
ArgumentCaptor<AsyncListener> arg = ArgumentCaptor.forClass(AsyncListener.class);
verify(asyncContext).addListener(arg.capture());
AsyncListener listener = arg.getValue();
listener.onStartAsync(event);
listener.onError(event);
listener.onComplete(event);
assertThat(meterRegistry.summary(LATENCY, getTags(DEFAULT_METHOD, 500)).count(), is(1L));
}
use of javax.servlet.AsyncListener in project tomee by apache.
the class CalcServlet method process.
private void process(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
if (req.getAttribute(RESULT_ATTRIBUTE) == null) {
final ResultHolder result = new ResultHolder();
req.setAttribute("RESULT", result);
final String operation = req.getParameter("op");
final String asyncParam = req.getParameter("async");
final String delayParam = req.getParameter("delay");
final String timeoutParam = req.getParameter("timeout");
final String xParam = req.getParameter("x");
final String yParam = req.getParameter("y");
if (operation == null || (!OPERATIONS.contains(operation.toUpperCase()))) {
displayUsage(resp);
return;
}
final int x;
try {
x = Integer.parseInt(xParam);
} catch (final Exception e) {
displayUsage(resp);
return;
}
final int y;
try {
y = Integer.parseInt(yParam);
} catch (final Exception e) {
displayUsage(resp);
return;
}
int delay = 0;
try {
delay = Integer.parseInt(delayParam);
} catch (final Exception e) {
// ignore
}
int timeout = -1;
try {
timeout = Integer.parseInt(timeoutParam);
} catch (final Exception e) {
// ignore
}
boolean async = false;
try {
async = Boolean.parseBoolean(asyncParam);
} catch (final Exception e) {
// ignore
}
if (!async) {
process(operation, x, y, result);
resp.getWriter().print(result.getResult());
return;
}
final int threadDelay = delay;
final AsyncContext asyncContext = req.startAsync();
final AtomicBoolean interrupted = new AtomicBoolean(false);
asyncContext.addListener(new AsyncListener() {
@Override
public void onComplete(AsyncEvent asyncEvent) throws IOException {
}
@Override
public void onTimeout(AsyncEvent asyncEvent) throws IOException {
interrupted.set(true);
}
@Override
public void onError(AsyncEvent asyncEvent) throws IOException {
interrupted.set(true);
}
@Override
public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
}
});
asyncContext.setTimeout(timeout);
asyncContext.start(() -> {
try {
Thread.sleep(threadDelay);
} catch (final InterruptedException e) {
// ignore
}
try {
process(operation, x, y, result);
} finally {
if (!interrupted.get()) {
// do not call dispatch if this request has timed-out or errored
asyncContext.dispatch();
}
}
});
} else {
final ResultHolder result = (ResultHolder) req.getAttribute("RESULT");
resp.getWriter().print(result.getResult());
}
}
use of javax.servlet.AsyncListener in project sonarqube by SonarSource.
the class ServerPushClientTest method addListener_addsListener.
@Test
public void addListener_addsListener() {
AsyncListener mock = mock(AsyncListener.class);
underTest.addListener(mock);
verify(asyncContext).addListener(mock);
}
Aggregations