com.yxw.framework.mvc.controller.Servlets.java Source code

Java tutorial

Introduction

Here is the source code for com.yxw.framework.mvc.controller.Servlets.java

Source

/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.yxw.framework.mvc.controller;

import java.util.Enumeration;
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.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;
import com.google.common.net.HttpHeaders;
import com.yxw.framework.utils.EncodeUtils;

/**
 * HttpServlet.
 * 
 * @author calvin
 */
public class Servlets {
    private static Logger logger = LoggerFactory.getLogger(Servlets.class);

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

    public static final String APPLICATION_XML = "application/xml";
    public static final String APPLICATION_XML_UTF_8 = "application/xml;charset=UTF-8";

    public static final String JSON = "application/json";
    public static final String JSON_UTF_8 = "application/json;charset=UTF-8";

    public static final String JAVASCRIPT = "application/javascript";
    public static final String JAVASCRIPT_UTF_8 = "application/javascript;charset=UTF-8";

    public static final String APPLICATION_XHTML_XML = "application/xhtml+xml";
    public static final String APPLICATION_XHTML_XML_UTF_8 = "application/xhtml+xml;charset=UTF-8";

    public static final String TEXT_PLAIN = "text/plain";
    public static final String TEXT_PLAIN_UTF_8 = "text/plain;charset=UTF-8";

    public static final String TEXT_XML = "text/xml";
    public static final String TEXT_XML_UTF_8 = "text/xml;charset=UTF-8";

    public static final String TEXT_HTML = "text/html";
    public static final String TEXT_HTML_UTF_8 = "text/html;charset=UTF-8";

    /**
     *  Header.
     */
    public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) {
        // Http 1.0 header, set a fix expires date.
        response.setDateHeader(HttpHeaders.EXPIRES, System.currentTimeMillis() + (expiresSeconds * 1000));
        // Http 1.1 header, set a time after now.
        response.setHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=" + expiresSeconds);
    }

    /**
     * ?Header.
     */
    public static void setNoCacheHeader(HttpServletResponse response) {
        // Http 1.0 header
        response.setDateHeader(HttpHeaders.EXPIRES, 1L);
        response.addHeader(HttpHeaders.PRAGMA, "no-cache");
        // Http 1.1 header
        response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0");
    }

    /**
     * LastModified Header.
     */
    public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) {
        response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModifiedDate);
    }

    /**
     * Etag Header.
     */
    public static void setEtag(HttpServletResponse response, String etag) {
        response.setHeader(HttpHeaders.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(HttpHeaders.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(HttpHeaders.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(HttpHeaders.ETAG, etag);
                return false;
            }
        }
        return true;
    }

    /**
     * ??Header.
     * 
     * @param fileName
     *            ???.
     */
    public static void setFileDownloadHeader(HttpServletResponse response, String fileName) {
        // ???
        String encodedfileName = new String(fileName.getBytes(), Charsets.ISO_8859_1);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");

    }

    /**
     * ???Request Parameters, copy from spring WebUtils.
     * 
     * Parameter???.
     */
    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 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.
                    logger.error("(values == null) || (values.length == 0");
                } 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());
    }
}