Search in sources :

Example 41 with AsyncListener

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;
}
Also used : ChangeRequestHistory(org.apache.druid.server.coordination.ChangeRequestHistory) 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) GET(javax.ws.rs.GET)

Example 42 with AsyncListener

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");
}
Also used : AsyncListener(javax.servlet.AsyncListener) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent)

Example 43 with AsyncListener

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));
}
Also used : AsyncListener(javax.servlet.AsyncListener) AsyncContext(javax.servlet.AsyncContext) AsyncEvent(javax.servlet.AsyncEvent) Test(org.junit.Test)

Example 44 with AsyncListener

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());
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AsyncListener(javax.servlet.AsyncListener) AsyncContext(javax.servlet.AsyncContext) IOException(java.io.IOException) AsyncEvent(javax.servlet.AsyncEvent) IOException(java.io.IOException)

Example 45 with AsyncListener

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);
}
Also used : AsyncListener(javax.servlet.AsyncListener) Test(org.junit.Test)

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