com.dgq.utils.Struts2Utils.java Source code

Java tutorial

Introduction

Here is the source code for com.dgq.utils.Struts2Utils.java

Source

/**
 * Copyright (c) 2005-2009 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: Struts2Utils.java 1005 2010-03-25 15:50:00Z calvinxiu $
 */
package com.dgq.utils;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.map.ObjectMapper;

import com.dgq.utils.ServletUtils;
import com.opensymphony.xwork2.ActionContext;

/**
 * Struts2.
 * 
 * ?Request/Response/Sessionjsp/freemaker.
 * 
 * @author calvin
 */
public class Struts2Utils {

    // -- 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;

    private static ObjectMapper mapper = null;

    public static synchronized ObjectMapper getObjectMapper() {
        if (mapper == null) {
            mapper = new ObjectMapper();
        }

        return mapper;
    }

    /**
     * ?AppContext.
     */
    public static ServletContext getAppContext() {
        return ServletActionContext.getServletContext();
    }

    // -- ?Request/Response/Session --//
    /**
     * ?HttpSession.
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * ?HttpSession.
     */
    public static HttpSession getSession(boolean isNew) {
        return getRequest().getSession(isNew);
    }

    /**
     * ?HttpSessionAttribute.
     */
    public static Object getSessionAttribute(String name) {
        // HttpSession session = getSession(false);
        // return (session != null ? session.getAttribute(name) : null);
        Map<String, Object> session = ActionContext.getContext().getSession();
        return (session != null ? session.get(name) : null);
    }

    /**
     * HttpSessionAttribute,session
     */
    public static void setSessionAttribute(String name, Object obj) {
        Map<String, Object> session = ActionContext.getContext().getSession();
        session.put(name, obj);
    }

    /**
     * ?HttpRequest.
     */
    public static HttpServletRequest getRequest() {
        return ServletActionContext.getRequest();
    }

    /**
     * ?HttpRequestParameter.
     */
    public static String getParameter(String name) {
        return getRequest().getParameter(name);
    }

    /**
     * ?HttpResponse.
     */
    public static HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }

    // -- jsp/freemaker --//
    /**
     * .
     * 
     * 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(final String contentType, final String content, final String... headers) {
        HttpServletResponse response = initResponseHeader(contentType, headers);
        try {
            response.getWriter().write(content);
            response.getWriter().flush();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static void renderServlet(final String contentType, final String content, HttpServletResponse response,
            final String... headers) {
        response = initResponseHeaderServlet(contentType, response, headers);
        try {
            response.getWriter().write(content);
            response.getWriter().flush();
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * .
     * 
     * @see #render(String, String, String...)
     */
    public static void renderText(final String text, final String... headers) {
        render(ServletUtils.TEXT_TYPE, text, headers);
    }

    /**
     * HTML.
     * 
     * @see #render(String, String, String...)
     */
    public static void renderHtml(final String html, final String... headers) {
        render(ServletUtils.HTML_TYPE, html, headers);
    }

    /**
     * XML.
     * 
     * @see #render(String, String, String...)
     */
    public static void renderXml(final String xml, final String... headers) {
        render(ServletUtils.XML_TYPE, xml, headers);
    }

    public static void renderXmlServlet(final String xml, HttpServletResponse response, final String... headers) {
        renderServlet(ServletUtils.XML_TYPE, xml, response, headers);
    }

    /**
     * JSON.
     * 
     * @param jsonString
     *            json.
     * @see #render(String, String, String...)
     */
    public static void renderJson(final String jsonString, final String... headers) {
        render(ServletUtils.JSON_TYPE, jsonString, headers);
    }

    /**
     * JSON,Jackson?Java.
     * 
     * @param data
     *            ?List<POJO>, POJO[], POJO, ?Map??.
     * @see #render(String, String, String...)
     */
    public static void renderJson(final Object data, final String... headers) {
        HttpServletResponse response = initResponseHeader(ServletUtils.JSON_TYPE, headers);
        try {
            getObjectMapper().writeValue(response.getWriter(), data);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    }

    /**
     * ?MashupJSONP.
     * 
     * @param callbackName
     *            callback??.
     * @param object
     *            Java,?List<POJO>, POJO[], POJO ,?Map??, json.
     */
    public static void renderJsonp(final String callbackName, final Object object, final String... headers) {
        String jsonString = null;
        try {
            jsonString = getObjectMapper().writeValueAsString(object);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }

        String result = new StringBuilder().append(callbackName).append("(").append(jsonString).append(");")
                .toString();

        // Content-Typejavascript,javascript?,
        // callback197("{html:'Hello World!!!'}");
        render(ServletUtils.JS_TYPE, result, headers);
    }

    /**
     * ?contentTypeheaders.
     */
    private static HttpServletResponse initResponseHeader(final String contentType, final String... headers) {
        // ?headers?
        String encoding = DEFAULT_ENCODING;
        boolean noCache = DEFAULT_NOCACHE;
        for (String header : headers) {
            String headerName = StringUtils.substringBefore(header, ":");
            String headerValue = 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");
            }
        }

        HttpServletResponse response = getResponse();

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

        return response;
    }

    private static HttpServletResponse initResponseHeaderServlet(final String contentType,
            HttpServletResponse response, final String... headers) {
        // ?headers?
        String encoding = DEFAULT_ENCODING;
        boolean noCache = DEFAULT_NOCACHE;
        for (String header : headers) {
            String headerName = StringUtils.substringBefore(header, ":");
            String headerValue = 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) {
            ServletUtils.setNoCacheHeader(response);
        }

        return response;
    }

}