1 package org.wamblee.io;
3 import java.io.BufferedReader;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.io.OutputStream;
9 import java.io.PrintStream;
10 import java.io.StringWriter;
11 import java.io.Writer;
13 import org.apache.commons.logging.Log;
14 import org.apache.commons.logging.LogFactory;
16 public class SimpleProcess {
18 private static final Log LOG = LogFactory.getLog(SimpleProcess.class);
20 private File _directory;
22 private String[] _cmd;
24 private String _stdout;
25 private String _stderr;
27 public SimpleProcess(File aDirectory, String[] aCmd) {
28 _directory = aDirectory;
35 public String getStdout() {
42 public String getStderr() {
47 * Runs the process and blocks until it is done.
49 * @return Exit status of the process.
51 * In case of problems.
53 public int run() throws IOException {
57 private int runImpl() throws IOException {
60 for (String part: _cmd) {
61 fullcmd += " " + part;
63 LOG.debug("Executing '" + fullcmd + "' in directory '" + _directory
65 java.lang.Process proc = Runtime.getRuntime().exec(_cmd, null, _directory);
67 // Read standard output and error in separate threads to avoid
70 StringWriter stdout = new StringWriter();
71 StringWriter stderr = new StringWriter();
72 Thread stdoutReader = readAndLogStream("STDOUT> ", proc
73 .getInputStream(), stdout);
74 Thread stderrReader = readAndLogStream("STDERR> ", proc
75 .getErrorStream(), stderr);
79 } catch (InterruptedException e) {
80 IOException exception = new IOException(
81 "Process was terminated: " + this);
82 exception.initCause(e);
85 waitForReader(stdoutReader);
86 waitForReader(stderrReader);
88 _stdout = stdout.toString();
89 _stderr = stderr.toString();
91 if (proc.exitValue() != 0) {
92 LOG.warn("Exit value was non-zero: " + this);
94 LOG.debug("Process finished");
96 return proc.exitValue();
97 } catch (IOException e) {
98 IOException exception = new IOException("Error executing process: "
100 exception.initCause(e);
105 private void waitForReader(Thread aReaderThread) {
107 aReaderThread.join();
108 } catch (InterruptedException e) {
111 + ": error waiting for output stream reader of process to finish");
115 private Thread readAndLogStream(final String aPrefix,
116 final InputStream aStream, final Writer aOutput) {
117 Thread inputReader = new Thread() {
120 BufferedReader br = null;
122 br = new BufferedReader(new InputStreamReader(aStream));
124 while ((str = br.readLine()) != null) {
125 LOG.debug(aPrefix + str);
128 } catch (IOException e) {
129 LOG.warn(SimpleProcess.this + ": error reading input stream", e);
134 } catch (IOException e) {
135 LOG.warn("Error closing stream " + aPrefix);
146 public String toString() {
148 for (String part: _cmd) {
149 fullcmd += part + " ";
151 return "process(dir = '" + _directory + "', cmd = '" + fullcmd + "')";