com.lushapp.common.web.utils.WebUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.lushapp.common.web.utils.WebUtils.java

Source

/**
 *  Copyright (c) 2014 http://www.lushapp.wang
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.lushapp.common.web.utils;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.lushapp.common.utils.StringUtils;
import com.lushapp.common.utils.browser.BrowserUtils;
import com.lushapp.common.utils.encode.EncodeUtils;
import com.lushapp.common.utils.mapper.JsonMapper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.zip.GZIPOutputStream;

/**
 * HttpServlet.
 * 
 * @author honey.zhao@aliyun.com  
 */
public class WebUtils extends org.springframework.web.util.WebUtils {

    private static final Log logger = LogFactory.getLog(WebUtils.class);

    //-- header ? --//
    private static final String HEADER_ENCODING = "encoding";
    private static final String HEADER_NOCACHE = "no-cache";
    private static final String DEFAULT_ENCODING = "UTF-8";
    private static final boolean DEFAULT_NOCACHE = true;

    //-- Content Type  --//
    public static final String TEXT_TYPE = "text/plain";
    public static final String JSON_TYPE = "application/json";
    public static final String XML_TYPE = "text/xml";
    public static final String HTML_TYPE = "text/html";
    public static final String JS_TYPE = "text/javascript";
    public static final String EXCEL_TYPE = "application/vnd.ms-excel";

    //-- Header  --//
    public static final String AUTHENTICATION_HEADER = "Authorization";

    //--  --//
    public static final long ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;

    /**
     *  Header.
     */
    public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) {
        // Http 1.0 header
        response.setDateHeader("Expires", System.currentTimeMillis() + expiresSeconds * 1000);
        // Http 1.1 header
        response.setHeader("Cache-Control", "max-age=" + expiresSeconds);
    }

    /**
     * Header.
     */
    public static void setNoCacheHeader(HttpServletResponse response) {
        //Http 1.0 header
        response.setDateHeader("Expires", 1L);
        response.addHeader("Pragma", "no-cache");
        //Http 1.1 header
        response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
    }

    /**
     * LastModified Header.
     */
    public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) {
        response.setDateHeader("Last-Modified", lastModifiedDate);
    }

    /**
     * Etag Header.
     */
    public static void setEtag(HttpServletResponse response, String etag) {
        response.setHeader("ETag", etag);
    }

    /**
     * ??If-Modified-Since Header, ?.
     * <p/>
     * , checkIfModifyfalse ,304 not modify status.
     * 
     * @param lastModified
     *            ?.
     */
    public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,
            long lastModified) {
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return false;
        }
        return true;
    }

    /**
     * ?? If-None-Match Header, Etag?.
     * <p/>
     * Etag, checkIfNoneMatchfalse, 304 not modify status.
     * 
     * @param etag
     *            ETag.
     */
    public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response,
            String etag) {
        String headerValue = request.getHeader("If-None-Match");
        if (headerValue != null) {
            boolean conditionSatisfied = false;
            if (!"*".equals(headerValue)) {
                StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

                while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                    String currentToken = commaTokenizer.nextToken();
                    if (currentToken.trim().equals(etag)) {
                        conditionSatisfied = true;
                    }
                }
            } else {
                conditionSatisfied = true;
            }

            if (conditionSatisfied) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                response.setHeader("ETag", etag);
                return false;
            }
        }
        return true;
    }

    /**
     * ???gzip?.
     */
    public static boolean checkAccetptGzip(HttpServletRequest request) {
        // Http1.1 header
        String acceptEncoding = request.getHeader("Accept-Encoding");

        if (StringUtils.contains(acceptEncoding, "gzip")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Gzip HeaderGZIPOutputStream.
     */
    public static OutputStream buildGzipOutputStream(HttpServletResponse response) throws IOException {
        response.setHeader("Content-Encoding", "gzip");
        response.setHeader("Vary", "Accept-Encoding");
        return new GZIPOutputStream(response.getOutputStream());
    }

    /**
     * ??Header.
     * 
     * @param fileName
     *            ???.
     */
    public static void setDownloadableHeader(HttpServletResponse response, String fileName) {
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    }

    /**
     * ??Header.
     *
     * @param fileName ???.
     */
    public static void setDownloadableHeader(HttpServletRequest request, HttpServletResponse response,
            String fileName) {
        try {
            if (BrowserUtils.isIE(request)) {
                response.setHeader("content-disposition",
                        "attachment;filename=\"" + java.net.URLEncoder.encode(fileName, "UTF-8") + "\"");
            } else {
                //???
                String encodedfileName = new String(fileName.getBytes(), "ISO8859-1");
                response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
            }

        } catch (UnsupportedEncodingException e) {
        }
    }

    /**
     * ???Request Parameters.
     * <p/>
     * Parameter???.
     */
    public static Map<String, Object> getParametersStartingWith(HttpServletRequest request, String prefix) {
        return org.springframework.web.util.WebUtils.getParametersStartingWith(request, prefix);
    }

    /**
     * ?Ajax.
     * 
     * @param request
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        if (header != null && "XMLHttpRequest".equals(header)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Http Basic? Header?.
     */
    public static String encodeHttpBasic(String userName, String password) {
        String encode = userName + ":" + password;
        return "Basic " + EncodeUtils.base64Encode(encode.getBytes());
    }

    /**
     * ?HttpRequestParameter.
     */
    public static <T> T getParameter(HttpServletRequest request, String name) {
        return (T) request.getParameter(name);
    }

    /**
     * ?sessiont attribute
     *
     * @param name ??
     * @return T
     */
    public static <T> T getSessionAttribute(HttpSession session, String name) {
        return (T) session.getAttribute(name);
    }

    /**
     * ?contentTypeheaders.
     */
    private static HttpServletResponse initResponseHeader(HttpServletResponse response, final String contentType,
            final String... headers) {
        //?headers?
        String encoding = DEFAULT_ENCODING;
        boolean noCache = DEFAULT_NOCACHE;
        for (String header : headers) {
            String headerName = org.apache.commons.lang3.StringUtils.substringBefore(header, ":");
            String headerValue = org.apache.commons.lang3.StringUtils.substringAfter(header, ":");

            if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
                encoding = headerValue;
            } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
                noCache = Boolean.parseBoolean(headerValue);
            } else {
                throw new IllegalArgumentException(headerName + "??header");
            }
        }

        //headers?
        String fullContentType = contentType + ";charset=" + encoding;
        response.setContentType(fullContentType);
        if (noCache) {
            WebUtils.setNoCacheHeader(response);
        }

        return response;
    }

    /**
     * .
        
     * eg.
     * render("text/plain", "hello", "encoding:GBK");
     * render("text/plain", "hello", "no-cache:false");
     * render("text/plain", "hello", "encoding:GBK", "no-cache:false");
     *
     * @param headers ??header??"encoding:""no-cache:",UTF-8true.
     */
    public static void render(HttpServletResponse response, final String contentType, final Object data,
            final String... headers) {
        initResponseHeader(response, contentType, headers);
        try {
            JsonMapper.getInstance().writeValue(response.getWriter(), data);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * .
     * @see #render(javax.servlet.http.HttpServletResponse, String, Object, String...)
     * @param response
     * @param data ? ?List Map
     * @param headers  null UTF-8? 
     * @throws IOException
     */
    public static void renderText(HttpServletResponse response, Object data, final String... headers) {
        render(response, TEXT_TYPE, data, headers);
    }

    /**
     * HTML.
     * @see #render(javax.servlet.http.HttpServletResponse, String, Object, String...)
     * @param response
     * @param data ? ?List Map
     * @param headers  null UTF-8? 
     * @throws IOException
     */
    public static void renderHtml(HttpServletResponse response, Object data, final String... headers) {
        render(response, HTML_TYPE, data, headers);
    }

    /**
     * XML.
     * @see #render(javax.servlet.http.HttpServletResponse, String, Object, String...)
     * @param response
     * @param data ? ?List Map
     * @param headers  null UTF-8? 
     * @throws IOException
     */
    public static void renderXml(HttpServletResponse response, Object data, final String... headers) {
        renderXml(response, data, new XmlMapper(), headers);
    }

    /**
     * XML.
     * @see #render(javax.servlet.http.HttpServletResponse, String, Object, String...)
     * @param response
     * @param data ? ?List Map
     * @param xmlMapper {@link XmlMapper}
     * @param headers  null UTF-8? 
     * @throws IOException
     */
    public static void renderXml(HttpServletResponse response, Object data, XmlMapper xmlMapper,
            final String... headers) {
        try {
            String result = xmlMapper.writeValueAsString(data);
            render(response, XML_TYPE, result, headers);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * JSON.
     * @see #render(javax.servlet.http.HttpServletResponse, String, Object, String...)
     * @param response
     * @param data ? ?List Map
     * @param headers  null UTF-8? 
     * @throws IOException
     */
    public static void renderJson(HttpServletResponse response, Object data, final String... headers) {
        render(response, JSON_TYPE, data, headers);
    }

    /**
     * ?MashupJSONP.
     *
     * @see #render(javax.servlet.http.HttpServletResponse, String, Object, String...)
     * @param response
     * @param data ? ?List Map
     * @param headers  null UTF-8? 
     * @throws IOException
     */
    public static void renderJsonp(final String callbackName, HttpServletResponse response, Object data,
            final String... headers) {
        String result = JsonMapper.nonDefaultMapper().toJsonP(callbackName, data);
        render(response, JSON_TYPE, result, headers);
    }

    /**
     * cookie.
     * @param response
     * @param name
     * @param value
     * @param path
     */
    public static void setCookie(HttpServletResponse response, String name, String value, String path) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cookie '" + name + "',?: '" + path + "'");
        }

        Cookie cookie = new Cookie(name, value);
        cookie.setSecure(false);
        cookie.setPath(path);
        cookie.setMaxAge(2592000);

        response.addCookie(cookie);
    }

    /**
     * ?Cookie.
     * @param request
     * @param name
     * @return
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        Cookie returnCookie = null;

        if (cookies == null) {
            return returnCookie;
        }

        for (Cookie thisCookie : cookies) {
            if (thisCookie.getName().equals(name)) {
                if (!thisCookie.getValue().equals("")) {
                    returnCookie = thisCookie;

                    break;
                }
            }
        }

        return returnCookie;
    }

    /**
     * Cookie.
     * @param response
     * @param cookie
     * @param path
     */
    public static void deleteCookie(HttpServletResponse response, Cookie cookie, String path) {
        if (cookie != null) {
            cookie.setMaxAge(0);
            cookie.setPath(path);
            response.addCookie(cookie);
        }
    }

    public static String getAppURL(HttpServletRequest request) {
        StringBuffer url = new StringBuffer();
        int port = request.getServerPort();
        if (port < 0) {
            port = 80;
        }
        String scheme = request.getScheme();
        url.append(scheme);
        url.append("://");
        url.append(request.getServerName());
        if (((scheme.equals("http")) && (port != 80)) || ((scheme.equals("https")) && (port != 443))) {
            url.append(':');
            url.append(port);
        }
        url.append(request.getContextPath());
        return url.toString();
    }
}