Java Code Examples for javax.servlet.AsyncContext#addListener()

The following examples show how to use javax.servlet.AsyncContext#addListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AsyncStockServlet.java    From Tomcat8-Source-Read with MIT License 7 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    if (req.isAsyncStarted()) {
        req.getAsyncContext().complete();
    } else if (req.isAsyncSupported()) {
        AsyncContext actx = req.startAsync();
        actx.addListener(this);
        resp.setContentType("text/plain");
        clients.add(actx);
        if (clientcount.incrementAndGet()==1) {
            Stockticker ticker = (Stockticker) req.getServletContext().getAttribute(
                    AsyncStockContextListener.STOCK_TICKER_KEY);
            ticker.addTickListener(this);
        }
    } else {
        new Exception("Async Not Supported").printStackTrace();
        resp.sendError(400,"Async is not supported.");
    }
}
 
Example 2
Source File: AsyncStockServlet.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    if (req.isAsyncStarted()) {
        req.getAsyncContext().complete();
    } else if (req.isAsyncSupported()) {
        AsyncContext actx = req.startAsync();
        actx.addListener(this);
        resp.setContentType("text/plain");
        clients.add(actx);
        if (clientcount.incrementAndGet()==1) {
            Stockticker ticker = (Stockticker) req.getServletContext().getAttribute(
                    AsyncStockContextListener.STOCK_TICKER_KEY);
            ticker.addTickListener(this);
        }
    } else {
        new Exception("Async Not Supported").printStackTrace();
        resp.sendError(400,"Async is not supported.");
    }
}
 
Example 3
Source File: AsyncStockServlet.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    if (req.isAsyncStarted()) {
        req.getAsyncContext().complete();
    } else if (req.isAsyncSupported()) {
        AsyncContext actx = req.startAsync();
        actx.addListener(this);
        resp.setContentType("text/plain");
        clients.add(actx);
        if (clientcount.incrementAndGet()==1) {
            ticker.addTickListener(this);
        }
    } else {
        new Exception("Async Not Supported").printStackTrace();
        resp.sendError(400,"Async is not supported.");
    }
}
 
Example 4
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {

    final AsyncContext asyncContext =
        request.startAsync(request, response);

    asyncContext.addListener(new TrackingListener(false, false, null));

    asyncContext.start(new Runnable() {

        @Override
        public void run() {
            try {
                Thread.sleep(THREAD_SLEEP_TIME);
                TestAsyncContextImpl.track("Runnable-");
                asyncContext.complete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
 
Example 5
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    if (req.isAsyncSupported()) {
        TestAsyncContextImpl.track("TimeoutServletGet-");
        final AsyncContext ac = req.startAsync();
        ac.setTimeout(ASYNC_TIMEOUT);

        if (completeOnTimeout != null) {
            ac.addListener(new TrackingListener(false,
                    completeOnTimeout.booleanValue(), dispatchUrl));
        }
    } else {
        resp.getWriter().print("FAIL: Async unsupported");
    }
}
 
Example 6
Source File: RequestStartAsyncInterceptor.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
protected void doInAfterTrace(SpanEventRecorder recorder, Object target, Object[] args, Object result, Throwable throwable) {
    if (validate(target, result, throwable)) {
        // Add async listener. Servlet 3.0
        final AsyncContext asyncContext = (AsyncContext) result;
        final AsyncListener asyncListener = new JbossAsyncListener(this.traceContext, recorder.recordNextAsyncContext(true));
        asyncContext.addListener(asyncListener);
        if (isDebug) {
            logger.debug("Add async listener {}", asyncListener);
        }
    }

    recorder.recordServiceType(JbossConstants.JBOSS_METHOD);
    recorder.recordApi(methodDescriptor);
    recorder.recordException(throwable);
}
 
Example 7
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    track("doGet-startAsync-");
    AsyncContext ac = req.startAsync();
    if (addTrackingListener) {
        ac.addListener(new StickyTrackingListener(false, false, null));
    }
    ac.dispatch(target);
 }
 
Example 8
Source File: ServletRequestImplStartAsyncInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 9
Source File: AsyncServletUpnpStream.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public AsyncServletUpnpStream(ProtocolFactory protocolFactory,
                              AsyncContext asyncContext,
                              HttpServletRequest request) {
    super(protocolFactory);
    this.asyncContext = asyncContext;
    this.request = request;
    asyncContext.addListener(this);
}
 
Example 10
Source File: ServletRuntime.java    From brave with Apache License 2.0 5 votes vote down vote up
/** If another async is created (ex via asyncContext.dispatch), this needs to be re-attached */
@Override public void onStartAsync(AsyncEvent e) {
  AsyncContext eventAsyncContext = e.getAsyncContext();
  if (eventAsyncContext != null) {
    eventAsyncContext.addListener(this, e.getSuppliedRequest(), e.getSuppliedResponse());
  }
}
 
Example 11
Source File: WrapperRequest.java    From jvm-sandbox-repeater with Apache License 2.0 5 votes vote down vote up
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
        throws IllegalStateException {
    listener.onStartAsync(this);
    AsyncContext asyncContext = super.startAsync(this, response);
    asyncContext.addListener(new WrapperAsyncListener(listener, this, (WrapperResponseCopier) response));
    return asyncContext;
}
 
Example 12
Source File: TopologySSEServlet.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    resp.setContentType("text/event-stream");
    resp.setCharacterEncoding("UTF-8");

    AsyncContext asyncContext = req.startAsync();
    PrintWriter writer = resp.getWriter();

    TopologyListener topologyListener = new SSETopologyListener(writer, req.isSecure());

    ScheduledFuture keepAlive = this.keepAliveExecutor.scheduleAtFixedRate(
            new KeepAliveRunnable(writer, topologyListener),
            10,
            15,
            TimeUnit.SECONDS);
    asyncContext.setTimeout(0);
    asyncContext.addListener(new TopologyAsyncListener(topology, topologyListener, keepAlive));


    this.topology.addListener(topologyListener);
    String json = topologyToJson(req.isSecure());
    writer.write("event: topologyChange\n");
    writer.write("data: " + json);
    writer.flush();

}
 
Example 13
Source File: WingtipsRequestSpanCompletionAsyncListener.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Override
public void onStartAsync(AsyncEvent event) {
    // Another async event was started (e.g. via asyncContext.dispatch(...), which means this listener was
    //      removed and won't be called on completion unless we re-register (as per the javadocs for this
    //      method from the interface).
    AsyncContext eventAsyncContext = event.getAsyncContext();
    if (eventAsyncContext != null) {
        eventAsyncContext.addListener(this, event.getSuppliedRequest(), event.getSuppliedResponse());
    }
}
 
Example 14
Source File: AsyncServlet2.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    AsyncContext ctx = req.startAsync();
    ctx.addListener(new SimpleAsyncListener());
    ctx.addListener(new AsyncEventListener());
    Thread thread = new Thread(new AsyncTask(ctx));
    thread.start();
}
 
Example 15
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    if ("y".equals(req.getParameter(DISPATCH_CHECK))) {
        if (req.getDispatcherType() != DispatcherType.ASYNC) {
            track("WrongDispatcherType-");
        }
    }
    track("DispatchingServletGet-");
    final int iter = Integer.parseInt(req.getParameter(ITER_PARAM)) - 1;
    final AsyncContext ctxt = req.startAsync();
    if (addTrackingListener) {
        TrackingListener listener =
            new TrackingListener(completeOnError, true, null);
        ctxt.addListener(listener);
    }
    Runnable run = new Runnable() {
        @Override
        public void run() {
            if (iter > 0) {
                ctxt.dispatch("/stage1?" + ITER_PARAM + "=" + iter +
                        "&" + DISPATCH_CHECK + "=y");
            } else {
                ctxt.dispatch("/stage2");
            }
        }
    };
    if ("y".equals(req.getParameter("useThread"))) {
        new Thread(run).start();
    } else {
        run.run();
    }
}
 
Example 16
Source File: AsyncServletUpnpStream.java    From TVRemoteIME with GNU General Public License v2.0 5 votes vote down vote up
public AsyncServletUpnpStream(ProtocolFactory protocolFactory,
                              AsyncContext asyncContext,
                              HttpServletRequest request) {
    super(protocolFactory);
    this.asyncContext = asyncContext;
    this.request = request;
    asyncContext.addListener(this);
}
 
Example 17
Source File: RequestStartAsyncInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example 18
Source File: WCCRequestImplStartAsyncInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@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 WebsphereAsyncListener(this.traceContext, recorder.recordNextAsyncContext(true));
        asyncContext.addListener(asyncListener);
        if (isDebug) {
            logger.debug("Add async listener {}", asyncListener);
        }
    }
    recorder.recordServiceType(WebsphereConstants.WEBSPHERE_METHOD);
    recorder.recordApi(methodDescriptor);
    recorder.recordException(throwable);
}
 
Example 19
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    TestAsyncContextImpl.track("DispatchingServletGet-");
    resp.flushBuffer();

    final boolean first = TrackingServlet.first;
    TrackingServlet.first = false;

    final AsyncContext ctxt = req.startAsync();
    TrackingListener listener = new TrackingListener(false, true, null);
    ctxt.addListener(listener);
    ctxt.setTimeout(3000);

    Runnable run = new Runnable() {
        @Override
        public void run() {
            if (first) {
                ctxt.dispatch("/stage1");
            } else {
                ctxt.dispatch("/stage2");
            }
        }
    };
    if ("y".equals(req.getParameter("useThread"))) {
        new Thread(run).start();
    } else {
        run.run();
    }
}
 
Example 20
Source File: OcHttpServletFilter.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
  // only interested in http requests
  if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
    HttpServletRequest httpReq = (HttpServletRequest) request;
    HttpServletResponse httpResp = (HttpServletResponse) response;

    HttpRequestContext context = handler.handleStart(httpReq, httpReq);
    OcHttpServletListener listener = new OcHttpServletListener(handler, context);
    httpReq.setAttribute(OcHttpServletUtil.OPENCENSUS_SERVLET_LISTENER, listener);

    int length = httpReq.getContentLength();
    if (length > 0) {
      handler.handleMessageReceived(context, length);
    }

    Scope scope = Tracing.getTracer().withSpan(handler.getSpanFromContext(context));
    try {
      chain.doFilter(httpReq, httpResp);
    } finally {
      scope.close();
    }

    if (httpReq.isAsyncStarted()) {
      AsyncContext async = httpReq.getAsyncContext();
      async.addListener(listener, httpReq, httpResp);
    } else {
      OcHttpServletUtil.recordMessageSentEvent(handler, context, httpResp);
      handler.handleEnd(context, httpReq, httpResp, null);
    }
  } else {
    // pass request through unchanged
    chain.doFilter(request, response);
  }
}