-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCommand.java
More file actions
82 lines (65 loc) · 2.11 KB
/
Command.java
File metadata and controls
82 lines (65 loc) · 2.11 KB
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
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
@SuppressWarnings("unused")
public abstract class Command {
protected final String[] args;
public Command(String... args) {
this.args = args;
}
protected abstract String command();
protected abstract File directory();
protected int timeout() {
return 1000 * 60;// default timeout
}
public Result execute() throws Exception {
List<String> args = new ArrayList<>();
args.add(command());
String[] params = this.args;
if (this.args != null) {
for (String param : params) {
args.add(param);
}
}
ProcessBuilder builder = new ProcessBuilder(args);
builder.directory(directory());
final Process process = builder.start();
final Timer timeout = new Timer();
timeout.schedule(new TimerTask() {
@Override
public void run() {
process.destroy();
}
}, timeout());// timeout
int exitCode = process.waitFor();
timeout.cancel();
return new Result(exitCode, output(process));
}
private String output(Process process) throws IOException {
InputStream inputStream = process.getInputStream();
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
int readBytes;
byte[] buffer = new byte[2048];
while ((readBytes = inputStream.read(buffer)) >= 0) {
bytes.write(buffer, 0, readBytes);
}
return new String(bytes.toByteArray());
}
public class Result {
public final int code;
public final String output;
public Result(int code, String output) {
this.code = code;
this.output = output;
}
}
@Override
public String toString() {
return String.format("%s %s", command(), org.apache.commons.lang.StringUtils.join(args, " "));
}
}