1 package de.matthias_burbach.mosaique.core.util;
2
3 import java.io.BufferedReader;
4 import java.io.InputStream;
5 import java.io.InputStreamReader;
6
7 /***
8 * @author Matthias Burbach
9 */
10 public class CommandLine {
11 /***
12 * Holds the output written to standard out by {@link #execute(String)}.
13 */
14 private StringBuffer stdout = new StringBuffer();
15
16 /***
17 * Holds the output written to standard error by {@link #execute(String)}.
18 */
19 private StringBuffer stderr = new StringBuffer();
20
21 /***
22 * Executes the command on the command line.
23 *
24 * @param command The command to execute.
25 * @return The exit value of the process executed.
26 * By convention, 0 usually indicates normal execution.
27 */
28 public int execute(final String command) {
29 int exitValue = -1;
30 try {
31 Process process = Runtime.getRuntime().exec(command);
32 captureOutput(process.getInputStream(), stdout);
33 captureOutput(process.getErrorStream(), stderr);
34 exitValue = process.waitFor();
35 } catch (Exception e) {
36 e.printStackTrace();
37 }
38 return exitValue;
39 }
40
41 /***
42 * @return The standard out output of the last command executed.
43 */
44 public String getStdout() {
45 return stdout.toString();
46 }
47
48 /***
49 * This variant is helpful if regular expression pattern matching is to be
50 * applied on the string.
51 *
52 * @return The standard out output of the last command executed.
53 * Each new line character is replaced by a blank.
54 */
55 public String getStdoutWithoutNewLines() {
56 return stdout.toString().replace('\n', ' ');
57 }
58
59 /***
60 * @return The standard error output of the last command executed.
61 */
62 public String getStdErr() {
63 return stderr.toString();
64 }
65
66 /***
67 * This variant is helpful if regular expression pattern matching is to be
68 * applied on the string.
69 *
70 * @return The standard error output of the last command executed.
71 * Each new line character is replaced by a blank.
72 */
73 public String getStdErrWithoutNewLines() {
74 return stderr.toString().replace('\n', ' ');
75 }
76
77 /***
78 * @param is The input stream to capture the output from.
79 * @param storage The storage to save the captured output in.
80 * @throws Exception if anything goes wrong
81 */
82 private void captureOutput(
83 final InputStream is, final StringBuffer storage) throws Exception {
84 storage.setLength(0);
85 InputStreamReader isr = new InputStreamReader(is);
86 BufferedReader br = new BufferedReader(isr);
87 String line = null;
88 while ((line = br.readLine()) != null) {
89 storage.append(line + "\n");
90 }
91 }
92 }