//
// CmdTest executes a command as a process with all supplied arguments
// and writes stdout from the process to System.out and stderr from
// process to System.out.
//
import java.io.*;

public class CmdTest
{
  //
  // A StreamReader writes an input stream to an output stream
  //
  static class StreamCopier extends Thread
  {
    private InputStream m_is;
    private OutputStream m_os;

    public StreamCopier(InputStream is, OutputStream os)
    {
      m_is = is;
      m_os = os;
      start();
    }

    public void run()
    {
      try
      {
        byte[] arr = new byte[1024];
        int n = 0;
        while ((n = m_is.read(arr)) >= 0)
          m_os.write(arr, 0, n);
      }
      catch (IOException e)
      {
        System.out.println("*** stream closed ***");
      }
    }
  }

  public static void main(String[] args)
  {
    System.out.print("Executing command:");
    for (int i = 0; i < args.length; ++i)
      System.out.print(" " + args[i]);
    System.out.println();

    try
    {
      Runtime r = Runtime.getRuntime();
      Process p = r.exec(args);

      StreamCopier stdOutReader = new StreamCopier(p.getInputStream(),
                                                   System.out);
      StreamCopier stdErrReader = new StreamCopier(p.getErrorStream(),
                                                   System.err);

      //System.out.print("Waiting for process to terminate...");
      p.waitFor();
      //System.out.println("terminated");
    }
    catch (Exception e)
    {
      System.out.println("Exception " + e.getMessage());
    }
  }
}
