Example usage for javax.servlet AsyncContext getResponse

List of usage examples for javax.servlet AsyncContext getResponse

Introduction

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

Prototype

public ServletResponse getResponse();

Source Link

Document

Gets the response that was used to initialize this AsyncContext by calling ServletRequest#startAsync() or ServletRequest#startAsync(ServletRequest,ServletResponse) .

Usage

From source file:org.silverpeas.core.notification.sse.SilverpeasAsyncContext.java

/**
 * Wraps the given instance. Nothing is wrapped if the given instance is a wrapped one.
 * @param silverLogger the sse silverpeas logger.
 * @param asyncContext the instance to wrap.
 * @param userSessionId the identifier or the user session.
 * @param user the identifier of th user linked to the async request.
 * @return the wrapped given instance.//from   ww  w .j  a  v  a2s .  c o  m
 */
public static SilverpeasAsyncContext wrap(final SilverLogger silverLogger, AsyncContext asyncContext,
        final String userSessionId, User user) {
    if (asyncContext instanceof SilverpeasAsyncContext) {
        return (SilverpeasAsyncContext) asyncContext;
    }

    final SilverpeasAsyncContext context = new SilverpeasAsyncContext(asyncContext, userSessionId, user);
    final ServletRequest request = asyncContext.getRequest();
    final ServletResponse response = asyncContext.getResponse();
    context.addListener(new SilverpeasAsyncListener(silverLogger, context), request, response);
    return context;
}

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

/**
 * Write response directly as Event-Stream for Server Sent Events.
 *
 * @param asyncContext - Asynchronous Context.
 * @param event - Name of event to be written on response.
 * @param data - Content of event ot be written on response.
 * @param retry - Time in (milliseconds) for client retry opening connection.
 *              after asynchronous context is closed.
 * @throws IOException/*from w w w . j  av a  2 s .c o  m*/
 */
public static void writeResponseAsEventStream(AsyncContext asyncContext, String event, Object data, Long retry)
        throws IOException {
    if (asyncContext != null && event != null && data != null) {
        HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
        response.setContentType("text/event-stream");
        PrintWriter printWriter = response.getWriter();

        if (retry != null) {
            printWriter.write("retry:" + retry + "\n");
        }
        printWriter.write("event:" + event + "\n");
        printWriter.write("data:" + data + "\n\n");
        printWriter.flush();
    }
}

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

private void completeAsyncContext(AsyncContext aContext, String message) {
    try {//from ww  w.j  a  va 2  s.  com
        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.comcast.cqs.controller.CQSReceiveMessageBodyAction.java

@Override
public boolean doAction(User user, AsyncContext asyncContext) throws Exception {

    HttpServletRequest request = (HttpServletRequest) asyncContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();

    CQSQueue queue = CQSCache.getCachedQueue(user, request);

    HashMap<String, String> msgParam = new HashMap<String, String>();
    List<CQSMessage> messageList = PersistenceFactory.getCQSMessagePersistence().receiveMessage(queue,
            msgParam);//from ww  w.  jav a 2 s  .  c o m

    String out = "";
    response.setContentType("text/html");

    if (messageList.size() > 0) {

        out += messageList.get(0).getBody();

        try {
            new JSONObject(messageList.get(0).getBody());
            response.setContentType("application/json");
        } catch (JSONException ex) {
            // do nothing
        }
    }

    writeResponse(out, response);

    return true;
}

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 www  .  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:com.comcast.cns.controller.CNSSetSubscriptionAttributesAction.java

/**
 * The method simply gets the information from the user and request to set the subscription attributes based 
 * on what the user passed as the "AttributeName", and set that attribute to "AttributeValue"
 * //w w  w. j a  v a 2 s.  c  o m
 * @param user the user for whom we are setting the subscription attributes
 * @param asyncContext
 */
@Override
public boolean doAction(User user, AsyncContext asyncContext) throws Exception {

    HttpServletRequest request = (HttpServletRequest) asyncContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();

    String userId = user.getUserId();
    String attributeName = request.getParameter("AttributeName");
    String attributeValue = request.getParameter("AttributeValue");
    String subscriptionArn = request.getParameter("SubscriptionArn");

    logger.debug("event=cns_set_subscription_attributes attribute_name=" + attributeName + " attribute_value="
            + attributeValue + " subscription_arn=" + subscriptionArn + " user_id=" + userId);

    if ((userId == null) || (subscriptionArn == null) || (attributeName == null) || (attributeValue == null)) {
        logger.error("event=cns_set_subscription_attributes error_code=InvalidParameters attribute_name="
                + attributeName + " attribute_value=" + attributeValue + " subscription_arn=" + subscriptionArn
                + " user_id=" + userId);
        throw new CMBException(CNSErrorCodes.CNS_InvalidParameter, "missing parameters");
    }

    CNSSubscriptionAttributes subscriptionAttributes = new CNSSubscriptionAttributes();

    if (attributeName.equals("DeliveryPolicy")) {
        JSONObject json = new JSONObject(attributeValue);
        CNSSubscriptionDeliveryPolicy deliveryPolicy = new CNSSubscriptionDeliveryPolicy(json);
        subscriptionAttributes.setDeliveryPolicy(deliveryPolicy);
    } else if (attributeName.equals("RawMessageDelivery")) {
        Boolean rawMessageDelivery = Boolean.parseBoolean(attributeValue);
        PersistenceFactory.getSubscriptionPersistence().setRawMessageDelivery(subscriptionArn,
                rawMessageDelivery);
    } else {
        logger.error("event=cns_set_subscription_attributes error_code=InvalidParameters attribute_name="
                + attributeName + " attribute_value=" + attributeValue + " subscription_arn=" + subscriptionArn
                + " user_id=" + userId);
        throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,
                "AttributeName: " + attributeName + " is not a valid value");
    }

    PersistenceFactory.getCNSAttributePersistence().setSubscriptionAttributes(subscriptionAttributes,
            subscriptionArn);

    String out = CNSAttributePopulator.getSetSubscriptionAttributesResponse();
    logger.debug("event=cns_set_subscription_attributes attribute_name=" + attributeName + " attribute_value="
            + attributeValue + " subscription_arn=" + subscriptionArn + " user_id=" + userId);
    writeResponse(out, response);
    return true;
}

From source file:com.comcast.cqs.controller.CQSPeekMessageAction.java

@Override
public boolean doAction(User user, AsyncContext asyncContext) throws Exception {

    HttpServletRequest request = (HttpServletRequest) asyncContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();

    CQSQueue queue = CQSCache.getCachedQueue(user, request);
    List<CQSMessage> messageList = getMessages(request, true, queue);

    Map<String, String[]> requestParams = request.getParameterMap();
    List<String> filterAttributes = new ArrayList<String>();
    List<String> filterMessageAttributes = new ArrayList<String>();

    for (String k : requestParams.keySet()) {
        if (k.contains(CQSConstants.MESSAGE_ATTRIBUTE_NAME)) {
            filterMessageAttributes.add(requestParams.get(k)[0]);
        } else if (k.contains(CQSConstants.ATTRIBUTE_NAME)) {
            filterAttributes.add(requestParams.get(k)[0]);
        }/*  www  . j av  a 2 s  .com*/
    }

    String out = CQSMessagePopulator.getReceiveMessageResponseAfterSerializing(messageList, filterAttributes,
            filterMessageAttributes);
    writeResponse(out, response);

    return messageList == null ? false : true;
}

From source file:com.comcast.cns.controller.CNSSetTopicAttributesAction.java

@Override
public boolean doAction(User user, AsyncContext asyncContext) throws Exception {

    HttpServletRequest request = (HttpServletRequest) asyncContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();

    String userId = user.getUserId();
    String attributeName = request.getParameter("AttributeName");
    String attributeValue = request.getParameter("AttributeValue");
    String topicArn = request.getParameter("TopicArn");

    if ((userId == null) || (topicArn == null) || (attributeName == null) || (attributeValue == null)) {
        logger.error("event=cns_set_topic_attributes error_code=InvalidParameters attribute_name="
                + attributeName + " attribute_value=" + attributeValue + " topic_arn=" + topicArn + " user_id="
                + userId);/*from  w  ww  .  j ava  2  s. co  m*/
        throw new CMBException(CNSErrorCodes.CNS_InvalidParameter, "missing parameters");
    }

    CNSTopicAttributes topicAttributes = new CNSTopicAttributes();

    if (attributeName.equals("DeliveryPolicy")) {

        JSONObject json = new JSONObject(attributeValue);
        CNSTopicDeliveryPolicy deliveryPolicy = new CNSTopicDeliveryPolicy(json);
        topicAttributes.setDeliveryPolicy(deliveryPolicy);
        logger.debug("event=cns_set_topic_delivery_policy topic_arn=" + topicArn + " value="
                + topicAttributes.getEffectiveDeliveryPolicy());

    } else if (attributeName.equals("Policy")) {

        // validate policy before updating

        try {
            new CMBPolicy(attributeValue);
        } catch (Exception ex) {
            logger.warn("event=invalid_policy topic_arn=" + topicArn + " policy=" + attributeValue, ex);
            throw ex;
        }

        topicAttributes.setPolicy(attributeValue);
        logger.debug(
                "event=cns_set_topic_policy topic_arn=" + topicArn + "  value=" + topicAttributes.getPolicy());

    } else if (attributeName.equals("DisplayName")) {

        if (validateDisplayName(attributeValue)) {
            topicAttributes.setDisplayName(attributeValue);
            logger.debug(
                    "event=cns_set_topic_display_name topic_arn=" + topicArn + "  value=" + attributeValue);
        } else {
            throw new CMBException(CNSErrorCodes.CNS_InvalidParameter, "Bad Display Name");
        }

    } else {
        logger.error("event=cns_set_topic_attributes error_code=InvalidParameters attribute_name="
                + attributeName + " attribute_value=" + attributeValue + " topic_arn=" + topicArn + " user_id="
                + userId);
        throw new CMBException(CNSErrorCodes.CNS_InvalidParameter,
                "AttributeName: " + attributeName + " is not a valid value");
    }

    PersistenceFactory.getCNSAttributePersistence().setTopicAttributes(topicAttributes, topicArn);
    String out = CNSAttributePopulator.getSetTopicAttributesResponse();
    logger.debug("event=cns_set_topic_attributes attribute_name=" + attributeName + " attribute_value="
            + attributeValue + " topic_arn=" + topicArn + " user_id=" + userId);
    writeResponse(out, response);
    return true;
}

From source file:org.forumj.web.requesthandler.prehandler.LoginPreHandler.java

@Override
public boolean handle(AsyncContext context) throws FJWebException {
    boolean ok = true;
    HttpServletRequest request = (HttpServletRequest) context.getRequest();
    HttpServletResponse response = (HttpServletResponse) context.getResponse();
    try {/*w  w  w  . ja va  2 s .  co  m*/
        IUser user = (IUser) request.getSession(true).getAttribute("user");
        UserService userService = FJServiceHolder.getUserService();
        if (user == null || !user.isLogined()) {
            QuotedPrintableCodec codec = new QuotedPrintableCodec();
            Cookie[] cookies = request.getCookies();
            Cookie iduCookie = getCookie(cookies, "idu");
            Cookie pass2Cookie = getCookie(cookies, "pass2");
            if (pass2Cookie != null) {
                String pass2 = pass2Cookie.getValue();
                if (pass2 != null) {
                    pass2 = codec.decode(pass2);
                    user = userService.read(Long.valueOf(iduCookie.getValue()), pass2, false);
                    if (user == null) {
                        ok = false;
                    } else {
                        if (!user.getIsActive()) {
                            user = null;
                        } else {
                            request.getSession().setAttribute("user", user);
                        }
                    }
                } else {
                    ok = false;
                }
            }
        }
        if (user == null) {
            String iduParameter = request.getParameter("IDU");
            String pass1Parameter = request.getParameter("PS1");
            String pass2Parameter = request.getParameter("PS2");
            if (iduParameter != null && (pass1Parameter != null || pass2Parameter != null)) {
                boolean firstPassword = pass1Parameter != null;
                user = userService.read(Long.valueOf(iduParameter),
                        firstPassword ? pass1Parameter : pass2Parameter, firstPassword);
                if (user == null) {
                    ok = false;
                } else {
                    if (!user.getIsActive()) {
                        user = null;
                    } else {
                        request.getSession().setAttribute("user", user);
                    }
                }
            }
        }
        if (user == null) {
            user = userService.readUser(0l);
            request.getSession().setAttribute("user", user);
        }
        if (ok) {
            if (user != null && user.isLogined()) {
                String ip = request.getRemoteAddr();
                if (ip != null && CheckIp.isSpammerIp(ip)) {
                    setcookie(response, "idu", "", 0, request.getContextPath(), request.getServerName());
                    setcookie(response, "pass2", "", 0, request.getContextPath(), request.getServerName());
                    user = userService.readUser(0l);
                    request.getSession().setAttribute("user", user);
                }
            }
            return true;
        } else {
            return false;
        }
    } catch (Throwable e) {
        throw new FJWebException(e);
    }
}

From source file:org.siphon.d2js.DispatchServlet.java

@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
    AsyncContext asyncContext = request.startAsync(request, response);
    D2jsRunner d2jsRunner = this.getD2jsRunner();
    try {/*from ww w . j  a  va2  s. c  o  m*/
        d2jsRunner.run((HttpServletRequest) asyncContext.getRequest(),
                (HttpServletResponse) asyncContext.getResponse(), "delete");
    } finally {
        asyncContext.complete();
    }
}