/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.remoting.marshal.http;

import org.jboss.logging.Logger;
import org.jboss.remoting.marshal.serializable.SerializableUnMarshaller;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StreamCorruptedException;
import java.util.Map;

/**
 * @author <a href="mailto:telrod@e2technologies.net">Tom Elrod</a>
 */
public class HTTPUnMarshaller extends SerializableUnMarshaller
{
   public final static String DATATYPE = "http";

   protected final Logger log = Logger.getLogger(getClass());

   /**
    * Will try to unmarshall data from inputstream.  Will try to convert to either an object
    * or a string.  If there is no data to read, will return null.
    *
    * @param inputStream
    * @return
    * @throws IOException
    * @throws ClassNotFoundException
    */
   public Object read(InputStream inputStream, Map metadata) throws IOException, ClassNotFoundException
   {
      Object ret = null;
      int bufferSize = 1024;
      byte[] byteBuffer = new byte[bufferSize];
      ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();

      int pointer = 0;
      int amtRead = inputStream.read(byteBuffer);
      while(amtRead > 0)
      {
         byteOutputStream.write(byteBuffer, pointer, amtRead);
         if(amtRead < bufferSize)
         {
            //done reading, so process
            break;
         }
         amtRead = inputStream.read(byteBuffer);
      }

      byteOutputStream.flush();

      byte[] totalByteArray = byteOutputStream.toByteArray();

      if(totalByteArray.length == 0)
      {
         //nothing to read, so is null
         return null;
      }

      try
      {
         return super.read(new ByteArrayInputStream(totalByteArray), metadata);
      }
      catch(StreamCorruptedException sce)
      {

         try
         {

            BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(totalByteArray)));
            StringBuffer buffer = new StringBuffer();
            String str = null;
            while((str = reader.readLine()) != null)
            {
               buffer.append(str);
            }
            reader.close();

            ret = buffer.toString();

         }
         catch(Exception e)
         {
            log.error("Can not unmarshall inputstream.  Tried to unmarshall as both an object and string type.", e);
            throw new IOException("Can not unmarshall inputstream.");
         }
      }
      return ret;

   }

}