com.sunway.cbm.util.web.ServletUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.sunway.cbm.util.web.ServletUtils.java

Source

/**
 * Copyright (c) 2005-2011 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: ServletUtils.java 1595 2011-05-11 16:41:16Z calvinxiu $
 */
package com.sunway.cbm.util.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;

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

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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * HttpServlet.
 * 
 * @author calvin
 */

public abstract class ServletUtils {

    private static final Logger logger = LoggerFactory.getLogger(ServletUtils.class);

    // -- 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
        response.setDateHeader("Expires", System.currentTimeMillis() + expiresSeconds * 1000);
        // Http 1.1 header
        response.setHeader("Cache-Control", "private, max-age=" + expiresSeconds);
    }

    /**
     * ?Header.
     */
    public static void setDisableCacheHeader(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.
     * 
     * Parameter???.
     */
    public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {
        AssertUtils.notNull(request, "Request must not be null");
        Enumeration<?> paramNames = request.getParameterNames();
        Map<String, Object> params = new TreeMap<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 " + EncodeUtils.encodeBase64(encode.getBytes());
    }

    /**
     * ?json
     * 
     * @param response
     * @param object
     */
    public static void responseJson(HttpServletResponse response, Object object) {
        // JsonMapper jsonMapper = JsonMapper.buildNormalMapper();
        // String jsonStr = jsonMapper.toJson(object);
        String jsonStr = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss", features);
        try {
            response.setContentType("text/plain");
            response.getWriter().write(jsonStr);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        logger.debug(jsonStr);
    }

    private static final SerializerFeature[] features = { SerializerFeature.WriteMapNullValue, // 
            SerializerFeature.WriteNullListAsEmpty, // listnull[]?null
            SerializerFeature.WriteNullNumberAsZero, // null0?null
            SerializerFeature.WriteNullBooleanAsFalse, // Booleannullfalse?null
            SerializerFeature.WriteNullStringAsEmpty // null""?null
    };

    /**
     * ?
     * 
     * @param response
     * @param object
     */
    public static void responseText(HttpServletResponse response, String text) {
        try {
            response.getWriter().write(text);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {

        }
    }

    /**
     * ?xml?
     * 
     * @param response
     * @param object
     */
    public static void responseXml(HttpServletResponse response, String xml) {
        try {
            response.setContentType("text/xml");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(xml);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            logger.debug(e.toString());
        }
    }

    public static String getStringParameter(HttpServletRequest request, String name) {
        return request.getParameter(name);
    }

    public static Integer getIntegerParameter(HttpServletRequest request, String name) {
        String value = getStringParameter(request, name);
        if (StringUtils.isNumeric(value))
            return new Integer(value);
        else
            return null;
    }

    public static Boolean getBooleanParameter(HttpServletRequest request, String name) {
        String value = getStringParameter(request, name);

        if (StringUtils.isNotBlank(value))
            return Boolean.parseBoolean(value);
        else
            return Boolean.FALSE;
    }

    public static Date getDateTimeParameter(HttpServletRequest request, String name) {
        String value = getStringParameter(request, name);
        try {
            if (StringUtils.isNotBlank(value))
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date getDateParameter(HttpServletRequest request, String name) {
        String value = getStringParameter(request, name);
        try {
            if (StringUtils.isNotBlank(value))
                return new SimpleDateFormat("yyyy-MM-dd").parse(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * ?Request Parameter.
     */
    public static List<String> getListParameter(HttpServletRequest request, String name) {
        String[] values = request.getParameterValues(name);
        return values == null ? Collections.emptyList() : Arrays.asList(values);
    }
}