Example usage for javax.servlet AsyncContext addListener

List of usage examples for javax.servlet AsyncContext addListener

Introduction

In this page you can find the example usage for javax.servlet AsyncContext addListener.

Prototype

public void addListener(AsyncListener listener);

Source Link

Document

Registers the given AsyncListener with the most recent asynchronous cycle that was started by a call to one of the ServletRequest#startAsync methods.

Usage

From source file:com.sishuok.chapter3.web.controller.StreamingController.java

@RequestMapping("/async3")
public void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setHeader("Connection", "Keep-Alive");
    resp.addHeader("Cache-Control", "private");
    resp.addHeader("Pragma", "no-cache");
    resp.setContentType("text/html;charset=utf-8");
    resp.flushBuffer();/*from  www.j  a v  a2 s. com*/

    //1??
    final AsyncContext asyncContext = req.startAsync();

    asyncContext.addListener(new AsyncListener() {
        @Override
        public void onComplete(final AsyncEvent event) throws IOException {
            queue.remove(event.getAsyncContext());
        }

        @Override
        public void onTimeout(final AsyncEvent event) throws IOException {
            event.getAsyncContext().complete();
            queue.remove(event.getAsyncContext());
        }

        @Override
        public void onError(final AsyncEvent event) throws IOException {
            queue.remove(event.getAsyncContext());
        }

        @Override
        public void onStartAsync(final AsyncEvent event) throws IOException {
        }
    });

    //????
    queue.add(asyncContext);

}

From source file:io.atrato.pubsubserver.PubsubRestProvider.java

@GET
@Path("topics/{topic}")
@Produces(MediaType.APPLICATION_JSON)/*from w  w w  .j a  va2  s. c  om*/
public PubsubBroker.TimedTopicData getTopicData(@PathParam("topic") String topic,
        @QueryParam("laterThan") Long timestamp, @QueryParam("poll") Boolean poll,
        @Context HttpServletRequest request) {
    if (timestamp == null) {
        timestamp = -1L;
    }
    //LOG.debug("topic: {} poll: {}", topic, poll);
    PubsubBroker.TimedTopicData data = PubsubServer.getBroker().getLatestTopicData(topic, timestamp);
    if (data == null) {
        if (BooleanUtils.isTrue(poll)) {
            AsyncContext asyncContext = request.startAsync();
            PubsubServer.getBroker().oneTimeSubscribe(asyncContext, topic);
            asyncContext.addListener(new AsyncListener() {
                @Override
                public void onComplete(AsyncEvent asyncEvent) throws IOException {
                    PubsubServer.getBroker().invalidateOneTimeSubscriber(asyncEvent.getAsyncContext());
                }

                @Override
                public void onTimeout(AsyncEvent asyncEvent) throws IOException {
                    PubsubServer.getBroker().invalidateOneTimeSubscriber(asyncEvent.getAsyncContext());
                }

                @Override
                public void onError(AsyncEvent asyncEvent) throws IOException {
                    PubsubServer.getBroker().invalidateOneTimeSubscriber(asyncEvent.getAsyncContext());
                }

                @Override
                public void onStartAsync(AsyncEvent asyncEvent) throws IOException {
                }
            });
            return null;
        } else {
            throw new NotFoundException();
        }
    }
    LOG.debug("topic: {} poll: {} data: {}", topic, poll, (data != null ? data.getData() : data));
    return data;
}

From source file:com.cisco.oss.foundation.http.server.MonitoringFilter.java

@Override
public void doFilterImpl(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    regiterMonitoring();/*  w  ww  .j av a  2 s . co m*/

    final long startTime = System.currentTimeMillis();
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    String tempMethodName = httpServletRequest.getMethod();
    if (uniqueUriMonitoringEnabled) {
        tempMethodName += ":" + httpServletRequest.getRequestURI();
    }

    boolean reportToMonitoring = true;

    try {
        LOGGER.trace("Monitoring filter: Request processing started at: {}", startTime);

        //         methodName = httpServletRequest.getMethod() + ":" + httpServletRequest.getRequestURI().toString();
        tempMethodName = updateMethodName(httpServletRequest, tempMethodName);

        LOGGER.trace("transaction method name is: {}", tempMethodName);

        CommunicationInfo.getCommunicationInfo().transactionStarted(serviceDetails, tempMethodName,
                threadPool != null ? threadPool.getThreads() : -1);

    } catch (Exception e) {
        LOGGER.error("can't report monitoring data as it has failed on:" + e);
        reportToMonitoring = false;
    }
    final String methodName = tempMethodName;

    try {
        chain.doFilter(httpServletRequest, httpServletResponse);

        if (request.isAsyncStarted()) {

            AsyncContext async = request.getAsyncContext();
            async.addListener(new AsyncListener() {
                @Override
                public void onComplete(AsyncEvent event) throws IOException {
                    final long endTime = System.currentTimeMillis();
                    final int processingTime = (int) (endTime - startTime);
                    LOGGER.debug("Processing time: {} milliseconds", processingTime);
                }

                @Override
                public void onTimeout(AsyncEvent event) throws IOException {

                }

                @Override
                public void onError(AsyncEvent event) throws IOException {
                    Throwable throwable = event.getThrowable();
                    if (throwable != null) {
                        CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName,
                                true, throwable.toString());
                    }
                }

                @Override
                public void onStartAsync(AsyncEvent event) throws IOException {

                }
            });

        } else {
            final long endTime = System.currentTimeMillis();
            final int processingTime = (int) (endTime - startTime);
            LOGGER.debug("Processing time: {} milliseconds", processingTime);
        }

    } catch (Exception e) {
        CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, true,
                e.toString());
        throw e;
    }

    if (reportToMonitoring) {
        try {

            int status = httpServletResponse.getStatus();

            if (status >= 400) {
                CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, true,
                        httpServletResponse.getStatus() + "");

            } else {

                CommunicationInfo.getCommunicationInfo().transactionFinished(serviceDetails, methodName, false,
                        "");
            }
        } catch (Exception e) {
            LOGGER.error("can't report monitoring data as it has failed on:" + e);
        }
    }

}

From source file:com.kurento.kmf.content.internal.base.AbstractContentHandlerServlet.java

@Override
protected final void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    if (useControlProtocol) {
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_NOT_IMPLEMENTED,
                "Only POST request are supported for this service. You can enable GET requests "
                        + " by setting useControlProtocol to false on the appropriate handler annotation");
        return;//from   w  w w  .j  a v a  2 s  .  co m
    }

    getLogger().info("GET request received: " + req.getRequestURI());

    if (!req.isAsyncSupported()) {
        // Async context could not be created. It is not necessary to
        // complete it. Just send error message to
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "AsyncContext could not be started. The application should add \"asyncSupported = true\" in all "
                        + this.getClass().getName() + " instances and in all filters in the associated chain");
        return;
    }
    if (handler == null) {
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                handler.getClass().getSimpleName() + " is null. This error means that you "
                        + "need to provide a valid implementation of interface "
                        + handler.getClass().getSimpleName());
        return;
    }

    String contentId = req.getPathInfo();
    if (contentId != null) {
        contentId = contentId.substring(1);
    }

    AsyncContext asyncCtx = req.startAsync();

    // Add listener for managing error conditions
    asyncCtx.addListener(new ContentAsyncListener());

    doRequest4SimpleHttpProtocol(asyncCtx, contentId, resp);

}

From source file:com.kurento.kmf.content.internal.base.AbstractContentHandlerServlet.java

@Override
protected final void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    getLogger().info("POST request received: " + req.getRequestURI());

    if (!req.isAsyncSupported()) {
        // Async context could not be created. It is not necessary to
        // complete it. Just send error message to
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "AsyncContext could not be started. The application should add \"asyncSupported = true\" in all "
                        + this.getClass().getName() + " instances and in all filters in the associated chain");
        return;// w w  w  .  j  a v a2  s .  co  m
    }
    if (handler == null) {
        ServletUtils.sendHttpError(req, resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                handler.getClass().getSimpleName() + " is null. This error means that you "
                        + "need to provide a valid implementation of interface "
                        + handler.getClass().getSimpleName());
        return;
    }

    String contentId = req.getPathInfo();
    if (contentId != null) {
        contentId = contentId.substring(1);
    }

    AsyncContext asyncCtx = req.startAsync();

    // Add listener for managing error conditions
    asyncCtx.addListener(new ContentAsyncListener());

    if (useControlProtocol) {
        doRequest4JsonControlProtocol(asyncCtx, contentId, resp);
    } else {
        // TODO: we should check that the content type correspond to
        // the ones we support. We should avoid receiving application/json
        // here and send a coherent error message in that case because this
        // case corresponds to using incorrectly annotations on handlers
        doRequest4SimpleHttpProtocol(asyncCtx, contentId, resp);
    }
}

From source file:com.jsmartframework.web.manager.ServletControl.java

private boolean doAsync(String path, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    try {/*from   www. j  a  va2s  . c o m*/
        // Only proceed if the AsyncContext was not started to avoid looping whe dispatch is called
        if (!request.isAsyncStarted()) {
            WebAsyncListener bean = (WebAsyncListener) HANDLER.instantiateAsyncBean(path);

            if (bean != null) {
                AsyncContext asyncContext = request.startAsync();
                bean.asyncContextCreated(asyncContext);
                asyncContext.addListener(new WebServletAsyncListener(path, bean));
                return true;
            }
        }
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE,
                "AsyncBean on path [" + path + "] could not be instantiated: " + ex.getMessage());
        throw new ServletException(ex);
    }
    return false;
}

From source file:org.apache.vysper.xmpp.extension.xep0124.BoshBackedSessionContext.java

protected void addContinuationExpirationListener(final AsyncContext context) {
    // listen the continuation to be notified when the request expires
    context.addListener(new AsyncListener() {

        public void onTimeout(AsyncEvent event) throws IOException {
            requestExpired(context);/*from ww  w  .  ja  va 2s .c o  m*/
        }

        public void onStartAsync(AsyncEvent event) throws IOException {
            // ignore
        }

        public void onError(AsyncEvent event) throws IOException {
            handleAsyncEventError(event);
        }

        public void onComplete(AsyncEvent event) throws IOException {
            // ignore
        }
    });
}

From source file:org.apache.vysper.xmpp.extension.xep0124.BoshBackedSessionContextTest.java

@Test
public void testWrite0() {
    HttpServletRequest httpServletRequest = mocksControl.createMock(HttpServletRequest.class);
    AsyncContext asyncContext = mocksControl.createMock(AsyncContext.class);
    expect(httpServletRequest.startAsync()).andReturn(asyncContext);
    expectLastCall().atLeastOnce();/*from w w w.ja v a2 s.co m*/
    expect(httpServletRequest.getAsyncContext()).andReturn(asyncContext);
    expectLastCall().atLeastOnce();
    asyncContext.setTimeout(anyLong());
    asyncContext.dispatch();
    expectLastCall().atLeastOnce();
    httpServletRequest.setAttribute(eq(BOSH_REQUEST_ATTRIBUTE), EasyMock.<BoshRequest>notNull());
    asyncContext.addListener(EasyMock.<AsyncListener>anyObject());
    Capture<BoshResponse> captured = new Capture<BoshResponse>();
    httpServletRequest.setAttribute(eq(BOSH_RESPONSE_ATTRIBUTE), EasyMock.<BoshResponse>capture(captured));
    mocksControl.replay();

    BoshBackedSessionContext boshBackedSessionContext = new BoshBackedSessionContext(serverRuntimeContext, null,
            inactivityChecker);
    Stanza body = BoshStanzaUtils.EMPTY_BOSH_RESPONSE;
    boshBackedSessionContext.insertRequest(new BoshRequest(httpServletRequest, body, 1L));
    boshBackedSessionContext.writeBoshResponse(body);
    mocksControl.verify();

    BoshResponse boshResponse = captured.getValue();
    assertEquals(BoshServlet.XML_CONTENT_TYPE, boshResponse.getContentType());
    assertEquals(new Renderer(body).getComplete(), new String(boshResponse.getContent()));
}

From source file:org.apache.vysper.xmpp.extension.xep0124.BoshBackedSessionContextTest.java

@Test
public void testRequestExpired() throws IOException {
    Stanza emtpyStanza = BoshStanzaUtils.EMPTY_BOSH_RESPONSE;

    // addRequest
    HttpServletRequest httpServletRequest = mocksControl.createMock(HttpServletRequest.class);
    AsyncContext asyncContext = mocksControl.createMock(AsyncContext.class);
    expect(httpServletRequest.startAsync()).andReturn(asyncContext).atLeastOnce();
    expect(httpServletRequest.getAsyncContext()).andReturn(asyncContext).atLeastOnce();
    asyncContext.setTimeout(anyLong());//ww w.j  av a 2  s  . com
    httpServletRequest.setAttribute(eq(BOSH_REQUEST_ATTRIBUTE), EasyMock.<BoshRequest>notNull());

    expect(asyncContext.getRequest()).andReturn(httpServletRequest).atLeastOnce();
    asyncContext.dispatch();
    expectLastCall().atLeastOnce();

    Capture<AsyncListener> listenerCaptured = new Capture<AsyncListener>();
    asyncContext.addListener(EasyMock.<AsyncListener>capture(listenerCaptured));

    AsyncEvent asyncEvent = mocksControl.createMock(AsyncEvent.class);

    BoshRequest br = new BoshRequest(httpServletRequest, emtpyStanza, 1L);

    // requestExpired
    expect(httpServletRequest.getAttribute(BOSH_REQUEST_ATTRIBUTE)).andReturn(br);
    Capture<BoshResponse> responseCaptured = new Capture<BoshResponse>();
    httpServletRequest.setAttribute(eq(BOSH_RESPONSE_ATTRIBUTE),
            EasyMock.<BoshResponse>capture(responseCaptured));

    // write0
    mocksControl.replay();
    BoshBackedSessionContext boshBackedSessionContext = new BoshBackedSessionContext(serverRuntimeContext, null,
            inactivityChecker);

    boshBackedSessionContext.insertRequest(br);
    listenerCaptured.getValue().onTimeout(asyncEvent);
    mocksControl.verify();

    assertEquals(new Renderer(emtpyStanza).getComplete(), new String(responseCaptured.getValue().getContent()));
    assertEquals(BoshServlet.XML_CONTENT_TYPE, responseCaptured.getValue().getContentType());
}