com.feilong.servlet.http.CookieUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.feilong.servlet.http.CookieUtil.java

Source

/*
 * Copyright (C) 2008 feilong
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.feilong.servlet.http;

import static java.util.Collections.emptyMap;

import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.feilong.core.bean.PropertyUtil;
import com.feilong.servlet.http.entity.CookieEntity;
import com.feilong.tools.jsonlib.JsonUtil;

import static com.feilong.core.Validator.isNotNullOrEmpty;
import static com.feilong.core.Validator.isNullOrEmpty;

/**
 * {@link javax.servlet.http.Cookie Cookie} .
 * 
 * <p>
 * ,? <a href="https://github.com/venusdrogon/feilong-servlet/wiki/CookieUtil">CookieUtil wiki</a>
 * </p>
 * 
 * <p>
 * ?:Cookie?Servlet3
 * </p>
 * 
 * <h3>:</h3>
 * 
 * <h4>
 * case:Cookie
 * </h4>
 * 
 * <blockquote>
 * <p>
 * 1.name??shopName,valuefeilong Cookie (?,Cookie?,?)<br>
 * ?{@link #addCookie(String, String, HttpServletResponse)}<br>
 * :
 * </p>
 * 
 * <p>
 * <code>CookieUtil.addCookie("shopName","feilong",response)</code>
 * </p>
 * 
 * <p>
 * ?:cookie, -1,??
 * </p>
 * 
 * <p>
 * 2.cookie,,? {@link #addCookie(String, String, int, HttpServletResponse)}<br>
 * :
 * </p>
 * 
 * <p>
 * <code>CookieUtil.addCookie("shopName","feilong", SECONDS_PER_DAY,response)</code>
 * </p>
 * 
 * <p>
 * 3.cookiehttpOnly,? {@link #addCookie(CookieEntity, HttpServletResponse)}<br>
 * :
 * </p>
 * 
 * <pre class="code">
 * CookieEntity cookieEntity = new CookieEntity("shopName", "feilong", SECONDS_PER_DAY);
 * cookieEntity.setHttpOnly(true);
 * CookieUtil.addCookie(cookieEntity, response);
 * </pre>
 * 
 * <p>
 * ,,?cookieEntity path,domain
 * </p>
 * </blockquote>
 * 
 * <h4>
 * case:?Cookie
 * </h4>
 * 
 * <blockquote>
 * 
 * <p>
 * 1.? {@link #getCookie(HttpServletRequest, String)}? {@link Cookie}
 * <br>
 * :
 * </p>
 * 
 * <p>
 * <code>CookieUtil.getCookie(request, "shopName")</code>
 * </p>
 * 
 * <p>
 * 2.,? {@link #getCookieValue(HttpServletRequest, String)}?Cookie
 * <br>
 * :
 * </p>
 * 
 * <p>
 * <code>CookieUtil.getCookieValue(request, "shopName")</code>
 * </p>
 * 
 * <p>
 *  "feilong" 
 * </p>
 * 
 * 
 * <p>
 * 3.,? {@link #getCookieMap(HttpServletRequest)}? Cookie namevalue?map
 * <br>
 * :
 * </p>
 * 
 * <p>
 * <code>CookieUtil.getCookieMap(request)</code>
 * </p>
 * 
 * <p>
 * , {@link com.feilong.servlet.http.RequestLogBuilder#build()}
 * </p>
 * </blockquote>
 * 
 * 
 * <h4>
 * case:Cookie
 * </h4>
 * 
 * <blockquote>
 * 
 * <p>
 * 1.? {@link #deleteCookie(String, HttpServletResponse)}?Cookie
 * <br>
 * :
 * </p>
 * 
 * <p>
 * <code>CookieUtil.deleteCookie(request, "shopName")</code>
 * </p>
 * 
 * <p>
 * 2.,Cookie?path,? {@link #deleteCookie(CookieEntity, HttpServletResponse)}?Cookie
 * <br>
 * :
 * </p>
 * 
 * <pre class="code">
 * CookieEntity cookieEntity = new CookieEntity("shopName", "feilong");
 * cookieEntity.setPath("/member/account");
 * CookieUtil.deleteCookie(request, "shopName");
 * </pre>
 * 
 * </blockquote>
 * 
 * @author <a href="http://feitianbenyue.iteye.com/">feilong</a>
 * @see javax.servlet.http.Cookie
 * @see "org.springframework.web.util.CookieGenerator"
 * @see com.feilong.servlet.http.entity.CookieEntity
 * @since 1.0.0
 */
public final class CookieUtil {

    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory.getLogger(CookieUtil.class);

    /** Don't let anyone instantiate this class. */
    private CookieUtil() {
        //AssertionError?. ?????. ???.
        //see Effective Java 2nd
        throw new AssertionError("No " + getClass().getName() + " instances for you!");
    }

    //********************************************************************

    /**
     * ?Cookie.
     * 
     * @param request
     *            HttpServletRequest
     * @param cookieName
     *            cookie??,{@link Cookie#getName()}
     * @return ??cookie, <code>null</code>;<br>
     *         ?, {@link Cookie#getValue()}
     * @see #getCookie(HttpServletRequest, String)
     * @see Cookie#getValue()
     */
    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        Cookie cookie = getCookie(request, cookieName);
        return null == cookie ? null : cookie.getValue();
    }

    /**
     *  {@link Cookie}.
     * 
     * <p>
     * ?? {@link HttpServletRequest#getCookies()}, {@link Cookie#getName()} <code>cookieName</code>  {@link Cookie}
     * </p>
     * 
     * @param request
     *            the request
     * @param cookieName
     *            the cookie name
     * @return  {@link HttpServletRequest#getCookies()} null,null;<br>
     *          <code>cookieName</code> ? {@link Cookie},null
     * @see javax.servlet.http.HttpServletRequest#getCookies()
     * @see javax.servlet.http.Cookie#getName()
     */
    public static Cookie getCookie(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();

        if (isNullOrEmpty(cookies)) {
            LOGGER.info("request's cookies is null or empty!!");
            return null;
        }

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("[getCookie],cookieName:[{}],cookie info:[{}]", cookieName,
                            JsonUtil.format(cookie, 0, 0));
                }
                return cookie;
            }
        }
        LOGGER.info("can't find the cookie:[{}]", cookieName);
        return null;
    }

    /**
     * {@link Cookie} key value? map({@link TreeMap}).
     *
     * @param request
     *            the request
     * @return  {@link HttpServletRequest#getCookies()}, {@link Collections#emptyMap()};<br>
     *         ?, loop cookies,? {@link Cookie#getName()}? {@link Cookie#getValue()} ?map 
     * @see HttpServletRequest#getCookies()
     * @see javax.servlet.http.Cookie#getName()
     * @see javax.servlet.http.Cookie#getValue()
     * @see javax.servlet.jsp.el.ImplicitObjectELResolver.ImplicitObjects#createCookieMap(javax.servlet.jsp.PageContext)
     */
    public static Map<String, String> getCookieMap(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (isNullOrEmpty(cookies)) {
            return emptyMap();
        }

        Map<String, String> map = new TreeMap<>();
        for (Cookie cookie : cookies) {
            map.put(cookie.getName(), cookie.getValue());
        }
        return map;
    }

    //*********************************************************************************

    /**
     * {@link Cookie}.
     * 
     * <p style="color:red">
     * {@link Cookie},path??;<br>
     * path?, {@link CookieUtil#deleteCookie(CookieEntity, HttpServletResponse)}
     * </p>
     * 
     * @param cookieName
     *            the cookie name
     * @param response
     *            the response
     * @see #deleteCookie(CookieEntity, HttpServletResponse)
     */
    public static void deleteCookie(String cookieName, HttpServletResponse response) {
        deleteCookie(new CookieEntity(cookieName, ""), response);
    }

    /**
     * cookie.
     * 
     * <p style="color:red">
     *  Cookie,path??
     * </p>
     * 
     * @param cookieEntity
     *            the cookie entity
     * @param response
     *            the response
     * @see #addCookie(CookieEntity, HttpServletResponse)
     * @since 1.5.0
     */
    public static void deleteCookie(CookieEntity cookieEntity, HttpServletResponse response) {
        Validate.notNull(cookieEntity, "cookieEntity can't be null!");

        cookieEntity.setMaxAge(0);// 0?Cookie
        addCookie(cookieEntity, response);

        LOGGER.debug("[deleteCookie],cookieName:[{}]", cookieEntity.getName());
    }

    //****************************************************************************************************

    /**
     * cookie.
     * 
     * <p>
     * ?:cookie, -1,??
     * </p>
     * 
     * <p>
     *  <code>cookieName</code> null, {@link NullPointerException}<br>
     *  <code>cookieName</code> blank, {@link IllegalArgumentException}<br>
     * </p>
     *
     * @param cookieName
     *            the cookie name
     * @param value
     *            cookie,,?? {@link CookieEntity#getValue()}
     *            <p style="color:red">
     *            ?:4K,?,??
     *            </p>
     * @param response
     *            response
     * @see CookieUtil#addCookie(CookieEntity, HttpServletResponse)
     * @since 1.5.0
     */
    public static void addCookie(String cookieName, String value, HttpServletResponse response) {
        Validate.notBlank(cookieName, "cookieName can't be null/empty!");
        addCookie(new CookieEntity(cookieName, value), response);
    }

    /**
     * cookie.
     * 
     * <p>
     *  <code>cookieName</code> null, {@link NullPointerException}<br>
     *  <code>cookieName</code> blank, {@link IllegalArgumentException}<br>
     * </p>
     *
     * @param cookieName
     *            the cookie name
     * @param value
     *            cookie,,?? {@link CookieEntity#getValue()}
     *            <p style="color:red">
     *            ?:4K,?,??
     *            </p>
     * @param maxAge
     *            cookie,? {@link com.feilong.core.TimeInterval TimeInterval}?
     * @param response
     *            response
     * @see CookieUtil#addCookie(CookieEntity, HttpServletResponse)
     * @since 1.5.0
     */
    public static void addCookie(String cookieName, String value, int maxAge, HttpServletResponse response) {
        Validate.notBlank(cookieName, "cookieName can't be null/empty!");
        addCookie(new CookieEntity(cookieName, value, maxAge), response);
    }

    /**
     * cookie.
     * 
     * @param cookieEntity
     *            cookieEntity
     * @param response
     *            response
     * @see "org.apache.catalina.connector.Response#generateCookieString(Cookie, boolean)"
     */
    public static void addCookie(CookieEntity cookieEntity, HttpServletResponse response) {
        validateCookieEntity(cookieEntity);//

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[addCookie],cookieEntity info:[{}]", JsonUtil.format(cookieEntity, 0, 0));
        }
        response.addCookie(toCookie(cookieEntity));
    }

    /**
     * To cookie.
     *
     * @param cookieEntity
     *            the cookie entity
     * @return the cookie
     * @since 1.5.3
     */
    private static Cookie toCookie(CookieEntity cookieEntity) {
        Cookie cookie = new Cookie(cookieEntity.getName(), cookieEntity.getValue());
        PropertyUtil.copyProperties(cookie, cookieEntity, "maxAge", "secure", "version", "httpOnly");

        PropertyUtil.setPropertyIfValueNotNullOrEmpty(cookie, "comment", cookieEntity.getComment());//???cookie.
        //NullPointerException at javax.servlet.http.Cookie.setDomain(Cookie.java:213) ~[servlet-api-6.0.37.jar:na]
        PropertyUtil.setPropertyIfValueNotNullOrEmpty(cookie, "domain", cookieEntity.getDomain());// cookie.
        PropertyUtil.setPropertyIfValueNotNullOrEmpty(cookie, "path", cookieEntity.getPath());//cookiecookie.
        return cookie;
    }

    /**
     * Validate cookie entity.
     *
     * @param cookieEntity
     *            the cookie entity
     * @since 1.5.0
     */
    private static void validateCookieEntity(CookieEntity cookieEntity) {
        Validate.notNull(cookieEntity, "cookieEntity can't be null!");
        Validate.notBlank(cookieEntity.getName(), "cookieName can't be null/empty!");

        String value = cookieEntity.getValue();

        //4000,????
        if (isNotNullOrEmpty(value) && value.length() > 4000) {
            String pattern = "cookie value:{},length:{},more than 4000!!!some browser may be not support!!!!!,cookieEntity info :{}";
            LOGGER.warn(pattern, value, value.length(), JsonUtil.format(cookieEntity, 0, 0));
        }
    }
}