01: package net.sourceforge.cruisecontrol.util;
02:
03: import java.io.ByteArrayInputStream;
04: import java.io.FilterInputStream;
05: import java.io.IOException;
06: import java.io.InterruptedIOException;
07: import java.io.InputStream;
08:
09: import org.apache.log4j.Logger;
10:
11: /**
12: * A utility that helps to run command lines.
13: *
14: * @author Scott Coplin
15: */
16: public final class CommandlineUtil {
17: private static final Logger LOG = Logger
18: .getLogger(CommandlineUtil.class);
19:
20: /**
21: * Private constructor to prevent instantiation.
22: */
23: private CommandlineUtil() {
24: // Do nothing
25: }
26:
27: /**
28: * Run a command line and stream the output. It is expected that the
29: * stream that is returned is read to the end and then closed. This
30: * will ensure that it releases any associated resources. The error stream
31: * will be sent to the log.
32: *
33: * @param command The command to run.
34: * @return The output stream of the command.
35: */
36: public static InputStream streamOutput(Commandline command) {
37: try {
38: Process p = command.execute();
39: WarningConsumer consumer = new WarningConsumer(LOG);
40: StreamPumper errorPumper = new StreamPumper(p
41: .getErrorStream(), consumer);
42: new Thread(errorPumper).start();
43: return new ProcessStreamWrapper(p);
44: } catch (Exception e) {
45: LOG.error("Error in executing the command : ", e);
46: return new ByteArrayInputStream(new byte[0]);
47: }
48: }
49:
50: private static final class WarningConsumer implements
51: StreamConsumer {
52: private final Logger log;
53:
54: private WarningConsumer(Logger log) {
55: super ();
56: this .log = log;
57: }
58:
59: public void consumeLine(String line) {
60: this .log.warn(line);
61: }
62: }
63:
64: private static final class ProcessStreamWrapper extends
65: FilterInputStream {
66: private Process process;
67:
68: public ProcessStreamWrapper(Process process) {
69: super (process.getInputStream());
70: this .process = process;
71: }
72:
73: public void close() throws IOException {
74: try {
75: this .process.waitFor();
76: } catch (InterruptedException e) {
77: InterruptedIOException ioe = new InterruptedIOException();
78: ioe.initCause(e);
79: throw ioe;
80: }
81:
82: this.process.getInputStream().close();
83: this.process.getOutputStream().close();
84: this.process.getErrorStream().close();
85: }
86: }
87: }
|