/*
 * 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 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.servlet.*;
import javax.servlet.http.*;
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 "standard" HTTP requests.
 *
 * @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
 * @version X
 */
class NormalRequestImpl extends RequestImplBase
{
  /*--------------------------------------------------------------------------------
   * Internal class implementing DataItem for the entire request body
   *--------------------------------------------------------------------------------
   */

  private class BodyDataItem implements DataItem, Blob
  {
    /*====================================================================
     * Attributes
     *====================================================================
     */

    private byte[] m_data;

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

    BodyDataItem() throws IOException
    {
      m_data = IOUtils.load(m_req.getInputStream());

    } // end constructor

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

    public String getName()
    {
      return "STDIN";

    } // end getName

    public String getMimeType()
    {
      return m_req.getContentType();

    } // end getMimeType

    public int getSize()
    {
      return m_req.getContentLength();

    } // 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_req.getContentLength());

    } // 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 BodyDataItem

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

  private static Class s_parameter_class;  // class of String[] - that's the values in getParameterMap

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

  private Map m_data_map;   // data map for output

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

  /**
   * Creates a new <CODE>NormalRequestImpl</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.
   */
  NormalRequestImpl(HttpServletRequest req, Verb verb, ServiceProvider services, Request prev)
      throws RequestParseException
  {
    super(req,verb,services,prev);
    if (Verb.PUT.equals(verb))
    { // create an array of a single DataItem and a map pointing to it
      try
      { // create the entry
	DataItem[] val = new DataItem[1];
	val[0] = new BodyDataItem();
	m_data_map = Collections.singletonMap("_body",val);

      } // end try
      catch (IOException e)
      { // throw RequestParseException
	throw new RequestParseException("IO error: " + e.getMessage(),e);

      } // end catch

    } // end if
    else  // no data values
      m_data_map = Collections.EMPTY_MAP;

  } // end constructor
  
  /*--------------------------------------------------------------------------------
   * Overrides from class Object
   *--------------------------------------------------------------------------------
   */

  /**
   * Returns a string equivalent of this object, for debugging purposes.
   *
   * @return A string equivalent of this object, for debugging purposes.
   */
  public String toString()
  {
    return "NormalRequestImpl 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_req.getParameterMap();

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

  /*--------------------------------------------------------------------------------
   * Static initializer
   *--------------------------------------------------------------------------------
   */

  static
  {
    String[] tmp = new String[0];
    s_parameter_class = tmp.getClass();

  } // end static initializer

} // end class NormalRequestImpl
