/
ProcessExecutor.java
63 lines (52 loc) · 1.76 KB
/
ProcessExecutor.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
/*
* SPDX-License-Identifier: Apache-2.0
*
* Copyright The original authors
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.moditect.internal.command;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.moditect.spi.log.Log;
/**
* Executes a specified external processor, logging output to the given logger.
*
* @author Gunnar Morling
*/
public class ProcessExecutor {
public static void run(String name, List<String> command, Log log) {
ProcessBuilder builder = new ProcessBuilder(command);
Process process;
List<String> outputLines = new ArrayList<>();
try {
process = builder.start();
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
outputLines.add(line);
log.debug(line);
}
BufferedReader err = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = err.readLine()) != null) {
log.error(line);
}
process.waitFor();
}
catch (IOException | InterruptedException e) {
for (String line : outputLines) {
log.error(line);
}
throw new RuntimeException("Couldn't run " + name, e);
}
if (process.exitValue() != 0) {
for (String line : outputLines) {
log.error(line);
}
throw new RuntimeException("Execution of " + name + " failed");
}
}
}