
import java.util.logging.Logger;
import java.util.*;
import java.io.*;


class StreamGobbler extends Thread
{
   public static final Logger LOGGER = Logger.getLogger("StreamGobbler");

   InputStream is;
   String type;
   OutputStream os;

   StreamGobbler(InputStream is, String type)
   {
      this(is, type, null);
   }

   StreamGobbler(InputStream is, String type, OutputStream redirect)
   {
      this.is = is;
      this.type = type;
      this.os = redirect;
   }


   public void run()
   {
      try
      {
         BufferedOutputStream bos = null;
         if(os != null)
            bos = new BufferedOutputStream(os);

         BufferedInputStream bis = new BufferedInputStream(is);

         byte[] buffer = new byte[2048];
         int nread = 0;
         while ( (nread = bis.read(buffer)) != -1)
         {
            if (bos != null)
            {
               bos.write(buffer, 0, nread);
            }
            else
            {
               LOGGER.info(type + ">" + new String(buffer, 0, nread, "utf-8"));
            }
         }

         if(bos !=null)
            bos.flush();

      } catch (IOException ioe)
      {
         ioe.printStackTrace();  
      }
   }
}


class ExecCmd
{
   public static final Logger LOGGER = Logger.getLogger("ExecCmd");

   public int exitValue;

   public void doRun(OutputStream outputStream, String[] cmd)
      throws IOException, InterruptedException
   {
      // Assert outputStream != null

      LOGGER.info("CMD: " + Arrays.toString(cmd));

      Runtime rt = Runtime.getRuntime();
      Process proc = rt.exec(cmd);

      // any error message?
      StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");

      // any output?
      StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT", outputStream);

      // kick them off
      outputGobbler.start();
      errorGobbler.start();

      outputGobbler.join();
      errorGobbler.join();

      exitValue = proc.waitFor();

      outputStream.flush();
   }


}

