00001 package net.threebit.utils.sosc;
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 import com.oreilly.servlet.*;
00023 import java.io.*;
00024 import java.sql.*;
00025 import java.util.*;
00026
00031 public class ProcTool {
00032
00033 String[] cmd = null;
00034 Process process = null;
00035 BufferedReader stdout = null;
00036 BufferedReader stderr = null;
00037 PrintWriter stdin = null;
00038 StringBuffer sbout = new StringBuffer();
00039 StringBuffer sberr = new StringBuffer();
00040 ReaderToBuffer bo = null;
00041 ReaderToBuffer be = null;
00042
00046 public ProcTool (String[] cmd) throws Exception {
00047 this.cmd = cmd;
00048 start();
00049 }
00050
00054 public String getOutput() throws Exception {
00055 if (bo == null) { return null; }
00056 return bo.getBuffer();
00057 }
00058
00062 public String getError() throws Exception {
00063 if (be == null) { return null; }
00064 return be.getBuffer();
00065 }
00066
00070 public OutputStream getStdin() throws Exception {
00071 return process.getOutputStream();
00072 }
00073
00077 public synchronized void waitFor() throws Exception {
00078 if (process == null) { throw new Exception("Cannot wait for the process: It has not been started."); }
00079
00080
00081 stdout = null;
00082 stderr = null;
00083 stdin = null;
00084 bo = null;
00085 be = null;
00086 try { process.getInputStream().close(); } catch (Exception e) { };
00087 try { process.getErrorStream().close(); } catch (Exception e) { };
00088 try { process.getOutputStream().close(); } catch (Exception e) { };
00089
00090 System.gc();
00091 process.waitFor();
00092 }
00093
00097 private synchronized void start() throws Exception {
00098
00099 if (process != null) { throw new Exception("Cannot start(): Process has already been started."); }
00100 process = Runtime.getRuntime().exec(cmd);
00101
00102
00103 stdout = new BufferedReader( new InputStreamReader( process.getInputStream() ));
00104 stderr = new BufferedReader( new InputStreamReader( process.getErrorStream() ));
00105 stdin = new PrintWriter( process.getOutputStream() );
00106
00107
00108 bo = new ReaderToBuffer(stdout);
00109 be = new ReaderToBuffer(stderr);
00110 bo.start();
00111 be.start();
00112
00113 }
00114
00115 class ReaderToBuffer extends Thread {
00116 BufferedReader br;
00117 StringBuffer sb = new StringBuffer();
00118 public ReaderToBuffer (BufferedReader br) {
00119 this.br = br;
00120 }
00121 public void run() {
00122 try {
00123 String line;
00124 while ((line = br.readLine()) != null) {
00125 synchronized (sb) { sb.append(line); sb.append("\n"); }
00126
00127 }
00128 }
00129 catch (Exception e) {
00130
00131 }
00132 }
00133 public String getBuffer() {
00134 synchronized (sb) {
00135 String result = sb.toString();
00136 if (sb.length() > 0) { sb.delete(0, sb.length()-1); }
00137 return result;
00138 }
00139 }
00140 }
00141
00142 }