KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > archive > update > CommandLineWithOutput


1 package com.openedit.archive.update;
2
3 import java.io.IOException JavaDoc;
4 import java.util.Iterator JavaDoc;
5 import java.util.List JavaDoc;
6 import java.util.Vector JavaDoc;
7
8 import org.apache.commons.logging.Log;
9 import org.apache.commons.logging.LogFactory;
10
11 public class CommandLineWithOutput extends CommandLine {
12     private static final Log log = LogFactory.getLog(CommandLineWithOutput.class);
13
14     private Vector JavaDoc output = new Vector JavaDoc();
15
16     public List JavaDoc getOutput() {
17         return output;
18     }
19
20     public boolean exec(String JavaDoc[] cmd) {
21         if ( cmd ==null)
22             return false;
23
24         output = new Vector JavaDoc();
25         int exitVal = 0;
26         try {
27             Runtime JavaDoc runtime = Runtime.getRuntime();
28
29             log.debug("Running: " + cmd);
30             Process JavaDoc proc = runtime.exec(cmd);
31             manageOutputStreams(proc);
32             exitVal = proc.waitFor();
33             if (exitVal != 0) {
34                 reportError(cmd);
35             }
36             log.debug("ExitValue: " + exitVal);
37             for (Iterator JavaDoc iter = output.iterator(); iter.hasNext();) {
38                 log.debug(iter.next());
39             }
40         } catch (IOException JavaDoc x) {
41             reportError(cmd);
42             return false;
43         } catch (InterruptedException JavaDoc e) {
44             reportError(cmd);
45             return false;
46         }
47         return exitVal == 0;
48     }
49
50     private void manageOutputStreams(Process JavaDoc proc) {
51         errorMessagesGobbler(proc).start();
52         outputMessagesGobbler(proc).start();
53     }
54
55     private StreamGobbler outputMessagesGobbler(Process JavaDoc proc) {
56         StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(),
57                 "OUTPUT", output);
58         return outputGobbler;
59     }
60
61     private StreamGobbler errorMessagesGobbler(Process JavaDoc proc) {
62         StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(),
63                 "ERROR", output);
64         return errorGobbler;
65     }
66 }
Popular Tags