Example usage for javax.servlet.http Cookie getValue

List of usage examples for javax.servlet.http Cookie getValue

Introduction

In this page you can find the example usage for javax.servlet.http Cookie getValue.

Prototype

public String getValue() 

Source Link

Document

Gets the current value of this Cookie.

Usage

From source file:de.unirostock.sems.cbarchive.web.Tools.java

/**
 * Gets the user./*from ww w  .j  a  v a2  s .  c  o  m*/
 *
 * @param cookies the cookies
 * @return the user
 * @throws IOException the IO exception
 */
public static UserManager getUser(CookieManager cookies) throws IOException {
    Cookie pathCookie = cookies.getCookie(Fields.COOKIE_PATH);
    if (pathCookie == null)
        return null;

    cookies.setCookie(pathCookie);

    Cookie userInfo = cookies.getCookie(Fields.COOKIE_USER);

    UserManager user = null;
    if (WorkspaceManager.getInstance().hasWorkspace(pathCookie.getValue())) {
        // workspace exists
        user = new UserManager(pathCookie.getValue());
        // parse vCard info
        if (userInfo != null && !userInfo.getValue().isEmpty())
            user.setData(UserData.fromJson(userInfo.getValue()));

        storeUserCookies(cookies, user);
    }

    return user;
}

From source file:com.ibm.jaggr.service.impl.transport.AbstractHttpTransport.java

/**
 * This method checks the request for the has conditions which may either be contained in URL 
 * query arguments or in a cookie sent from the client.
 * /*from w  w  w.j a  va 2  s  .  c o  m*/
 * @return The has conditions from the request.
 * @throws UnsupportedEncodingException 
 */
protected static String getHasConditionsFromRequest(HttpServletRequest request) throws IOException {
    String ret = null;
    if (request.getParameter(FEATUREMAPHASH_REQPARAM) != null) {
        // The cookie called 'has' contains the has conditions
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; ret == null && i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(FEATUREMAP_REQPARAM) && cookie.getValue() != null) {
                    ret = URLDecoder.decode(cookie.getValue(), "US-ASCII"); //$NON-NLS-1$
                    break;
                }
            }
        }
        if (ret == null) {
            if (log.isLoggable(Level.WARNING)) {
                StringBuffer url = request.getRequestURL();
                if (url != null) { // might be null if using mock request for unit testing
                    url.append("?").append(request.getQueryString()).toString(); //$NON-NLS-1$
                    log.warning(MessageFormat.format(Messages.AbstractHttpTransport_0,
                            new Object[] { url, request.getHeader("User-Agent") })); //$NON-NLS-1$
                }
            }
        }
    } else
        ret = request.getParameter(FEATUREMAP_REQPARAM);

    return ret;
}

From source file:framework.GlobalHelpers.java

public static String cookieValue(String name) {
    Cookie cookie = FrontController.threadData.get().cookies.get(name);
    return cookie != null ? cookie.getValue() : 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 ww  w . j  a  v a2 s. com*/
    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:dk.netarkivet.common.webinterface.HTMLUtils.java

/**
 * Get a locale from cookie, if present. The default request locale otherwise.
 *
 * @param request The request to get the locale for.
 * @return The cookie locale, if present. The default request locale otherwise.
 */// w  w w.  j  a  v  a  2 s.c  o m
public static String getLocale(HttpServletRequest request) {
    ArgumentNotValid.checkNotNull(request, "request");
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            if (c.getName().equals("locale")) {
                return c.getValue();
            }
        }
    }
    return request.getLocale().toString();
}

From source file:com.erudika.para.utils.Utils.java

/**
 * Reads a cookie.//from   ww  w  .ja v  a2 s . c  o m
 * @param name the name
 * @param req HTTP request
 * @return the cookie value
 */
public static String getCookieValue(HttpServletRequest req, String name) {
    if (StringUtils.isBlank(name) || req == null) {
        return null;
    }
    Cookie cookies[] = req.getCookies();
    if (cookies == null || name == null || name.length() == 0) {
        return null;
    }
    //Otherwise, we have to do a linear scan for the cookie.
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals(name)) {
            return cookie.getValue();
        }
    }
    return null;
}

From source file:com.xpn.xwiki.stats.impl.StatsUtil.java

/**
 * Try to find the visit object in the database from cookie if it's not a new cookie, search by unique id otherwise.
 * /*  www.  ja v  a 2s . c o  m*/
 * @param context the XWiki context.
 * @return the visit statistics object found.
 * @since 1.4M1
 */
private static VisitStats findVisitByCookieOrIPUA(XWikiContext context) {
    VisitStats visitStats = null;

    XWikiRequest request = context.getRequest();

    Cookie cookie = (Cookie) context.get(CONTPROP_STATS_COOKIE);
    boolean newcookie = ((Boolean) context.get(CONTPROP_STATS_NEWCOOKIE)).booleanValue();

    if (!newcookie) {
        try {
            visitStats = findVisitByCookie(cookie.getValue(), context);
        } catch (XWikiException e) {
            LOGGER.error("Failed to find visit by cookie", e);
        }
    } else {
        try {
            String ip = request.getRemoteAddr();
            String ua = request.getHeader(REQPROP_USERAGENT);
            visitStats = findVisitByIPUA(ip + ua, context);
        } catch (XWikiException e) {
            LOGGER.error("Failed to find visit by unique id", e);
        }
    }

    return visitStats;
}

From source file:com.baidu.rigel.biplatform.ma.report.utils.QueryUtils.java

/**
 * /*from w ww  .ja  v a2s .c o  m*/
 * @param params
 * @param request
 * @return Map<String, String>
 */
private static Map<String, String> collectRequestParams(Collection<ReportParam> params,
        HttpServletRequest request) {
    Map<String, String> rs = Maps.newHashMap();
    request.getParameterMap().forEach((k, v) -> {
        rs.put(k, v[0]);
    });
    // cookie??url?
    if (request.getCookies() != null) {
        for (Cookie cookie : request.getCookies()) {
            rs.put(cookie.getName(), cookie.getValue());
        }
    }

    // ???cookie?
    rs.putAll(ContextManager.getParams());
    // ???
    rs.remove(Constants.RANDOMCODEKEY);
    rs.remove(Constants.TOKEN);
    rs.remove(Constants.BIPLATFORM_PRODUCTLINE);

    return rs;
}

From source file:com.xpn.xwiki.stats.impl.StatsUtil.java

/**
 * Indicate of the provided visit object has to be recreated.
 * //w  w w  .j av  a2 s  .  c  o  m
 * @param visitObject the visit object to validate.
 * @param context the XWiki context.
 * @return false if the visit object has to be recreated, true otherwise.
 * @since 1.4M1
 */
private static boolean isVisitObjectValid(VisitStats visitObject, XWikiContext context) {
    boolean valid = true;

    XWikiRequest request = context.getRequest();
    HttpSession session = request.getSession(true);
    Cookie cookie = (Cookie) context.get(CONTPROP_STATS_COOKIE);
    Date nowDate = new Date();

    if (visitObject != null) {
        // Let's verify if the session is valid
        // If the cookie is not the same
        if (!visitObject.getCookie().equals(cookie.getValue())) {
            // Let's log a message here
            // Since the session is also maintained using a cookie
            // then there is something wrong here
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Found visit with cookie " + visitObject.getCookie() + " in session "
                        + session.getId() + " for request with cookie " + cookie.getValue());
            }

            valid = false;
        } else if ((nowDate.getTime() - visitObject.getEndDate().getTime()) > 30 * 60 * 1000) {
            // If session is longer than 30 minutes we should invalidate it
            // and create a new one
            valid = false;
        } else if (visitObject != null && !context.getUser().equals(visitObject.getName())) {
            // If the user is not the same, we should invalidate the session
            // and create a new one
            valid = false;
        }
    }

    return valid;
}

From source file:com.tremolosecurity.proxy.SessionManagerImpl.java

public static TremoloHttpSession findSessionFromCookie(Cookie sessionCookie, SecretKey encKey,
        SessionManagerImpl sessionMgr) throws UnsupportedEncodingException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {
    String tokenHeader = new String(
            org.bouncycastle.util.encoders.Base64.decode(sessionCookie.getValue().getBytes("UTF-8")));
    Gson gson = new Gson();
    Token token = gson.fromJson(tokenHeader, Token.class);
    byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv());

    IvParameterSpec spec = new IvParameterSpec(iv);
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, encKey, spec);

    byte[] encBytes = org.bouncycastle.util.encoders.Base64.decode(token.getEncryptedRequest());
    String requestToken = new String(cipher.doFinal(encBytes));

    TremoloHttpSession tsession = sessionMgr.getSessions().get(requestToken);
    return tsession;
}