Example usage for javax.servlet AsyncContext getRequest

List of usage examples for javax.servlet AsyncContext getRequest

Introduction

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

Prototype

public ServletRequest getRequest();

Source Link

Document

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

Usage

From source file:com.kolich.blog.mappers.AbstractETagAwareResponseMapper.java

private static String getIfNoneMatchFromRequest(final AsyncContext context) {
    final HttpServletRequest request = (HttpServletRequest) context.getRequest();
    return request.getHeader(IF_NONE_MATCH);
}

From source file:org.springframework.http.server.reactive.ServletHttpHandlerAdapter.java

/**
 * We cannot combine ERROR_LISTENER and HandlerResultSubscriber due to:
 * https://issues.jboss.org/browse/WFLY-8515
 *//*from   w  w  w .  ja  v  a2 s.co m*/
private static void runIfAsyncNotComplete(AsyncContext asyncContext, AtomicBoolean isCompleted, Runnable task) {
    try {
        if (asyncContext.getRequest().isAsyncStarted() && isCompleted.compareAndSet(false, true)) {
            task.run();
        }
    } catch (IllegalStateException ex) {
        // Ignore: AsyncContext recycled and should not be used
        // e.g. TIMEOUT_LISTENER (above) may have completed the AsyncContext
    }
}

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  w w  w  .ja  v  a 2s  .co  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.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);/*  www . ja v  a  2s . 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.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"
 * //from   w  w  w  .j  a  va2s  .co 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]);
        }// w ww.  ja  v a2  s .  c  o m
    }

    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 av a2  s. c o  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 {/* ww w .  jav  a 2 s  . c o 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: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;//from  w ww . j a  va 2 s.  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.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  w ww  .  java2s . c  o m*/
        d2jsRunner.run((HttpServletRequest) asyncContext.getRequest(),
                (HttpServletResponse) asyncContext.getResponse(), "delete");
    } finally {
        asyncContext.complete();
    }
}