com.founder.fix.fixflow.explorer.util.ResultUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.founder.fix.fixflow.explorer.util.ResultUtils.java

Source

/**
 *  Copyright 1996-2013 Founder International Co.,Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * @author ?
 */
package com.founder.fix.fixflow.explorer.util;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * .
 * 
 * jsp/freemaker.
 * 
 * @author ?
 */
public class ResultUtils {

    // -- 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";
    public static HttpServletResponse response;
    private static ResultUtils instance;

    public static ResultUtils getInstance(HttpServletResponse responseParm) {
        response = responseParm;
        if (instance == null) {
            instance = new ResultUtils();
        }
        return instance;
    }

    private ObjectMapper mapper = new ObjectMapper();

    /**
     * <P>
     * .
     * </p>
     * 
     * @param headers
     *            ??header,??"encoding:""no-cache:",UTF-8true.
     */
    public 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);
        }
    }

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

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

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

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

    /**
     * JSON,Jackson?Java.
     * 
     * @param data
     *            ?List<POJO>, POJO[], POJO, ?Map??.
     * @see #render(String, String, String...)
     */
    public void renderJson(final Object data, final String... headers) {
        HttpServletResponse response = initResponseHeader(ResultUtils.JSON_TYPE, headers);
        try {
            mapper.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 void renderJsonp(final String callbackName, final Object object, final String... headers) {
        String jsonString = null;
        try {
            jsonString = mapper.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(ResultUtils.JS_TYPE, result, headers);
    }

    /**
     * ?Header.
     */
    public 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");
    }

    /**
     * ?contentTypeheaders.
     */
    private 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");
            }
        }

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

        return response;
    }

}