/
UnixCommand.java
82 lines (62 loc) · 1.92 KB
/
UnixCommand.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package voldemort.utils.ec2testing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.commons.lang.StringUtils;
/**
* A wrapper for executing a unix command
*
* @author jay
*
*/
public class UnixCommand {
private final String[] args;
public static void main(String[] args) throws Exception {
UnixCommand cmd = new UnixCommand(args);
cmd.execute();
}
public UnixCommand(String... args) {
this.args = args;
}
public UnixCommand(List<String> args) {
this.args = args.toArray(new String[args.size()]);
}
public void execute() throws InterruptedException, IOException {
ProcessBuilder builder = new ProcessBuilder(this.args);
Process process = builder.start();
Thread stdout = new StreamPrinter(process.getInputStream());
Thread stderr = new StreamPrinter(process.getErrorStream());
stdout.start();
stderr.start();
process.waitFor();
int exitCode = process.exitValue();
if(exitCode > 0)
throw new RuntimeException(exitCode + "");
}
public String getCommand() {
return StringUtils.join(args, ' ');
}
@Override
public String toString() {
return StringUtils.join(args, ' ');
}
private static class StreamPrinter extends Thread {
private BufferedReader reader;
public StreamPrinter(InputStream inputStream) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
}
@Override
public void run() {
try {
String line = null;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
}