Example usage for javax.servlet AsyncContext complete

List of usage examples for javax.servlet AsyncContext complete

Introduction

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

Prototype

public void complete();

Source Link

Document

Completes the asynchronous operation that was started on the request that was used to initialze this AsyncContext, closing the response that was used to initialize this AsyncContext.

Usage

From source file:com.ibm.amc.feedback.FeedbackHandler.java

@Override
public void actionStatusUpdated(final ActionStatus status) {
    if (logger.isEntryEnabled())
        logger.entry("actionStatusUpdated", status);

    if (!status.isSynchronous()) {
        final String user = status.getUserId();

        final Set<AsyncContext> contexts = feedbackListeners.remove(user);
        if (contexts == null) {
            // No one waiting - queue status
            if (logger.isDebugEnabled())
                logger.debug("actionStatusUpdated", "Queuing status update for action " + status.getActionId());
            queueActionStatus(status);//from   w w w.ja va 2  s .c  o  m
        } else {
            // Request waiting - send response immediately
            if (logger.isDebugEnabled())
                logger.debug("actionStatusUpdated", "Sending status update for action " + status.getActionId());
            final Queue<ActionStatusResponse> queue = new LinkedList<ActionStatusResponse>();
            queue.offer(new ActionStatusResponse(status));
            for (AsyncContext ctx : contexts) {
                writeResponse(ctx.getResponse(), queue);
                ctx.complete();
            }
        }
    }

    if (logger.isEntryEnabled())
        logger.exit("actionStatusUpdated");
}

From source file:eu.rethink.lhcb.broker.servlet.WellKnownServlet.java

private void completeAsyncContext(AsyncContext aContext, String message) {
    try {/*from  w w  w  . j  a  v a2s .co m*/
        aContext.getResponse().getWriter().write(message);
        aContext.getResponse().getWriter().flush();
    } catch (IOException e1) {
        LOG.error("Unable to send message '" + message + "'to requester", e1);
    }
    aContext.complete();
}

From source file:com.kurento.kmf.content.internal.ControlProtocolManager.java

/**
 * Sender method for error messages in JSON throw a request.
 * /*ww  w  .ja  va  2  s  . co  m*/
 * @param asyncCtx
 *            Asynchronous context
 * @param message
 *            JSON error message (as a Java class)
 * @throws IOException
 *             Exception while parsing operating with asynchronous context
 */
public void sendJsonError(AsyncContext asyncCtx, JsonRpcResponse message) {
    try {
        internalSendJsonAnswer(asyncCtx, message);
    } catch (Throwable e) {
        log.info("Cannot send answer message to destination", e);
    } finally {
        if (asyncCtx != null) {
            asyncCtx.complete();
        }
    }
}

From source file:jetbrains.buildServer.clouds.azure.arm.web.SettingsController.java

private void doPost(@NotNull final HttpServletRequest request, @NotNull final HttpServletResponse response) {
    final Element xmlResponse = XmlResponseUtil.newXmlResponse();
    final ActionErrors errors = new ActionErrors();
    final String[] resources = request.getParameterValues("resource");
    final List<Promise<Content, Throwable, Void>> promises = new ArrayList<>(resources.length);

    for (final String resource : resources) {
        final ResourceHandler handler = HANDLERS.get(resource);
        if (handler == null)
            continue;

        try {/*from www  .  j a  va 2  s . c o  m*/
            final Promise<Content, Throwable, Void> promise = handler.handle(request)
                    .fail(new FailCallback<Throwable>() {
                        @Override
                        public void onFail(Throwable result) {
                            LOG.debug(result);
                            errors.addError(resource, result.getMessage());
                        }
                    });
            promises.add(promise);
        } catch (Throwable t) {
            LOG.debug(t);
            errors.addError(resource, t.getMessage());
        }
    }

    if (promises.size() == 0) {
        if (errors.hasErrors()) {
            errors.serialize(xmlResponse);
        }

        writeResponse(xmlResponse, response);
        return;
    }

    final AsyncContext context = request.startAsync(request, response);
    myManager.when(promises.toArray(new Promise[] {})).always(new AlwaysCallback<MultipleResults, OneReject>() {
        @Override
        public void onAlways(Promise.State state, MultipleResults resolved, OneReject rejected) {
            if (errors.hasErrors()) {
                errors.serialize(xmlResponse);
            } else {
                for (OneResult oneResult : resolved) {
                    xmlResponse.addContent((Content) oneResult.getResult());
                }
            }

            writeResponse(xmlResponse, context.getResponse());
            context.complete();
        }
    });
}

From source file:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java

void sendResponseOrSkip(final AtomicInteger synchronizer, final AsyncContext asyncContext,
        final VerificationItems verificationItems) {
    if (synchronizer.getAndIncrement() == 1) {
        try {//from w  ww.ja  v  a2s  .  c  om
            final Writer responseWriter = asyncContext.getResponse().getWriter();
            responseWriter.write(GSON.toJson(verificationItems));
            asyncContext.complete();
        } catch (Exception e) {
            log.error("Failed to send back the response", e);
        }
    }
}

From source file:com.kurento.kmf.content.internal.ControlProtocolManager.java

/**
 * Internal implementation for sending JSON (called from sendJsonAnswer and
 * sendJsonError methods)./*w  ww  . j av  a 2  s.co  m*/
 * 
 * @param asyncCtx
 *            Asynchronous context
 * @param message
 *            JSON message (as a Java class)
 * @throws IOException
 *             Exception while parsing operating with asynchronous context
 */
private void internalSendJsonAnswer(AsyncContext asyncCtx, JsonRpcResponse message) {
    try {
        if (asyncCtx == null) {
            throw new KurentoMediaFrameworkException("Null asyncCtx found", 20017);
        }

        synchronized (asyncCtx) {
            if (!asyncCtx.getRequest().isAsyncStarted()) {
                throw new KurentoMediaFrameworkException("Cannot send message in completed asyncCtx", 1); // TODO
            }

            HttpServletResponse response = (HttpServletResponse) asyncCtx.getResponse();
            response.setContentType("application/json");
            OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), UTF8);
            osw.write(gson.toJson(message));
            osw.flush();
            log.info("Sent JsonRpc answer ...\n" + message);
            asyncCtx.complete();
        }
    } catch (IOException ioe) {
        throw new KurentoMediaFrameworkException(ioe.getMessage(), ioe, 20018);
    }
}

From source file:eu.rethink.lhcb.broker.servlet.WellKnownServlet.java

private void handleRequest(HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {

    // add header for cross domain stuff
    resp.addHeader("Access-Control-Allow-Origin", "*");
    String host = req.getHeader("X-Forwarded-Host");
    if (host == null)
        host = req.getHeader("Host");

    // setting external host here helps BrokerWebSocketListener to return info about HTTP interface
    // Broker might not know how it is accessible. This is a workaround for it
    LHCBBroker.externalHost = host;//  www. ja  v a 2s.  c  o  m
    final AsyncContext asyncContext = req.startAsync();
    asyncContext.start(() -> {
        ServletRequest aReq = asyncContext.getRequest();
        String payload = null;
        try {
            payload = IOUtils.toString(aReq.getReader());
        } catch (IOException e) {
            e.printStackTrace();
        }

        String finalPayload = payload;

        Map<String, String[]> params = aReq.getParameterMap();
        LOG.debug("payload: {}\r\nparams: {}", payload, params);

        RequestCallback cb = new RequestCallback() {

            @Override
            public void response(Message msg) {
                resp.setStatus(HttpServletResponse.SC_OK);
                try {
                    asyncContext.getResponse().getWriter().write(msg.toString());
                    asyncContext.getResponse().getWriter().flush();
                    asyncContext.complete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(Exception e) {
                String error = "Request failed.\r\npayload: " + finalPayload + "\r\nparams: " + params;
                LOG.error(error + "\r\nreason: " + e.getLocalizedMessage(),
                        e instanceof InvalidMessageException ? null : e);
                if (e instanceof InvalidMessageException) {
                    resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                } else {
                    resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

                }
                completeAsyncContext(asyncContext, error + "\r\nreason: " + e.getLocalizedMessage());
            }
        };

        try {
            Message msg = null;

            if (payload.length() > 0) {
                msg = Message.fromString(payload);
            } else {
                msg = Message.fromParams(params);
            }

            requestHandler.handleRequest(msg, cb);
        } catch (InvalidMessageException e) {
            cb.error(e);
        }
    });
}

From source file:org.synchronoss.cloud.nio.multipart.example.web.MultipartController.java

void sendErrorOrSkip(final AtomicInteger synchronizer, final AsyncContext asyncContext, final String message) {
    if (synchronizer.getAndIncrement() <= 1) {
        try {//from w  w  w .  j av  a2 s  . c  om
            final ServletResponse servletResponse = asyncContext.getResponse();
            if (servletResponse instanceof HttpServletResponse) {
                ((HttpServletResponse) servletResponse).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        message);
            } else {
                asyncContext.getResponse().getWriter().write(message);
            }
            asyncContext.complete();
        } catch (Exception e) {
            log.error("Failed to send back the error response", e);
        }
    }
}

From source file:com.kolich.havalo.controllers.api.ObjectApi.java

@RequestMapping(methods = HEAD, value = "/api/object/{key}", matcher = AntPathMatcher.class, filters = HavaloAuthenticationFilter.class)
public final void head(final ObjectKey key, final KeyPair userKp, final HttpServletResponse response,
        final AsyncContext context) throws Exception {
    final Repository repo = getRepository(userKp.getKey());
    new ReentrantReadWriteEntityLock<Void>(repo) {
        @Override//from   ww  w.  j  ava2 s .c om
        public Void transaction() throws Exception {
            final HashedFileObject hfo = getHashedFileObject(repo,
                    // The URL-decoded key of the object to delete.
                    key,
                    // Fail if not found.
                    true);
            new ReentrantReadWriteEntityLock<HashedFileObject>(hfo) {
                @Override
                public HashedFileObject transaction() throws Exception {
                    final DiskObject object = getCanonicalObject(repo, hfo);
                    streamHeaders(object, hfo, response);
                    return hfo;
                }
            }.read(); // Shared read lock on file object
            return null;
        }

        @Override
        public void success(final Void v) throws Exception {
            context.complete();
        }
    }.read(); // Shared read lock on repo
}