/*
 * Copyright (C) 2004 TiongHiang Lee
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not,  write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Email: thlee@onemindsoft.org
 */

package org.onemind.commons.java.util;

import java.io.File;
import java.util.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileUpload;
/**
 * The servlet utiltity
 * @author TiongHiang Lee (thlee@onemindsoft.org)
 * @version $Id: ServletUtils.java,v 1.3 2004/10/23 15:27:01 thlee Exp $ $Name:  $
 */
public final class ServletUtils
{

    /**
     * Constructor
     */
    private ServletUtils()
    {
    };

    /**
     * Get the request environment
     * @param req the request
     * @return the environment in a map
     */
    public static Map getRequestEnvironment(HttpServletRequest req)
    {
        Map m = new HashMap();
        m.put("REQUEST", req);
        m.put("REQUEST_AUTH_TYPE", req.getAuthType());
        //m.put("REQUEST_CONTEXT_PATH", req.getContextPath());
        m.put("REQUEST_COOKIES", req.getCookies());
        Enumeration enum = req.getHeaderNames();
        while (enum.hasMoreElements())
        {
            String header = (String) enum.nextElement();
            String value = req.getHeader(header);
            m.put(header, value);
        }
        m.put("REQUEST_METHOD", req.getMethod());
        m.put("PATH_INFO", req.getPathInfo());
        m.put("PATH_TRANSLATED", req.getPathTranslated());
        m.put("QUERY_STRING", req.getQueryString());
        m.put("REMOTE_ADDR", req.getRemoteAddr());
        m.put("REMOTE_HOST", req.getRemoteHost());
        m.put("REMOTE_USER", req.getRemoteUser());
        m.put("REQUESTED_SESSION_ID", req.getRequestedSessionId());
        m.put("REQUEST_URI", req.getRequestURI());
        //m.put("REQUEST_URL", req.getRequestURL());
        m.put("SERVLET_PATH", req.getServletPath());
        m.put("SESSION", req.getSession(true));
        //env
        return m;
    }

    /**
     * Get request attributes (Only for jsdk 2.3)
     * @param req the request
     * @return the servlet attributes
     */
    public static Map getExtraRequestEnvironment(HttpServletRequest req)
    {
        Map m = new HashMap();
        Enumeration enum = req.getAttributeNames();
        while (enum.hasMoreElements())
        {
            String attr = (String) enum.nextElement();
            m.put(attr, req.getAttribute(attr));
        }
        m.put("CHARACTER_ENCODING", req.getCharacterEncoding());
        m.put("CONTENT_LENGTH", new Integer(req.getContentLength()));
        m.put("CONTENT_TYPE", req.getContentType());
        m.put("REQUEST_PROTOCOL", req.getProtocol());
        m.put("REQUEST_SCHEME", req.getScheme());
        m.put("SERVER_NAME", req.getServerName());
        m.put("SERVER_PORT", new Integer(req.getServerPort()));
        return m;
    }

    /**
     * Get the servlet environment from the config
     * @param config the config
     * @return the environment in a map
     */
    public static Map getServletEnvironment(ServletConfig config)
    {
        Map m = new HashMap();
        m.put("SERVLET_CONTEXT", config.getServletContext());
        return m;
    }

    /**
     * Get the request parameters in a mp
     * @param req the request
     * @return the environment in the map
     */
    public static Map getRequestParameters(HttpServletRequest req, DiskFileUpload upload) throws FileUploadException
    {
        Map m = new HashMap();
        if (FileUpload.isMultipartContent(req))
        {
            // Parse the request
            List items = upload.parseRequest(req);
            Iterator iter = items.iterator();
            while (iter.hasNext())
            {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                {
                    m.put(item.getFieldName(), item.getString());
                } else
                {
                    String fieldName = item.getFieldName();
                    m.put(fieldName + ".FILENAME", item.getName()); //file name
                    m.put(fieldName + ".CONTENT_TYPE", item.getContentType());
                    m.put(fieldName + ".ITEM", item);                    
                }
            }
        } else
        {
            Enumeration enum = req.getParameterNames();
            while (enum.hasMoreElements())
            {
                String key = (String) enum.nextElement();
                String[] value = req.getParameterValues(key);
                if (value.length == 0)
                {
                    m.put(key, null);
                } else if (value.length == 1)
                {
                    m.put(key, value[0]);
                } else
                {
                    m.put(key, value);
                }
            }
        }
        return m;
    }
}