1 24 package org.riotfamily.common.io; 25 26 import java.io.ByteArrayOutputStream ; 27 import java.io.IOException ; 28 import java.io.OutputStream ; 29 import java.util.List ; 30 31 import org.springframework.util.Assert; 32 import org.springframework.util.StringUtils; 33 34 38 public class RuntimeCommand { 39 40 private String [] commandLine; 41 42 private Process process; 43 44 private OutputStream stdErr = new ByteArrayOutputStream (); 45 46 private OutputStream stdOut = new ByteArrayOutputStream (); 47 48 private OutputStream stdIn; 49 50 private StreamCopyThread stdErrCopyThread; 51 52 private StreamCopyThread stdOutCopyThread; 53 54 private Integer exitCode; 55 56 public RuntimeCommand(String executable) { 57 this(new String [] {executable}); 58 } 59 60 public RuntimeCommand(String executable, String arg) { 61 this(new String [] {executable, arg}); 62 } 63 64 public RuntimeCommand(List commandLine) { 65 this(StringUtils.toStringArray(commandLine)); 66 } 67 68 public RuntimeCommand(String [] commandLine) { 69 this.commandLine = commandLine; 70 } 71 72 public RuntimeCommand setStdOutStream(OutputStream stdOut) { 73 if (stdOut == null) { 74 stdOut = new NullOutputStream(); 75 } 76 this.stdOut = stdOut; 77 return this; 78 } 79 80 public RuntimeCommand setStdErrStream(OutputStream stdErr) { 81 if (stdErr == null) { 82 stdErr = new NullOutputStream(); 83 } 84 this.stdErr = stdErr; 85 return this; 86 } 87 88 public RuntimeCommand exec() throws IOException { 89 process = Runtime.getRuntime().exec(commandLine); 90 91 stdErrCopyThread = new StreamCopyThread(process.getErrorStream(), stdErr); 92 stdErrCopyThread.start(); 93 94 stdOutCopyThread = new StreamCopyThread(process.getInputStream(), stdOut); 95 stdOutCopyThread.start(); 96 97 stdIn = process.getOutputStream(); 98 return this; 99 } 100 101 public OutputStream getStdIn() { 102 Assert.notNull(stdIn, "exec() must be called first"); 103 return stdIn; 104 } 105 106 public int getExitCode() { 107 Assert.notNull(process, "exec() must be called first"); 108 if (exitCode == null) { 109 try { 110 IOUtils.closeStream(stdIn); 111 stdErrCopyThread.join(); 112 stdOutCopyThread.join(); 113 exitCode = new Integer (process.waitFor()); 114 } 115 catch (InterruptedException e) { 116 return -1; 117 } 118 } 119 return exitCode.intValue(); 120 } 121 122 public String getOutput() { 123 getExitCode(); 124 return stdOut.toString(); 125 } 126 127 public String getErrors() { 128 getExitCode(); 129 return stdErr.toString(); 130 } 131 132 public String getResult() throws IOException { 133 if (getExitCode() == 0) { 134 return stdOut.toString(); 135 } 136 else { 137 throw new IOException (stdErr.toString()); 138 } 139 } 140 141 } 142 | Popular Tags |