org.itboys.commons.utils.servlet.Servlets.java Source code

Java tutorial

Introduction

Here is the source code for org.itboys.commons.utils.servlet.Servlets.java

Source

/**
 * Copyright (c) 2005-2012 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.itboys.commons.utils.servlet;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

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

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.encode.Encodes;

/**
 * HttpServlet.
 */
public class Servlets {

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

    //-- 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, set a fix expires date.
        response.setDateHeader("Expires", System.currentTimeMillis() + expiresSeconds * 1000);
        //Http 1.1 header, set a time after now.
        response.setHeader("Cache-Control", "private, 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, ?.
     * 
     * , 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?.
     * 
     * 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;
    }

    /**
     * ??Header.
     * 
     * @param fileName ???.
     */
    public static void setFileDownloadHeader(HttpServletResponse response, String fileName) {
        try {
            //???
            String encodedfileName = new String(fileName.getBytes(), "ISO8859-1");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
        } catch (UnsupportedEncodingException e) {
        }
    }

    /**
     * ???Request Parameters, copy from spring.
     * 
     * Parameter???.
     * 
     * m2
     */
    @SuppressWarnings({ "rawtypes" })
    public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {
        Validate.notNull(request, "Request must not be null");
        Enumeration paramNames = request.getParameterNames();
        Map<String, Object> params = new HashMap<String, Object>();
        if (prefix == null) {
            prefix = "";
        }
        while (paramNames != null && paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            if ("".equals(prefix) || paramName.startsWith(prefix)) {
                String unprefixed = paramName.substring(prefix.length());
                String[] values = request.getParameterValues(paramName);
                if (values == null || values.length == 0) {
                    // Do nothing, no values found at all.
                } else if (values.length > 1) {
                    params.put(unprefixed, values);
                } else {
                    params.put(unprefixed, values[0]);
                }
            }
        }
        return params;
    }

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

    /**  
     * request??Map  
     * charset
     * @param request
     * @return Map<String, String>
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map<String, String> genMapByRequestParas(HttpServletRequest request, String charset) {
        Map<String, String> params = new HashMap<String, String>();
        Map requestMap = request.getParameterMap();
        Set<Object> set = requestMap.keySet();
        for (Iterator<Object> iter = set.iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestMap.get(name);
            String valueStr = StringUtils.EMPTY;
            for (int i = 0; i < values.length; i++) { //? ?
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            if (StringUtils.isBlank(charset)) {
                params.put(name, valueStr);
            } else {
                try {
                    valueStr = StringUtils.isNotBlank(valueStr)
                            ? new String(valueStr.getBytes(CommonConstants.ENCODE.ISO_8859_1), charset)
                            : valueStr;//???????
                    params.put(name, valueStr);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return params;
    }

    /**  
     * request??Map  
     * charset
     * @param request
     * @return Map<String, String>
     */
    public static Map<String, String> genMapByRequestParas(HttpServletRequest request) {
        return genMapByRequestParas(request, null);
    }
}