org.jxstar.control.action.ActionHelper.java Source code

Java tutorial

Introduction

Here is the source code for org.jxstar.control.action.ActionHelper.java

Source

/*
 * ActionHelper.java 2009-5-28
 * 
 * Copyright 2010 Guangzhou Donghong Software Technology Inc.
 * Licensed under the www.jxstar.org
 */
package org.jxstar.control.action;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.fileupload.DefaultFileItemFactory;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.jxstar.util.config.SystemVar;
import org.jxstar.util.factory.FactoryUtil;
import org.jxstar.util.log.Log;
import org.jxstar.util.resource.JsMessage;
import org.jxstar.util.resource.JsParam;

/**
 * ActionHttpServletRequest?RequestContext
 * ????
 * multipart???????gbk??utf-8
 * TOMCAT?????
 *
 * @author TonyTan
 * @version 1.0, 2009-5-28
 */
@SuppressWarnings({ "unchecked", "deprecation" })
public class ActionHelper {
    private static final Log _log = Log.getInstance();

    /**
     * RequestContext?HttpServletRequest?
     * ?[sys.realpath]IP?[sys.realpath]
     * @param request
     * @return
     */
    public static RequestContext getRequestContext(HttpServletRequest request) throws ActionException {
        Map<String, Object> requestMap;
        boolean isMultipart = DiskFileUpload.isMultipartContent(request);
        _log.showDebug("request is have file upload: " + isMultipart);
        if (isMultipart) {
            requestMap = parseMultiRequest(request);
        } else {
            requestMap = parseRequestParam(request);
        }
        _log.showDebug("------------request param=" + requestMap.toString());
        //?
        requestMap.put(JsParam.REALPATH, SystemVar.REALPATH);

        //?
        RequestContext requestContext = new RequestContext(requestMap);
        //?Map<String,String>???client_ip?session_id
        requestContext.setClientInfo(getClientInfo(request));

        //?ID?Context
        String funid = requestContext.getRequestValue(JsParam.FUNID);
        requestContext.setFunID(funid);

        //??
        String pageType = requestContext.getRequestValue(JsParam.PAGETYPE);
        requestContext.setPageType(pageType);

        //?eventCode????eventCode
        String eventCode = requestContext.getRequestValue(JsParam.EVENTCODE);
        requestContext.setEventCode(eventCode);

        return requestContext;
    }

    private static Map<String, Object> parseRequestParam(HttpServletRequest request) throws ActionException {
        Map<String, Object> requestMap = FactoryUtil.newMap();
        Enumeration<String> paramNames = request.getParameterNames();

        //?map
        while (paramNames.hasMoreElements()) {
            String name = paramNames.nextElement();
            String[] value = request.getParameterValues(name);

            //??__?.??
            name = name.replace("__", ".");
            if (value == null) {
                requestMap.put(name, "");
            } else if (value.length == 1) {
                requestMap.put(name, value[0]);
            } else {
                requestMap.put(name, value);
            }
        }

        return requestMap;
    }

    /**
     * ?
     * @param request
     * @return
     */
    private static Map<String, Object> parseMultiRequest(HttpServletRequest request) throws ActionException {
        //?
        DefaultFileItemFactory factory = new DefaultFileItemFactory();
        //?
        DiskFileUpload upload = new DiskFileUpload(factory);
        //????
        upload.setHeaderEncoding("utf-8");
        //?10M
        String maxSize = SystemVar.getValue("upload.file.maxsize", "10");
        upload.setSizeMax(1000 * 1000 * Integer.parseInt(maxSize));
        //?
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            _log.showError(e);
            throw new ActionException(JsMessage.getValue("fileaction.overmaxsize"), maxSize);
        }
        _log.showDebug("request item size=" + items.size());

        //
        Map<String, Object> requestMap = FactoryUtil.newMap();
        // ?
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                String key = item.getFieldName();
                //?????
                String value = "";
                try {
                    value = item.getString("utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if (key == null || key.length() == 0)
                    continue;
                requestMap.put(key, value);
            } else {
                String key = item.getFieldName();
                requestMap.put(key, item);
                //??
                String fileName = item.getName();
                String contentType = item.getContentType();
                long fileSize = item.getSize();
                _log.showDebug(
                        "request filename=" + fileName + ";fileSize=" + fileSize + ";contentType=" + contentType);
            }
        }

        return requestMap;
    }

    /**
     * ?
     * @param request
     */
    private static Map<String, String> getClientInfo(HttpServletRequest request) {
        Map<String, String> mpInfo = FactoryUtil.newMap();

        //??ID
        HttpSession session = request.getSession();
        mpInfo.put("session_id", session.getId());
        //??
        mpInfo.put("client_ip", request.getRemoteAddr());

        //??
        @SuppressWarnings("rawtypes")
        Enumeration em = request.getHeaderNames();
        while (em.hasMoreElements()) {
            String name = (String) em.nextElement();
            String value = request.getHeader(name);
            mpInfo.put(name.toLowerCase(), value);
        }

        return mpInfo;
    }

    /**
     * ????
     * 
     * @param request - 
     * @param response - ?
     */
    public static void contextToResponse(RequestContext request, ResponseContext response) {
        if (request == null)
            return;
        if (response == null)
            return;

        response.setMessage(request.getMessage());
        response.setResponseData(request.getReturnData());
    }

    /**
     * ??????
     * @param userAgent -- ?
     * @param fileName -- ??
     * @return
     */
    public static String getAttachName(String userAgent, String fileName) {
        if (userAgent == null || fileName == null) {
            return fileName;
        }

        userAgent = userAgent.toLowerCase();
        try {
            if (userAgent.indexOf("msie") > -1) {
                fileName = URLEncoder.encode(fileName, "utf-8");
            } else {
                fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
                fileName = "\"" + fileName + "\"";
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return fileName;
    }
}