Example usage for javax.servlet.http HttpServletRequest getCookies

List of usage examples for javax.servlet.http HttpServletRequest getCookies

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getCookies.

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:org.apache.hadoop.security.authentication.server.AuthenticationFilter.java

/**
 * Returns the {@link AuthenticationToken} for the request.
 * <p/>/*from w  ww . ja v  a 2  s. c om*/
 * It looks at the received HTTP cookies and extracts the value of the {@link AuthenticatedURL#AUTH_COOKIE}
 * if present. It verifies the signature and if correct it creates the {@link AuthenticationToken} and returns
 * it.
 * <p/>
 * If this method returns <code>null</code> the filter will invoke the configured {@link AuthenticationHandler}
 * to perform user authentication.
 *
 * @param request request object.
 *
 * @return the Authentication token if the request is authenticated, <code>null</code> otherwise.
 *
 * @throws IOException thrown if an IO error occurred.
 * @throws AuthenticationException thrown if the token is invalid or if it has expired.
 */
protected AuthenticationToken getToken(HttpServletRequest request) throws IOException, AuthenticationException {
    AuthenticationToken token = null;
    String tokenStr = null;
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(AuthenticatedURL.AUTH_COOKIE)) {
                tokenStr = cookie.getValue();
                try {
                    tokenStr = signer.verifyAndExtract(tokenStr);
                } catch (SignerException ex) {
                    throw new AuthenticationException(ex);
                }
                break;
            }
        }
    }
    if (tokenStr != null) {
        token = AuthenticationToken.parse(tokenStr);
        if (!token.getType().equals(authHandler.getType())) {
            throw new AuthenticationException("Invalid AuthenticationToken type");
        }
        if (token.isExpired()) {
            throw new AuthenticationException("AuthenticationToken expired");
        }
    }
    return token;
}

From source file:org.apache.catalina.authenticator.FormAuthenticator.java

/**
 * Save the original request information into our session.
 *
 * @param request The request to be saved
 * @param session The session to contain the saved information
 *///  ww  w. jav a2 s  . co  m
private void saveRequest(HttpRequest request, Session session) {

    // Create and populate a SavedRequest object for this request
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    SavedRequest saved = new SavedRequest();
    Cookie cookies[] = hreq.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++)
            saved.addCookie(cookies[i]);
    }
    Enumeration names = hreq.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration values = hreq.getHeaders(name);
        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            saved.addHeader(name, value);
        }
    }
    Enumeration locales = hreq.getLocales();
    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        saved.addLocale(locale);
    }
    Map parameters = hreq.getParameterMap();
    Iterator paramNames = parameters.keySet().iterator();
    while (paramNames.hasNext()) {
        String paramName = (String) paramNames.next();
        String paramValues[] = (String[]) parameters.get(paramName);
        saved.addParameter(paramName, paramValues);
    }
    saved.setMethod(hreq.getMethod());
    saved.setQueryString(hreq.getQueryString());
    saved.setRequestURI(hreq.getRequestURI());

    // Stash the SavedRequest in our session for later use
    session.setNote(Constants.FORM_REQUEST_NOTE, saved);

}

From source file:edu.jhu.pha.vospace.oauth.AuthorizationServlet.java

/**
 * @param request//from  w ww.j a  v a 2 s  .  c om
 * @param response
 * @param callbackUrl
 * @throws IOException
 * @throws Oops
 */
private void authorizeRequestToken(HttpServletRequest request, HttpServletResponse response, String username)
        throws Oops {

    String token = null, callbackUrl = null;

    Cookie[] cookies = request.getCookies();

    String shareId = null;

    if (null != request.getParameter("oauth_token")) {
        token = request.getParameter("oauth_token");
        callbackUrl = request.getParameter("oauth_callback");
    } else if (cookies != null) {
        OauthCookie parsedCookie = null;

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(OauthCookie.COOKIE_NAME)) {
                // Remove the temporary 3rd party app cookie
                Cookie removeCookie = new Cookie(OauthCookie.COOKIE_NAME, "");
                removeCookie.setMaxAge(0);
                response.addCookie(removeCookie);
                try {
                    parsedCookie = OauthCookie.create(cookie);
                    shareId = parsedCookie.getShareId();
                    if (isBlank(parsedCookie.getRequestToken()))
                        throw new Oops(
                                "No request token present in oauth cookie (\"" + cookie.getValue() + "\").");
                    logger.debug("Parsed oauth cookie \"" + cookie.getValue() + "\" as \""
                            + parsedCookie.toString() + "\".");
                } catch (IOException e) {
                    logger.debug("Error parsing cookie. Just removing it.");
                }
            }
        }

        if (null != parsedCookie) {
            token = parsedCookie.getRequestToken();
            callbackUrl = parsedCookie.getCallbackUrl();
        }
    }

    if (null == token)
        throw new Oops("No request token found in request.");

    try {
        Token reqToken = MySQLOAuthProvider2.getRequestToken(token);
        if (null == reqToken)
            throw new PermissionDeniedException("401 Unauthorized");
        if (null != reqToken.getAttributes().getFirst("root_container")) { // pre-shared container accessor
            if (shareId != null) {//already created the share - user bound sharing
                List<String> groupUserLogins = MySQLOAuthProvider2.getShareUsers(shareId);
                if (!groupUserLogins.contains(username)) { // the username of the one authorized != user that share was created for
                    throw new PermissionDeniedException("401 Unauthorized");
                }
            } // else share is open for everyone
        }

        MySQLOAuthProvider2.markAsAuthorized(reqToken, username);

        if (null != callbackUrl && !callbackUrl.isEmpty()) {
            if (callbackUrl.indexOf('?') <= 0)
                callbackUrl += "?" + "oauth_token=" + reqToken.getToken();
            else
                callbackUrl += "&" + "oauth_token=" + reqToken.getToken();
            logger.debug("Redirecting user to " + callbackUrl);
            response.sendRedirect(callbackUrl);
        } else {
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            out.println("You have successfully authorized "
                    + ".\nPlease close this browser window and click continue" + " in the client.");
            out.close();
        }
    } catch (IOException e) {
        logger.error("Error performing the token authorization " + e.getMessage());
        e.printStackTrace();
        throw new Oops(e.getMessage());
    }
}

From source file:fr.mby.portal.coreimpl.app.BasicAppSigner.java

@Override
public String retrieveSignature(final HttpServletRequest request) {
    String signature = null;/* w  w w.j  a  v  a2s . co  m*/

    final Object attrObject = request.getAttribute(IPortal.SIGNATURE_PARAM_NAME);
    if (attrObject != null && attrObject instanceof String) {
        signature = (String) attrObject;
    }

    if (!StringUtils.hasText(signature)) {
        signature = request.getParameter(IPortal.SIGNATURE_PARAM_NAME);
    }

    if (!StringUtils.hasText(signature)) {
        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                if (cookie != null && IPortal.SIGNATURE_PARAM_NAME.equals(cookie.getName())) {
                    signature = cookie.getValue();
                }
            }
        }
    }

    if (!StringUtils.hasText(signature)) {
        request.setAttribute(IPortal.SIGNATURE_PARAM_NAME, signature);
    }

    return signature;
}

From source file:org.acegisecurity.ui.savedrequest.SavedRequest.java

public SavedRequest(HttpServletRequest request, PortResolver portResolver) {
    Assert.notNull(request, "Request required");
    Assert.notNull(portResolver, "PortResolver required");

    // Cookies/*from www .  j a  va2  s  . c  o m*/
    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            this.addCookie(cookies[i]);
        }
    }

    // Headers
    Enumeration names = request.getHeaderNames();

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        Enumeration values = request.getHeaders(name);

        while (values.hasMoreElements()) {
            String value = (String) values.nextElement();
            this.addHeader(name, value);
        }
    }

    // Locales
    Enumeration locales = request.getLocales();

    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        this.addLocale(locale);
    }

    // Parameters
    Map parameters = request.getParameterMap();
    Iterator paramNames = parameters.keySet().iterator();

    while (paramNames.hasNext()) {
        String paramName = (String) paramNames.next();
        Object o = parameters.get(paramName);
        if (o instanceof String[]) {
            String[] paramValues = (String[]) o;
            this.addParameter(paramName, paramValues);
        } else {
            if (logger.isWarnEnabled()) {
                logger.warn("ServletRequest.getParameterMap() returned non-String array");
            }
        }
    }

    // Primitives
    this.method = request.getMethod();
    this.pathInfo = request.getPathInfo();
    this.queryString = request.getQueryString();
    this.requestURI = request.getRequestURI();
    this.serverPort = portResolver.getServerPort(request);
    this.requestURL = request.getRequestURL().toString();
    this.scheme = request.getScheme();
    this.serverName = request.getServerName();
    this.contextPath = request.getContextPath();
    this.servletPath = request.getServletPath();
}

From source file:com.hangum.tadpole.application.start.dialog.login.LoginDialog.java

/**
 * initialize cookie data//from w  w  w .  j a v a2  s  .com
 */
private void initCookieData() {
    HttpServletRequest request = RWT.getRequest();
    Cookie[] cookies = request.getCookies();

    if (cookies != null) {
        int intCount = 0;
        for (Cookie cookie : cookies) {
            if (PublicTadpoleDefine.TDB_COOKIE_USER_ID.equals(cookie.getName())) {
                textEMail.setText(cookie.getValue());
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_PWD.equals(cookie.getName())) {
                textPasswd.setText(cookie.getValue());
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_SAVE_CKECK.equals(cookie.getName())) {
                btnCheckButton.setSelection(Boolean.parseBoolean(cookie.getValue()));
                intCount++;
            } else if (PublicTadpoleDefine.TDB_COOKIE_USER_LANGUAGE.equals(cookie.getName())) {
                comboLanguage.setText(cookie.getValue());
                changeUILocale(comboLanguage.getText());
                intCount++;
            }

            if (intCount == 4)
                break;
        }
    }
}

From source file:com.google.identitytoolkit.GitkitClient.java

private String lookupCookie(HttpServletRequest request, String cookieName) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return null;
    }/*from  www .j  a va  2 s .  c o  m*/
    for (Cookie cookie : cookies) {
        if (cookieName.equals(cookie.getName())) {
            return cookie.getValue();
        }
    }
    return null;
}

From source file:fr.cph.stock.web.servlet.portfolio.ModifyEquityServlet.java

@Override
protected final void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException {
    try {/*from ww  w . j  a  v a 2 s.  co  m*/
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
        String lang = CookieManagement.getCookieLanguage(Arrays.asList(request.getCookies()));
        LanguageFactory language = LanguageFactory.getInstance();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        Double quantity = null, unitCostPrice = null, stopLoss = null, objective = null, yieldPersonal = null,
                parityPersonal = null;
        String namePersonal = null, sectorPersonal = null, industryPersonal = null, marketCapPersonal = null;
        try {
            if (request.getParameter("delete") != null) {
                if (request.getParameter("manual") != null) {
                    String id = request.getParameter("id");
                    String companyId = request.getParameter("companyId");
                    Equity e = new Equity();
                    e.setid(Integer.parseInt(id));
                    business.deleteEquity(e);
                    Company company = new Company();
                    company.setId(Integer.parseInt(companyId));
                    business.deleteCompany(company);
                    request.setAttribute("modified", language.getLanguage(lang).get("CONSTANT_DELETED") + " !");
                } else {
                    String id = request.getParameter("id");
                    Equity e = new Equity();
                    e.setid(Integer.parseInt(id));
                    business.deleteEquity(e);
                    request.setAttribute("modified", language.getLanguage(lang).get("CONSTANT_DELETED") + " !");
                }
            } else {
                String ticker = request.getParameter("ticker");
                String namePerso = request.getParameter("namePersonal");
                if (!namePerso.equals("")) {
                    namePersonal = namePerso;
                }
                String sectorPerso = request.getParameter("sectorPersonal");
                if (!sectorPerso.equals("")) {
                    sectorPersonal = sectorPerso;
                }
                String industryPerso = request.getParameter("industryPersonal");
                if (!industryPerso.equals("")) {
                    industryPersonal = industryPerso;
                }
                String marketCapPerso = request.getParameter("marketCapPersonal");
                if (!marketCapPerso.equals("")) {
                    marketCapPersonal = marketCapPerso;
                }
                String quant = request.getParameter("quantity");
                if (!quant.equals("")) {
                    quantity = NumberUtils.createDouble(quant);
                } else {
                    quantity = 0.0;
                }
                String unitCostP = request.getParameter("unitCostPrice");
                if (!unitCostP.equals("")) {
                    unitCostPrice = NumberUtils.createDouble(unitCostP);
                } else {
                    unitCostPrice = 0.0;
                }
                String stopLo = request.getParameter("stopLoss");
                if (!stopLo.equals("")) {
                    stopLoss = NumberUtils.createDouble(stopLo);
                }
                String objc = request.getParameter("objective");
                if (!objc.equals("")) {
                    objective = NumberUtils.createDouble(objc);
                }
                String yieldPerso = request.getParameter("yieldPersonal");
                if (!yieldPerso.equals("")) {
                    yieldPersonal = NumberUtils.createDouble(yieldPerso);
                }
                String parityPerso = request.getParameter("modifyParityPersonal");
                if (!parityPerso.equals("")) {
                    parityPersonal = NumberUtils.createDouble(parityPerso);
                }
                if (quantity == 0) {
                    request.setAttribute("modifyError", "Error: quantity can not be 0");
                } else {
                    Equity equity = new Equity();
                    equity.setNamePersonal(namePersonal);
                    equity.setSectorPersonal(sectorPersonal);
                    equity.setIndustryPersonal(industryPersonal);
                    equity.setMarketCapPersonal(marketCapPersonal);
                    equity.setQuantity(quantity);
                    equity.setUnitCostPrice(unitCostPrice);
                    equity.setStopLossLocal(stopLoss);
                    equity.setObjectivLocal(objective);
                    equity.setYieldPersonal(yieldPersonal);
                    equity.setParityPersonal(parityPersonal);
                    business.updateEquity(user.getId(), ticker, equity);
                    request.setAttribute("modified",
                            language.getLanguage(lang).get("CONSTANT_MODIFIED") + " !");
                }
                if (request.getParameter("manual") != null) {
                    String companyId = request.getParameter("companyId");
                    String quote = request.getParameter("quote");
                    Double quoteRes = null;
                    Integer companyIdRes = null;
                    if (quote != null && !quote.equals("") && companyId != null && !companyId.equals("")) {
                        quoteRes = Double.parseDouble(quote);
                        companyIdRes = Integer.parseInt(companyId);
                        business.updateCompanyManual(companyIdRes, quoteRes);
                    }
                }
            }
        } catch (YahooException e) {
            LOG.warn(e.getMessage(), e);
            request.setAttribute("modifyError", "Error: " + e.getMessage());
        } catch (NumberFormatException e) {
            LOG.warn(e.getMessage(), e);
            request.setAttribute("modifyError", "Error: " + e.getMessage());
        }
        request.getRequestDispatcher("home").forward(request, response);
    } catch (Throwable t) {
        LOG.error(t.getMessage(), t);
        throw new ServletException("Error: " + t.getMessage(), t);
    }
}

From source file:com.stratelia.webactiv.survey.servlets.SurveyRequestRouter.java

/**
 * Read cookie from anonymous user and set status of anonymous user to allow him to vote or not
 * @param request the current HttpServletRequest
 * @param surveySC the survey session controller
 *///from  www .j  a v  a 2 s. co m
private void setAnonymousParticipationStatus(HttpServletRequest request, SurveySessionController surveySC) {
    surveySC.hasAlreadyParticipated(false);
    String surveyId = request.getParameter("SurveyId");
    if (surveyId != null) {
        Cookie[] cookies = request.getCookies();
        String cookieName = SurveySessionController.COOKIE_NAME + surveyId;
        for (int i = 0; i < cookies.length; i++) {
            Cookie currentCookie = cookies[i];
            if (currentCookie.getName().equals(cookieName)) {
                surveySC.hasAlreadyParticipated(true);
                break;
            }
        }
    }
}

From source file:com.salesmanager.catalog.CatalogInterceptor.java

@Override
protected String doIntercept(ActionInvocation invoke, HttpServletRequest req, HttpServletResponse resp)
        throws Exception {

    /** remove profile url **/
    req.getSession().removeAttribute("profileUrl");

    /** synchronize mini shopping cart**/

    //get http session shopping cart
    ShoppingCart cart = SessionUtil.getMiniShoppingCart(req);
    MerchantStore mStore = SessionUtil.getMerchantStore(req);

    if (cart == null) {//synch only when the cart is null or empty

        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(CatalogConstants.SKU_COOKIE + mStore.getMerchantId())) {

                    Locale locale = LocaleUtil.getLocale(req);

                    String cookieValue = StringUtil.unescape(cookie.getValue());

                    ShoppingCart sc = MiniShoppingCartSerializationUtil.deserializeJSON(cookieValue, mStore,
                            locale);//  w ww .ja  v  a  2 s  .c  o  m
                    if (sc != null) {

                        MiniShoppingCartUtil.calculateTotal(sc, mStore);
                        SessionUtil.setMiniShoppingCart(sc, req);

                    } else {//expire cookie
                        cookie.setValue(null);
                        cookie.setMaxAge(0);
                        resp.addCookie(cookie);
                    }
                }
            }
        }

    }

    return null;

}