001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
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    /**
027     * @author Brian Wing Shun Chan
028     * @author Shuyang Zhou
029     */
030    public class CookieUtil {
031    
032            public static String get(HttpServletRequest request, String name) {
033                    Map<String, Cookie> cookieMap = _getCookieMap(request);
034    
035                    Cookie cookie = cookieMap.get(name.toUpperCase());
036    
037                    if (cookie == null) {
038                            return null;
039                    }
040                    else {
041                            return cookie.getValue();
042                    }
043            }
044    
045            private static Map<String, Cookie> _getCookieMap(
046                    HttpServletRequest request) {
047    
048                    Map<String, Cookie> cookieMap =
049                            (Map<String, Cookie>)request.getAttribute(
050                                    CookieUtil.class.getName());
051    
052                    if (cookieMap != null) {
053                            return cookieMap;
054                    }
055    
056                    Cookie[] cookies = request.getCookies();
057    
058                    if (cookies == null) {
059                            cookieMap = Collections.emptyMap();
060                    }
061                    else {
062                            cookieMap = new HashMap<String, Cookie>(cookies.length * 4 / 3);
063    
064                            for (Cookie cookie : cookies) {
065                                    String cookieName = GetterUtil.getString(
066                                            cookie.getName());
067    
068                                    cookieName = cookieName.toUpperCase();
069    
070                                    cookieMap.put(cookieName, cookie);
071                            }
072                    }
073    
074                    request.setAttribute(CookieUtil.class.getName(), cookieMap);
075    
076                    return cookieMap;
077            }
078    
079    }