/*
 * The contents of this file are subject to the Mozilla Public License Version 1.1
 * (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.mozilla.org/MPL/>.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
 * WARRANTY OF ANY KIND, either express or implied. See the License for the specific
 * language governing rights and limitations under the License.
 * 
 * The Original Code is the Venice Web Communities System.
 * 
 * The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
 * for Silverwrist Design Studios.  Portions created by Eric J. Bowersox are
 * Copyright (C) 2002-03 Eric J. Bowersox/Silverwrist Design Studios.  All Rights Reserved.
 * 
 * Contributor(s): 
 */
package com.silverwrist.dynamo.servlet;

import java.io.*;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.*;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.log4j.Logger;
import com.silverwrist.util.*;
import com.silverwrist.dynamo.Verb;
import com.silverwrist.dynamo.except.*;
import com.silverwrist.dynamo.iface.*;

/**
 * The {@link com.silverwrist.dynamo.iface.Request Request} implementation for all HTTP POST requests
 * with a MIME type of <CODE>multipart/form-data</CODE>, which allows file uploads.  The individual files
 * are separated and made available as {@link com.silverwrist.dynamo.iface.DataItem DataItem} objects.
 * <P>This class uses the JavaMail MIME parser to separate out the individual file entries.  A future
 * version may use the Jakarta Commons Upload component for this purpose.
 *
 * @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
 * @version X
 */
class FileUploadRequestImpl extends RequestImplBase
{
  /*--------------------------------------------------------------------------------
   * Internal implementatiuon of DataItem
   *--------------------------------------------------------------------------------
   */

  private static class FileDataItem implements DataItem, Blob
  {
    /*====================================================================
     * Attributes
     *====================================================================
     */

    private String m_filename;   // file name of the data item
    private String m_type;       // MIME type of the data item
    private int m_size;          // size of the data item
    private byte[] m_data;       // the data itself

    /*====================================================================
     * Constructor
     *====================================================================
     */

    FileDataItem(String filename, MimeBodyPart part) throws MessagingException, IOException
    {
      m_filename = filename;
      m_type = part.getContentType();
      m_size = part.getSize();
      m_data = IOUtils.load(part.getInputStream());

    } // end constructor

    /*====================================================================
     * Implementations from interface DataItem
     *====================================================================
     */

    public String getName()
    {
      return m_filename;

    } // end getName

    public String getMimeType()
    {
      return m_type;

    } // end getMimeType

    public int getSize()
    {
      return m_size;

    } // end getSize

    public InputStream getDataStream() throws IOException
    {
      return new ByteArrayInputStream(m_data);

    } // end getDataStream

    public Blob getBlob() throws SQLException
    {
      return this;

    } // end getBlob

    /*====================================================================
     * Implementations from interface Blob
     *====================================================================
     */

    public long length()
    {
      return (long)m_size;

    } // end length

    public byte[] getBytes(long pos, int length) throws SQLException
    {
      int real_length = Math.min(length,(int)(m_data.length - pos));
      byte[] rc = new byte[real_length];
      System.arraycopy(m_data,(int)pos,rc,0,real_length);
      return rc;

    } // end getBytes

    public InputStream getBinaryStream() throws SQLException
    {
      return new ByteArrayInputStream(m_data);

    } // end getBinaryStream

    public long position(byte[] pattern, long start) throws SQLException
    {
      throw new SQLException("method not implemented");

    } // end position

    public long position(Blob pattern, long start) throws SQLException
    {
      return position(pattern.getBytes(0,(int)(pattern.length())),start);

    } // end position

    public int setBytes(long pos, byte[] bytes) throws SQLException
    {
      throw new SQLException("read-only Blob value");

    } // end setBytes

    public int setBytes(long pos, byte[] bytes, int offset, int len) throws SQLException
    {
      throw new SQLException("read-only Blob value");

    } // end setBytes

    public OutputStream setBinaryStream(long pos) throws SQLException
    {
      throw new SQLException("read-only Blob value");

    } // end setBinaryStream

    public void truncate(long len) throws SQLException
    {
      throw new SQLException("read-only Blob value");

    } // end truncate

  } // end class FileDataItem

  /*--------------------------------------------------------------------------------
   * Internal wrapper around the ServletRequest that implements DataSource
   *--------------------------------------------------------------------------------
   */

  private static class ServletDataSource implements DataSource
  {
    /*====================================================================
     * Attributes
     *====================================================================
     */

    private ServletRequest m_request;     // the servlet request
    private InputStream m_istm = null;    // the data stream coming from the request

    /*====================================================================
     * Constructor
     *====================================================================
     */

    ServletDataSource(ServletRequest request)
    {
      m_request = request;

    } // end constructor

    /*====================================================================
     * Implementations from interface DataSource
     *====================================================================
     */

    public InputStream getInputStream() throws IOException
    {
      if (m_istm==null)
	m_istm = m_request.getInputStream();
      return m_istm;

    } // end getInputStream

    public OutputStream getOutputStream() throws IOException
    {
      throw new IOException("tried to get OutputStream on servlet input?!?!?");

    } // end getOutputStream

    public String getContentType()
    {
      return m_request.getContentType();

    } // end getContentType

    public String getName()
    {
      return "servlet";

    } // end getName

  } // end class ServletDataSource

  /*--------------------------------------------------------------------------------
   * Static data members
   *--------------------------------------------------------------------------------
   */

  private static Logger logger = Logger.getLogger(FileUploadRequestImpl.class);

  private static final String[] TEXT_PROTO = new String[0];
  private static final DataItem[] DATA_PROTO = new DataItem[0];

  // class of String[] - that's the values in getParameterMap
  private static Class s_parameter_class = TEXT_PROTO.getClass();

  /*--------------------------------------------------------------------------------
   * Attributes
   *--------------------------------------------------------------------------------
   */

  private Map m_text_map;    // map of all text parameters
  private Map m_data_map;    // map of all data item parameters

  /*--------------------------------------------------------------------------------
   * Constructor
   *--------------------------------------------------------------------------------
   */

  /**
   * Creates a new <CODE>FileUploadRequestImpl</CODE>.
   *
   * @param req The original <CODE>HttpServletRequest</CODE> passed to the servlet.
   * @param verb The verb associated with this request.
   * @param services A {@link com.silverwrist.dynamo.iface.ServiceProvider ServiceProvider} object controlling
   *                 access to request services.
   * @param prev The previous {@link com.silverwrist.dynamo.iface.Request Request} object.  May be <CODE>null</CODE>.
   * @exception com.silverwrist.dynamo.except.RequestParseException If there was an error in parsing the HTTP
   *            request.
   */
  FileUploadRequestImpl(HttpServletRequest req, Verb verb, ServiceProvider services, Request prev)
      throws RequestParseException
  {
    super(req,verb,services,prev);
    try
    { // parse the request body
      MimeMultipart multipart = new MimeMultipart(new ServletDataSource(req));
      int count = multipart.getCount();
      if (logger.isDebugEnabled())
	logger.debug("retrieved " + count + " parameter(s) from request");

      // allocate initial maps for storing raw data
      HashMap text_map = new HashMap();
      HashMap data_map = new HashMap();
      for (int i=0; i<count; i++)
      { // start by identifying the Content-Disposition of the part
	MimeBodyPart part = (MimeBodyPart)(multipart.getBodyPart(i));
	String[] cdstr = part.getHeader("Content-Disposition");
	ContentDisposition cdisp = new ContentDisposition(cdstr[0]);
	String name = cdisp.getParameter("name");
	String filename = cdisp.getParameter("filename");

	if (filename!=null)
	{ // Windows boxes pass the filename complete with the backslashed pathname on the
	  // front, and, for some reason, ContentDisposition strips out the backslashes while
	  // leaving the pathname components in place (including the drive letter!).  So we
	  // have to go to manual here to extract the filename ourselves.
	  int pos = cdstr[0].indexOf("filename");
	  pos += 8;
	  while ((cdstr[0].charAt(pos)==' ') || (cdstr[0].charAt(pos)=='\t'))
	    pos++;
	  if (cdstr[0].charAt(pos)!='=')
	    throw new RequestParseException("Content-Disposition must have = sign after filename");
	  pos++;
	  while ((cdstr[0].charAt(pos)==' ') || (cdstr[0].charAt(pos)=='\t'))
	    pos++;
	  if ((cdstr[0].charAt(pos)=='\'') || (cdstr[0].charAt(pos)=='"'))
	  { // filename enclosed in quotes...
	    char match = cdstr[0].charAt(pos++);
	    filename = cdstr[0].substring(pos);
	    pos = filename.lastIndexOf(match);
	    if (pos<0)
	      throw new RequestParseException("Content-Disposition filename= parameter must "
					      + "have closing quote");
	    filename = filename.substring(0,pos);

	  } // end if
	  else
	  { // no quotes, just take the rest of the line
	    filename = cdstr[0].substring(pos);
	    pos = filename.lastIndexOf(';');
	    if (pos>=0)
	      filename = filename.substring(0,pos);

	  } // end else

	  if (logger.isDebugEnabled())
	    logger.debug("Raw filename: " + filename);

	  // Strip off everything but the base filename, if the browser happened to pass that.
	  pos = filename.lastIndexOf('\\');
	  if (pos>=0)
	    filename = filename.substring(pos+1);
	  pos = filename.lastIndexOf('/');
	  if (pos>=0)
	    filename = filename.substring(pos+1);

	  // Create the DataItem and add it to the hashmap of arrays we're generating.
	  DataItem item = new FileDataItem(filename,part);
	  ArrayList al = (ArrayList)(data_map.get(name));
	  if (al==null)
	  { // create initial ArrayList
	    al = new ArrayList();
	    data_map.put(name,al);

	  } // end if

	  al.add(item);

	} // end if (file parameter)
	else
	{ // this is an ordinary text value - process it accordingly
	  String value = part.getContent().toString();
	  ArrayList al = (ArrayList)(text_map.get(name));
	  if (al==null)
	  { // create initial ArrayList
	    al = new ArrayList();
	    text_map.put(name,al);

	  } // end if

	  al.add(value);

	} // end else (ordinary text value)

      } // end for

      if (!(text_map.isEmpty()))
      { // convert ArrayLists to actual arrays
	HashMap tmp = new HashMap();
	Iterator it = text_map.keySet().iterator();
	while (it.hasNext())
	{ // convert each ArrayList entry to an array and store it
	  String name = (String)(it.next());
	  ArrayList al = (ArrayList)(text_map.get(name));
	  tmp.put(name,al.toArray(TEXT_PROTO));

	} // end while

	m_text_map = Collections.unmodifiableMap(tmp);

      } // end if
      else // this is an empty map
	m_text_map = Collections.EMPTY_MAP;

      if (!(data_map.isEmpty()))
      { // convert ArrayLists to actual arrays
	HashMap tmp = new HashMap();
	Iterator it = data_map.keySet().iterator();
	while (it.hasNext())
	{ // convert each ArrayList entry to an array and store it
	  String name = (String)(it.next());
	  ArrayList al = (ArrayList)(data_map.get(name));
	  tmp.put(name,al.toArray(DATA_PROTO));

	} // end while

	m_data_map = Collections.unmodifiableMap(tmp);

      } // end if
      else // this is an empty map
	m_data_map = Collections.EMPTY_MAP;

    } // end try
    catch (MessagingException me)
    { // translate a MessagingException...
      logger.error("multipart request parse failed",me);
      throw new RequestParseException(me.getMessage(),me);

    } // end catch
    catch (IOException ioe)
    { // IO error schlepping data around - bail out
      logger.error("multipart request parse failed",ioe);
      throw new RequestParseException("IO error: " + ioe.getMessage(),ioe);

    } // end catch

  } // end constructor

  /*--------------------------------------------------------------------------------
   * Overrides from class Object
   *--------------------------------------------------------------------------------
   */

  /**
   * Returns a string representation of the object. In general, the <CODE>toString</CODE> method returns a string
   * that "textually represents" this object. 
   *
   * @return A string representation of the object.
   */
  public String toString()
  {
    return "FileUploadRequestImpl from address [" + getSourceAddress() + "]";

  } // end toString

  /*--------------------------------------------------------------------------------
   * Abstract implementations from class RequestImplBase
   *--------------------------------------------------------------------------------
   */

  /**
   * Returns a java.util.Map of the parameters of this request. Request parameters are extra information sent with
   * the request.  For HTTP requests, these parameters are passed in the query string or POST data.
   * <P>The keys of the map are <CODE>String</CODE> objects; the values of the map are arrays of the type specified
   * by the return value of {@link #getParametersEntryClass() getParametersEntryClass()}.
   *
   * @return The parameter map, as specified above.  This map is read-only.
   */
  public Map getParameters()
  {
    return m_text_map;

  } // end getParameters

  /**
   * Returns a class specifying the fundamental type of objects contained in the arrays acting as the values of
   * the map returned by {@link #getParameters() getParameters()}.  This class may be <CODE>Object</CODE>, indicating
   * that the contained objects may be of any type.
   *
   * @return The class of array elements within the parameter map.
   */
  public Class getParametersEntryClass()
  {
    return s_parameter_class;

  } // end getParametersEntryClass

  /**
   * Returns a java.util.Map of the data items of this request.  Data items are lengthy streams of data associated
   * with a request.  HTTP requests with verbs GET or DELETE have no data items associated
   * with them.  HTTP PUT requests have one data item, named "_body", which contains the data in the body of the
   * request.  HTTP POST requests, if they were sent with MIME type "multpart/form-data", may have one or more 
   * data items, with a variety of names.
   * <P>The keys of the map are <CODE>String</CODE> objects; the values of the map are arrays of
   * {@link com.silverwrist.dynamo.iface.DataItem DataItem} objects.
   *
   * @return The data item map, as specified above.  This map is read-only.
   */
  public Map getDataItems()
  {
    return m_data_map;

  } // end getDataItems

} // end class FileUploadRequestImpl
