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:com.acmeair.web.RESTCookieSessionFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    try {// ww  w .j a v  a 2  s .c  o  m
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String path = request.getContextPath() + request.getServletPath() + request.getPathInfo();
        // The following code is to ensure that OG is always set on the thread
        try {
            TransactionService txService = getTxService();
            if (txService != null)
                txService.prepareForTransaction();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // could do .startsWith for now, but plan to move LOGOUT to its own REST interface eventually
        if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH)) {
            // if logging in, let the request flow
            chain.doFilter(req, resp);
            return;
        }

        Cookie cookies[] = request.getCookies();
        Cookie sessionCookie = null;
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (c.getName().equals(LoginREST.SESSIONID_COOKIE_NAME)) {
                    sessionCookie = c;
                }
                if (sessionCookie != null)
                    break;
            }
            String sessionId = "";
            if (sessionCookie != null) // We need both cookie to work
                sessionId = sessionCookie.getValue().trim();
            else {
                log.info("falling through with a sessionCookie break, but it was null");
            }
            // did this check as the logout currently sets the cookie value to "" instead of aging it out
            // see comment in LogingREST.java
            if (sessionId.equals("")) {
                log.info("sending SC_FORBIDDEN due to empty session cookie");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            // Need the URLDecoder so that I can get @ not %40
            ValidateTokenCommand validateCommand = new ValidateTokenCommand(sessionId);
            CustomerSession cs = validateCommand.execute();
            if (cs != null) {
                request.setAttribute(LOGIN_USER, cs.getCustomerid());
                chain.doFilter(req, resp);
                return;
            } else {
                log.info("sending SC_FORBIDDEN due  to validateCommand returning null");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }

        // if we got here, we didn't detect the session cookie, so we need to return 403
        log.info("sending SC_FORBIDDEN due finding no sessionCookie");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } catch (Exception e) {
        e.printStackTrace(System.out);
    }
}

From source file:com.sjc.cc.login.action.LoginAction.java

/**
 * /*from ww w . ja va  2  s  .c  om*/
 * 
 * @return
 * @exception Exception can be thrown by subclasses.
 */
public String logout() throws Exception {
    LoginUserInfo loginUserInfo = LoginUserInfoHolder.getInstance().getCurrentUser();
    if (loginUserInfo != null && loginUserInfo.getEmpName() != null) {
        logService.saveOperLog("?", "" + loginUserInfo.getEmpName() + ""
                + BusinessEnvironment.OPER_RESULT_SUCCESS, loginUserInfo, 3);
    }
    sessionUserAccessor.logoutUser(ServletActionContext.getRequest().getSession());
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Cookiecookies[" + i + "].getName()==========[" + cookies[i].getName() + "]");
            }
            if (LoginAction.COOKIE_CC_USER_ID.equals(cookies[i].getName())) {
                cookies[i].setMaxAge(0);
                response.addCookie(cookies[i]);// cookie
                break;
            }
        }
    }
    TccSkin tCcSkin = loginService.getSkindflt();
    if (null != tCcSkin) {
        String dirString = tCcSkin.getSkinDir();
        if (null == dirString || dirString.equals("")) {
            dirString = "";
        }
        request.getSession().setAttribute("changeskin", dirString);
    } else {
        request.getSession().setAttribute("changeskin", "");
    }
    TCcBasicCfg basicCfg = loginService.getBasicCfg();
    request.getSession().setAttribute("basicCfg", basicCfg);
    return "logout";
}

From source file:eu.eidas.node.AbstractNodeServlet.java

/**
 * Sets HTTPOnly Header on the session to prevent cookies from being accessed through
 * client-side script./*w  ww  . jav a  2  s .c o  m*/
 *
 * @param renewSession indicates that the session cookie will be renewed
 */
protected final void setHTTPOnlyHeaderToSession(final boolean renewSession, HttpServletRequest request,
        HttpServletResponse response) {
    if (request != null && request.getSession(false) != null) {
        // Renewing the session if necessary
        String currentSession = null;
        String messageLog = null;
        if (renewSession) {
            currentSession = sessionIdRegenerationInWebApp(request);
            messageLog = "http session Renewed : {}";
        } else {
            currentSession = request.getSession().getId();
            messageLog = "http session obtained from request : {}";
        }
        MDC.put(LoggingMarkerMDC.MDC_SESSIONID, currentSession);
        getLogger().info(LoggingMarkerMDC.SECURITY_SUCCESS, messageLog, currentSession);
        // changing session cookie to http only cookie
        if (request.getCookies() != null && request.isRequestedSessionIdFromCookie()) {
            //Session Id requested by the client, obtained from the cookie
            final String requestedSessionId = request.getRequestedSessionId();
            for (Cookie cookie : request.getCookies()) {
                getLogger().debug("Treating cookie [domain][path][name][value] : [{}][{}][{}][{}]",
                        cookie.getName(), cookie.getPath(), cookie.getName(), cookie.getValue());
                if (currentSession.equals(requestedSessionId)) {
                    // Removes old version
                    boolean isSecure = request.isSecure();
                    getLogger().debug("Cookie==session : Remove and replacing with HttpOnly {}",
                            cookie.toString());
                    getLogger().debug("Is using SSL?", isSecure);

                    //TODO: when migrating to servlet 3, use the cookie interface calls below instead of writing the http header
                    //
                    //NOSONAR                        cookie.setMaxAge(0);
                    //NOSONAR                        cookie.setPath(getServletContext().getContextPath());
                    //NOSONAR                 cookie.setDomain(request.getServerName());
                    //NOSONAR                 cookie.setSecure(isSecure);
                    //NOSONAR                 cookie.setHttpOnly(true);
                    //NOSONAR                 response.addCookie(cookie);

                    // Create new one httpOnly
                    StringBuilder httpOnlyCookie = new StringBuilder(cookie.getName())
                            .append(EIDASValues.EQUAL.toString()).append(cookie.getValue())
                            .append(EIDASValues.SEMICOLON.toString()).append(" ")
                            .append(EIDASValues.DOMAIN.toString()).append(EIDASValues.EQUAL.toString())
                            .append(request.getServerName()).append(EIDASValues.SEMICOLON.toString())
                            .append(" ").append(EIDASValues.PATH.toString())
                            .append(EIDASValues.EQUAL.toString()).append(getServletContext().getContextPath())
                            .append(EIDASValues.SEMICOLON.toString()).append(" ")
                            .append(EIDASValues.HTTP_ONLY.toString()).append(EIDASValues.SEMICOLON.toString())
                            .append(isSecure ? EIDASValues.SECURE.toString() : "");
                    response.setHeader(EIDASValues.SETCOOKIE.toString(), httpOnlyCookie.toString());
                }
            }
        }
        //cookie _csrf
        //            request.setAttribute("_csrf_header", "X-CSRF-TOKEN");
        //            UUID idOne = UUID.randomUUID();
        //            LOG.info("generate csrf id="+idOne);
        //            request.setAttribute("_csrf", idOne);
        response.setHeader("_csrf_header", "X-CSRF-TOKEN");
        UUID idOne = UUID.randomUUID();
        UUID idTwo = UUID.randomUUID();
        getLogger().info("generate csrf id1=" + idOne + " id2=" + idTwo);
        Cookie gato = new Cookie("_csrf", idOne.toString());
        response.addCookie(gato);
        response.setHeader("X-CSRF-TOKEN", idTwo.toString());

    } else {
        getLogger().warn(LoggingMarkerMDC.SECURITY_FAILURE, "Request or Session is null !");
    }
}

From source file:com.glaf.core.util.HttpQueryUtils.java

public static BaseQuery prepareQuery(HttpServletRequest request, HttpServletResponse response,
        String serviceKey, Map<String, Object> paramMap) {
    BaseQuery query = new BaseQuery();
    Map<String, Object> params = new java.util.HashMap<String, Object>();
    List<QueryCondition> conditions = new java.util.ArrayList<QueryCondition>();
    JSONObject rootJson = new JSONObject();
    JSONObject paramJson = new JSONObject();
    JSONObject queryJson = new JSONObject();

    String qt = getStringValue(request, "qt");
    String qid = getStringValue(request, "qid");
    String field = getStringValue(request, "field");
    boolean removeLast = getBooleanValue(request, "removeLast");

    queryJson.put("removeLast", removeLast);

    if (serviceKey != null) {
        queryJson.put("serviceKey", serviceKey);
    }//from   w  w w .  jav  a 2s  . c o m
    if (qt != null) {
        queryJson.put("qt", qt);
    }
    if (qid != null) {
        queryJson.put("qid", qid);
    }
    if (field != null) {
        queryJson.put("field", field);
    }

    /**
     * IP?Cookie
     */
    String ip = RequestUtils.getIPAddress(request);
    String cookieKey = ip + "_mx_query_" + serviceKey;
    cookieKey = Hex.bytesToHex(cookieKey.getBytes());

    String content = null;

    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            /**
             * Cookie???
             */
            if (StringUtils.equals(cookie.getName(), cookieKey)) {
                content = cookie.getValue();
            }
        }
    }

    JSONObject oldJson = null;

    if (StringUtils.isNotEmpty(content)) {
        String str = new String(Hex.hexToBytes(content));
        if (str != null) {
            oldJson = JSON.parseObject(str);
        }
    }

    Object value = null;
    String fieldValue = null;
    QueryCondition currentCondition = null;

    if (oldJson != null) {
        logger.debug("@@previous query json:\n" + oldJson.toJSONString());
        JSONObject paramJx = oldJson.getJSONObject("params");
        if (paramJx != null && !paramJx.isEmpty()) {
            Set<String> keySet = paramJx.keySet();
            Iterator<String> iterator = keySet.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                if (paramJx.getString(key) != null) {
                    params.put(key, paramJx.getString(key));
                    paramJson.put(key, paramJx.getString(key));
                }
            }
        }

        JSONObject conjx = oldJson.getJSONObject("currentCondition");
        if (conjx != null && conjx.get("value") != null) {
            currentCondition = new QueryCondition();
            currentCondition.setAlias(conjx.getString("alias"));
            currentCondition.setName(conjx.getString("name"));
            currentCondition.setColumn(conjx.getString("column"));
            currentCondition.setType(conjx.getString("type"));
            currentCondition.setFilter(conjx.getString("filter"));
            currentCondition.setStringValue(conjx.getString("stringValue"));
            currentCondition.setValue(conjx.get("value"));
        }
    }

    Enumeration<?> enumeration = request.getParameterNames();
    while (enumeration.hasMoreElements()) {
        String paramName = (String) enumeration.nextElement();
        String paramValue = getStringValue(request, paramName);
        if (paramName != null) {
            if (StringUtils.isNotEmpty(paramValue)) {
                params.put(paramName, paramValue);
                paramJson.put(paramName, paramValue);
            }
        }
    }

    if (paramMap != null && !paramMap.isEmpty()) {
        if (paramMap != null && paramMap.size() > 0) {
            Set<Entry<String, Object>> entrySet = paramMap.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                String name = entry.getKey();
                Object v = entry.getValue();
                if (name != null && v != null) {
                    params.put(name, v);
                    paramJson.put(name, v);
                }
            }
        }
    }

    if (qt == null) {
        qt = (String) params.get("qt");
    }
    if (qid == null) {
        qid = (String) params.get("qid");
    }
    if (field == null) {
        field = (String) params.get("field");
    }

    /**
     * ??
     */
    if (StringUtils.isNotEmpty(qid)) {
        EntityService entityService = ContextFactory.getBean("entityService");
        /**
         * ?????
         */
        List<Object> rows = entityService.getList(qid, params);
        if (rows != null && rows.size() > 0) {
            for (Object object : rows) {
                if (object instanceof ColumnDefinition) {
                    ColumnDefinition column = (ColumnDefinition) object;
                    query.addColumn(column.getName(), column.getColumnName());
                    if (StringUtils.isNotEmpty(field) && StringUtils.equals(field, column.getName())) {
                        fieldValue = request.getParameter(field);
                        if (StringUtils.isNotEmpty(fieldValue)) {
                            String alias = getStringValue(request, "alias");
                            String filter = getStringValue(request, "filter");
                            if (StringUtils.isEmpty(alias)) {
                                alias = getStringValue(request, field + "_alias");
                            }
                            if (StringUtils.isEmpty(filter)) {
                                filter = getStringValue(request, field + "_filter");
                            }
                            String type = column.getJavaType();
                            if (StringUtils.equalsIgnoreCase(type, "datetime")
                                    || StringUtils.equalsIgnoreCase(type, "Date")) {
                                type = "Date";
                                value = fieldValue;
                                if (StringUtils.isEmpty(filter)) {
                                    filter = SearchFilter.GREATER_THAN_OR_EQUAL;
                                }
                            } else if (StringUtils.equalsIgnoreCase(type, "i4")
                                    || StringUtils.equalsIgnoreCase(type, "Integer")) {
                                type = "Integer";
                                value = Integer.parseInt(fieldValue);
                                if (StringUtils.isEmpty(filter)) {
                                    filter = SearchFilter.GREATER_THAN_OR_EQUAL;
                                }
                            } else if (StringUtils.equalsIgnoreCase(type, "i8")
                                    || StringUtils.equalsIgnoreCase(type, "Long")) {
                                type = "Long";
                                value = Long.parseLong(fieldValue);
                                if (StringUtils.isEmpty(filter)) {
                                    filter = SearchFilter.GREATER_THAN_OR_EQUAL;
                                }
                            } else if (StringUtils.equalsIgnoreCase(type, "r8")
                                    || StringUtils.equalsIgnoreCase(type, "Double")) {
                                type = "Double";
                                value = Double.parseDouble(fieldValue);
                                if (StringUtils.isEmpty(filter)) {
                                    filter = SearchFilter.GREATER_THAN_OR_EQUAL;
                                }
                            } else if (StringUtils.equalsIgnoreCase(type, "String")) {
                                type = "String";
                                value = fieldValue;
                                if (StringUtils.isEmpty(filter)) {
                                    filter = SearchFilter.LIKE;
                                }
                                if (StringUtils.equals(filter, SearchFilter.LIKE)) {
                                    value = "%" + fieldValue + "%";
                                }
                            }
                            if (value != null && filter != null) {
                                currentCondition = new QueryCondition();
                                currentCondition.setType(type);
                                currentCondition.setAlias(alias);
                                currentCondition.setName(field);
                                currentCondition.setColumn(column.getColumnName());
                                currentCondition.setFilter(filter);
                                currentCondition.setStringValue(fieldValue);
                                currentCondition.setValue(value);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * CookieSession??Ta???
     */
    if (oldJson != null) {
        JSONArray array = oldJson.getJSONArray("conditions");
        if (array != null) {
            // logger.debug("previous conditions:" + array.toJSONString());
            int size = array.size();
            for (int i = 0; i < size; i++) {
                JSONObject json = array.getJSONObject(i);
                QueryCondition c = new QueryCondition();
                c.setAlias(json.getString("alias"));
                c.setName(json.getString("name"));
                c.setColumn(json.getString("column"));
                c.setType(json.getString("type"));
                c.setFilter(json.getString("filter"));
                String val = json.getString("stringValue");

                if (StringUtils.equals(c.getType(), "Date")) {
                    c.setValue(DateUtils.toDate(val));
                    c.setStringValue(val);
                } else if (StringUtils.equals(c.getType(), "Integer")) {
                    c.setValue(Integer.parseInt(val));
                    c.setStringValue(val);
                } else if (StringUtils.equals(c.getType(), "Long")) {
                    c.setValue(Long.parseLong(val));
                    c.setStringValue(val);
                } else if (StringUtils.equals(c.getType(), "Double")) {
                    c.setValue(Double.parseDouble(val));
                    c.setStringValue(val);
                } else if (StringUtils.equals(c.getType(), "Boolean")) {
                    c.setValue(Boolean.valueOf(val));
                    c.setStringValue(val);
                } else {
                    c.setValue(json.get("value"));
                    c.setStringValue(val);
                }

                if (!conditions.contains(c)) {
                    conditions.add(c);
                }
            }
        }
        /**
         * ?
         */
        if (removeLast && conditions.size() > 0) {
            conditions.remove(conditions.size() - 1);
        }
    }

    /**
     * ????
     */
    if (StringUtils.equals("R", qt)) {
        logger.debug("#### clear conditions");
        conditions.clear();
    }

    if (currentCondition != null && currentCondition.getValue() != null) {
        query.setCurrentQueryCondition(currentCondition);
        if (!conditions.contains(currentCondition)) {
            conditions.add(currentCondition);
        }
        JSONObject json = new JSONObject();
        if (currentCondition.getAlias() != null) {
            json.put("alias", currentCondition.getAlias());
        }
        json.put("name", currentCondition.getName());
        json.put("column", currentCondition.getColumn());
        json.put("type", currentCondition.getType());
        json.put("filter", currentCondition.getFilter());
        json.put("value", currentCondition.getValue());
        json.put("stringValue", currentCondition.getStringValue());
        json.put("index", 0);
        rootJson.put("currentCondition", json);
    }

    if (conditions.size() > 0) {
        JSONArray jsonArray = new JSONArray();
        int index = 0;
        for (QueryCondition c : conditions) {
            if (c.getValue() != null) {
                JSONObject json = new JSONObject();
                if (c.getAlias() != null) {
                    json.put("alias", c.getAlias());
                }
                json.put("name", c.getName());
                json.put("column", c.getColumn());
                json.put("type", c.getType());
                json.put("filter", c.getFilter());
                json.put("value", c.getValue());
                json.put("stringValue", c.getStringValue());
                json.put("index", index++);
                jsonArray.add(json);
            }
        }
        rootJson.put("conditions", jsonArray);
    }

    rootJson.put("query", queryJson);
    rootJson.put("params", paramJson);

    String jsonText = rootJson.toJSONString();
    logger.debug("prepare query json:\n" + jsonText);

    jsonText = Hex.bytesToHex(jsonText.getBytes());

    if (response != null) {
        Cookie cookie = new Cookie(cookieKey, jsonText);
        response.addCookie(cookie);
    }

    query.setParameter(params);
    query.getParameters().putAll(params);

    logger.debug("#conditions:" + conditions);

    for (QueryCondition condition : conditions) {
        query.addCondition(condition);
    }

    return query;
}

From source file:com.google.gsa.valve.modules.krb.KerberosAuthenticationProcess.java

/**
 * This is the main method that does the Kerberos authentication and 
 * should be invoked by the classes that would like to open a new 
 * authentication process against a Kerberized protected source.
 * <p>//from   w  ww  .j a v a2 s.com
 * It behaves differently if the it's set up as a Negotiation process or 
 * the Kerberos credentials are got from the username and password 
 * credentials. It reads "isNegotiate" var and invokes the proper method 
 * that manages Kerberos authentication specifically for each method.
 * <p>
 * If the Kerberos authentication result is OK, a cookie is created with an  
 * encoded information that includes the username to be reused if this is 
 * needed in any other Authn/AuthZ module. It also populates the credentials 
 * vector with the user's Kerberos credential ("krb5") that the caller 
 * process should reuse when authorizing.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    //Vars             
    int responseCode = HttpServletResponse.SC_UNAUTHORIZED;
    Cookie[] cookies = null;

    // Read cookies
    cookies = request.getCookies();

    //Protection
    logger.debug("Checking if user already has Krb credentials. If so, return OK");

    try {
        if (creds != null) {
            if (creds.getCredential(KRB5_ID) != null) {

                logger.debug("Credential found: " + KRB5_ID);

                if (creds.getCredential(KRB5_ID).getSubject() != null) {

                    //user Kerberos subject already created, so user is authenticated                        
                    logger.debug("Kerberos subject already exists. Returning...");

                    // Set status code
                    responseCode = HttpServletResponse.SC_OK;

                    // Return
                    return responseCode;
                }
            }
        }
    } catch (NullPointerException e) {
        logger.debug("Krb subject does not exist. Continue with the process...");
    }

    try {
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:");
    }

    try {
        logger.debug("Getting credentials");
        //Get Krb config files            
        krbconfig = valveConf.getKrbConfig().getKrbconfig();
        logger.debug("Krb config file: " + krbconfig);
        krbini = valveConf.getKrbConfig().getKrbini();
        logger.debug("Krb ini file: " + krbini);

        if ((isNegotiate) && (serverSubject == null)) {

            try {

                initializeKerberos();

            } catch (Exception ex) {
                logger.error("Exception during Server Kerberos config initialization: " + ex.getMessage(), ex);
            } finally {
            }

        }

        //Get user credentials
        //First read the u/p the credentails store, in this case using the same as the root login
        Credential userNamePwdCred = null;

        if (isNegotiate) {
            logger.debug("KerbAuth: IsNegotiate");
            responseCode = authNegotiate(request, response);
        } else {
            logger.debug("KerbAuth: It's NOT IsNegotiate with id: " + id);

            try {
                logger.debug("HttpKrb: trying to get creds from repository id: " + id);
                userNamePwdCred = creds.getCredential(id);
            } catch (NullPointerException npe) {
                logger.error("NPE while reading credentials of ID: " + id);
            }

            if (userNamePwdCred == null) {
                logger.debug("HttpKrb: trying to get creds from repository \"root\"");
                userNamePwdCred = creds.getCredential("root");
            }

            //Execute Authentication method with username and password
            responseCode = authUsernamePassword(userNamePwdCred);
        }

        if (responseCode == HttpServletResponse.SC_OK) {
            //create cookie
            createCookie(request, response);
            //add cookie to the cookie array
            authCookies.add(gsaKrbAuthCookie);
            //add Krb credentials
            Credential krb5Cred = new Credential(KRB5_ID);
            krb5Cred.setKrbSubject(getUserSubject());
            krb5Cred.setUsername(getUsername());
            creds.add(krb5Cred);
        }

    } catch (Exception e) {
        logger.debug("Error creating Credentials: " + e.getMessage());
        e.printStackTrace();
        responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    return responseCode;
}

From source file:org.hdiv.filter.ValidatorHelperRequest.java

/**
 * Checks if the cookies received in the request are correct. For that, it checks if they are in the user session.
 * //www . j ava 2  s  .  c  om
 * @param request
 *            HttpServletRequest to validate
 * @param target
 *            Part of the url that represents the target action
 * @return valid result if all the cookies received in the request are correct. They must have been previously
 *         stored in the user session by HDIV to be correct. False otherwise.
 * @since HDIV 1.1
 */
public ValidatorHelperResult validateRequestCookies(HttpServletRequest request, String target) {

    Cookie[] requestCookies = request.getCookies();

    if ((requestCookies == null) || (requestCookies.length == 0)) {
        return ValidatorHelperResult.VALID;
    }

    Hashtable sessionCookies = (Hashtable) request.getSession().getAttribute(Constants.HDIV_COOKIES_KEY);

    if (sessionCookies == null) {
        return ValidatorHelperResult.VALID;
    }

    boolean cookiesConfidentiality = Boolean.TRUE.equals(this.hdivConfig.getConfidentiality())
            && this.hdivConfig.isCookiesConfidentialityActivated();

    for (int i = 0; i < requestCookies.length; i++) {

        boolean found = false;
        if (requestCookies[i].getName().equals(Constants.JSESSIONID)) {
            continue;
        }

        if (sessionCookies.containsKey(requestCookies[i].getName())) {

            SavedCookie savedCookie = (SavedCookie) sessionCookies.get(requestCookies[i].getName());
            if (savedCookie.equals(requestCookies[i], cookiesConfidentiality)) {

                found = true;
                if (cookiesConfidentiality) {
                    if (savedCookie.getValue() != null) {
                        requestCookies[i].setValue(savedCookie.getValue());
                    }
                }
            }
        }

        if (!found) {
            this.logger.log(HDIVErrorCodes.COOKIE_INCORRECT, target, "cookie:" + requestCookies[i].getName(),
                    requestCookies[i].getValue());
            return new ValidatorHelperResult(HDIVErrorCodes.COOKIE_INCORRECT);
        }
    }
    return ValidatorHelperResult.VALID;
}

From source file:com.acc.storefront.filters.CartRestorationFilter.java

@Override
public void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    if (getUserService().isAnonymousUser(getUserService().getCurrentUser())) {
        if (getCartFacade().hasSessionCart() && getBaseSiteService().getCurrentBaseSite()
                .equals(getBaseSiteService().getBaseSiteForUID(getCartFacade().getSessionCart().getSite()))) {
            final String guid = getCartFacade().getSessionCart().getGuid();

            if (!StringUtils.isEmpty(guid)) {
                getCartRestoreCookieGenerator().addCookie(response, guid);
            }/*from w  w w.j a  va2  s  .  co  m*/
        } else if (request.getSession().isNew()
                || (getCartFacade().hasSessionCart() && !getBaseSiteService().getCurrentBaseSite().equals(
                        getBaseSiteService().getBaseSiteForUID(getCartFacade().getSessionCart().getSite())))) {
            String cartGuid = null;

            if (request.getCookies() != null) {
                final String anonymousCartCookieName = getCartRestoreCookieGenerator().getCookieName();

                for (final Cookie cookie : request.getCookies()) {
                    if (anonymousCartCookieName.equals(cookie.getName())) {
                        cartGuid = cookie.getValue();
                        break;
                    }
                }
            }

            if (!StringUtils.isEmpty(cartGuid)) {
                try {
                    getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                            getCartFacade().restoreSavedCart(cartGuid));
                } catch (final CommerceCartRestorationException e) {
                    getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                            "basket.restoration.errorMsg");
                }
            }
        }

    } else {
        if ((!getCartFacade().hasSessionCart()
                && getSessionService().getAttribute(WebConstants.CART_RESTORATION) == null)
                || (getCartFacade().hasSessionCart() && !getBaseSiteService().getCurrentBaseSite().equals(
                        getBaseSiteService().getBaseSiteForUID(getCartFacade().getSessionCart().getSite())))) {
            try {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                        getCartFacade().restoreSavedCart(null));
            } catch (final CommerceCartRestorationException e) {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION, "basket.restoration.errorMsg");
            }
        }
    }

    filterChain.doFilter(request, response);
}

From source file:de.hybris.alantrails.storefront.filters.CartRestorationFilter.java

@Override
public void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    if (getUserService().isAnonymousUser(getUserService().getCurrentUser())) {
        if (getCartFacade().hasSessionCart() && getBaseSiteService().getCurrentBaseSite()
                .equals(getBaseSiteService().getBaseSiteForUID(getCartFacade().getSessionCart().getSite()))) {
            final String guid = getCartFacade().getSessionCart().getGuid();

            if (!StringUtils.isEmpty(guid)) {
                getCartRestoreCookieGenerator().addCookie(response, guid);
            }/*from w  w  w .jav a2s .c om*/
        } else if (request.getSession().isNew()
                || (getCartFacade().hasSessionCart() && !getBaseSiteService().getCurrentBaseSite().equals(
                        getBaseSiteService().getBaseSiteForUID(getCartFacade().getSessionCart().getSite())))) {
            String cartGuid = null;

            if (request.getCookies() != null) {
                final String anonymousCartCookieName = getCartRestoreCookieGenerator().getCookieName();

                for (final Cookie cookie : request.getCookies()) {
                    if (anonymousCartCookieName.equals(cookie.getName())) {
                        cartGuid = cookie.getValue();
                        break;
                    }
                }
            }

            if (!StringUtils.isEmpty(cartGuid)) {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION_SHOW_MESSAGE, Boolean.TRUE);
                try {
                    getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                            getCartFacade().restoreSavedCart(cartGuid));
                } catch (final CommerceCartRestorationException e) {
                    getSessionService().setAttribute(WebConstants.CART_RESTORATION_ERROR_STATUS,
                            WebConstants.CART_RESTORATION_ERROR_STATUS);
                }
            }
        }

    } else {
        if ((!getCartFacade().hasSessionCart()
                && getSessionService().getAttribute(WebConstants.CART_RESTORATION) == null)
                || (getCartFacade().hasSessionCart() && !getBaseSiteService().getCurrentBaseSite().equals(
                        getBaseSiteService().getBaseSiteForUID(getCartFacade().getSessionCart().getSite())))) {
            getSessionService().setAttribute(WebConstants.CART_RESTORATION_SHOW_MESSAGE, Boolean.TRUE);
            try {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                        getCartFacade().restoreSavedCart(null));
            } catch (final CommerceCartRestorationException e) {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                        WebConstants.CART_RESTORATION_ERROR_STATUS);
            }
        }
    }

    filterChain.doFilter(request, response);
}

From source file:cec.easyshop.storefront.filters.CartRestorationFilter.java

@Override
public void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    if (getUserService().isAnonymousUser(getUserService().getCurrentUser())) {
        if (getCartService().hasSessionCart() && getBaseSiteService().getCurrentBaseSite().equals(
                getBaseSiteService().getBaseSiteForUID(getCartService().getSessionCart().getSite().getUid()))) {
            final String guid = getCartService().getSessionCart().getGuid();

            if (!StringUtils.isEmpty(guid)) {
                getCartRestoreCookieGenerator().addCookie(response, guid);
            }//from  ww w . j a  v a 2 s.  com
        } else if (request.getSession().isNew() || (getCartService().hasSessionCart()
                && !getBaseSiteService().getCurrentBaseSite().equals(getBaseSiteService()
                        .getBaseSiteForUID(getCartService().getSessionCart().getSite().getUid())))) {
            String cartGuid = null;

            if (request.getCookies() != null) {
                final String anonymousCartCookieName = getCartRestoreCookieGenerator().getCookieName();

                for (final Cookie cookie : request.getCookies()) {
                    if (anonymousCartCookieName.equals(cookie.getName())) {
                        cartGuid = cookie.getValue();
                        break;
                    }
                }
            }

            if (!StringUtils.isEmpty(cartGuid)) {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION_SHOW_MESSAGE, Boolean.TRUE);
                try {
                    getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                            getCartFacade().restoreSavedCart(cartGuid));
                } catch (final CommerceCartRestorationException e) {
                    getSessionService().setAttribute(WebConstants.CART_RESTORATION_ERROR_STATUS,
                            WebConstants.CART_RESTORATION_ERROR_STATUS);
                }
            }
        }

    } else {
        if ((!getCartService().hasSessionCart()
                && getSessionService().getAttribute(WebConstants.CART_RESTORATION) == null)
                || (getCartService().hasSessionCart()
                        && !getBaseSiteService().getCurrentBaseSite().equals(getBaseSiteService()
                                .getBaseSiteForUID(getCartService().getSessionCart().getSite().getUid())))) {
            getSessionService().setAttribute(WebConstants.CART_RESTORATION_SHOW_MESSAGE, Boolean.TRUE);
            try {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                        getCartFacade().restoreSavedCart(null));
            } catch (final CommerceCartRestorationException e) {
                getSessionService().setAttribute(WebConstants.CART_RESTORATION,
                        WebConstants.CART_RESTORATION_ERROR_STATUS);
            }
        }
    }

    filterChain.doFilter(request, response);
}

From source file:com.liferay.portal.action.LogoutAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws Exception {

    try {/*from  ww  w .j  a v a 2  s  .  c o m*/
        HttpSession ses = req.getSession();
        try {
            // Logger.info(this, "User " +
            // PortalUtil.getUser(req).getFullName() + " (" +
            // PortalUtil.getUser(req).getUserId() +
            // ") has logged out from IP: " + req.getRemoteAddr());
            SecurityLogger.logInfo(this.getClass(), "User " + PortalUtil.getUser(req).getFullName() + " ("
                    + PortalUtil.getUser(req).getUserId() + ") has logged out from IP: " + req.getRemoteAddr());
        } catch (Exception e) {
            //Logger.info(this, "User has logged out from IP: " + req.getRemoteAddr());
            SecurityLogger.logInfo(this.getClass(), "User has logged out from IP: " + req.getRemoteAddr());
        }

        EventsProcessor.process(PropsUtil.getArray(PropsUtil.LOGOUT_EVENTS_PRE), req, res);

        ArrayList<Cookie> al = new ArrayList<Cookie>();
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                al.add(cookie);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                res.addCookie(cookie);
            }
        }

        Map sessions = PortletSessionPool.remove(ses.getId());

        if (sessions != null) {
            Iterator itr = sessions.entrySet().iterator();

            while (itr.hasNext()) {
                Map.Entry entry = (Map.Entry) itr.next();

                HttpSession portletSession = (HttpSession) entry.getValue();

                portletSession.invalidate();
            }
        }

        try {
            ses.invalidate();
        } catch (Exception e) {
        }

        EventsProcessor.process(PropsUtil.getArray(PropsUtil.LOGOUT_EVENTS_POST), req, res);

        // ActionForward af = mapping.findForward("referer");
        // return af;
        return mapping.findForward(Constants.COMMON_REFERER);
    } catch (Exception e) {
        req.setAttribute(PageContext.EXCEPTION, e);
        return mapping.findForward(Constants.COMMON_REFERER);
    }
}