001
014
015 package com.liferay.util;
016
017 import com.liferay.portal.kernel.util.GetterUtil;
018 import com.liferay.portal.kernel.util.StringUtil;
019
020 import java.util.Collections;
021 import java.util.HashMap;
022 import java.util.Map;
023
024 import javax.servlet.http.Cookie;
025 import javax.servlet.http.HttpServletRequest;
026
027
033 public class CookieUtil {
034
035 public static String get(HttpServletRequest request, String name) {
036 return get(request, name, true);
037 }
038
039 public static String get(
040 HttpServletRequest request, String name, boolean toUpperCase) {
041
042 Map<String, Cookie> cookieMap = _getCookieMap(request);
043
044 if (toUpperCase) {
045 name = StringUtil.toUpperCase(name);
046 }
047
048 Cookie cookie = cookieMap.get(name);
049
050 if (cookie == null) {
051 return null;
052 }
053 else {
054 return cookie.getValue();
055 }
056 }
057
058 private static Map<String, Cookie> _getCookieMap(
059 HttpServletRequest request) {
060
061 Map<String, Cookie> cookieMap =
062 (Map<String, Cookie>)request.getAttribute(
063 CookieUtil.class.getName());
064
065 if (cookieMap != null) {
066 return cookieMap;
067 }
068
069 Cookie[] cookies = request.getCookies();
070
071 if (cookies == null) {
072 cookieMap = Collections.emptyMap();
073 }
074 else {
075 cookieMap = new HashMap<String, Cookie>(cookies.length * 4 / 3);
076
077 for (Cookie cookie : cookies) {
078 String cookieName = GetterUtil.getString(cookie.getName());
079
080 cookieName = StringUtil.toUpperCase(cookieName);
081
082 cookieMap.put(cookieName, cookie);
083 }
084 }
085
086 request.setAttribute(CookieUtil.class.getName(), cookieMap);
087
088 return cookieMap;
089 }
090
091 }