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