package basics.utl;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

public class StreamUtl extends Object
{
private static byte [] buffer = new byte [2048];

private StreamUtl()
{
   super();
}

public synchronized static int copy(InputStream source, OutputStream destination, boolean autoClose)
{
   int sum = 0;
   try
   {
      int n;
      while((n = source.read(buffer)) >= 0)
      {
         sum += n;
         destination.write(buffer, 0, n);
      }
   }
   catch(Exception e)
   {
      sum = (sum == 0) ? Integer.MIN_VALUE : -sum;
   }
   finally
   {
      if(autoClose)
      {
         close(source);
         close(destination);
      }
   }
   return sum;
}

public static synchronized byte [] getBytes(InputStream stream, boolean autoClose)
   throws IOException
{
   int length = buffer.length;
   byte [] result = new byte [length];
   try
   {
      int offset = 0;
      int n;
      while((n = stream.read(buffer)) >= 0)
      {
         if(length < offset + n)
         {
            while(length < offset + n)
               length <<= 1;
            byte [] buffer = new byte [length];
            System.arraycopy(result, 0, buffer, 0, offset);
            result = buffer;
            buffer = null; // GC
         }
         System.arraycopy(buffer, 0, result, offset, n);
         offset += n;
      }
      if(offset < length)
      {
         byte [] buffer = new byte [offset];
         System.arraycopy(result, 0, buffer, 0, offset);
         result = buffer;
         buffer = null; // GC
      }
      return result;
   }
   finally
   {
      if(autoClose)
         StreamUtl.close(stream);
   }
}

public static String getContent(InputStream stream, boolean autoClose) throws IOException
{
   return new String(getBytes(stream, autoClose));
}

public static void close(InputStream inputStream)
{
   try
   {
      if(inputStream != null)
         inputStream.close();
   }
   catch(IOException e)
   {
      // Keine Aktion ntig
   }
}

public static void close(OutputStream outputStream)
{
   try
   {
      if(outputStream != null)
         outputStream.close();
   }
   catch(IOException e)
   {
   }
}

public static void close(Reader reader)
{
   try
   {
      if(reader != null)
         reader.close();
   }
   catch(IOException e)
   {
   }
}

public static void close(Writer writer)
{
   try
   {
      if(writer != null)
         writer.close();
   }
   catch(IOException e)
   {
   }
}

public static InputStream toInputStream(String input)
{
   return new ByteArrayInputStream(input.getBytes());
}
}
