|
/** |
|
* GPL |
|
*/ |
|
public class ProcessBuilderWrapper { |
|
private String[] command; |
|
private File workingDirectory; |
|
|
|
// exit value of the process |
|
private int status; |
|
|
|
private boolean redirectToStdout; |
|
private boolean redirectErrorStream; |
|
|
|
private ByteArrayOutputStream outStd = new ByteArrayOutputStream(); |
|
private ByteArrayOutputStream outError = new ByteArrayOutputStream(); |
|
|
|
// environment variables, that are visible to the process |
|
private Map<String, String> environment = null; |
|
|
|
public ProcessBuilderWrapper(String... command) { |
|
this.command = command; |
|
} |
|
|
|
public void run() throws IOException, InterruptedException { |
|
ProcessBuilder pb = new ProcessBuilder(command); |
|
if(workingDirectory != null) |
|
pb.directory(workingDirectory); |
|
if(environment != null && environment.size() > 0) |
|
pb.environment().putAll(environment); |
|
|
|
pb.redirectErrorStream(redirectErrorStream); |
|
|
|
Process process = pb.start(); |
|
try (var infoStream = process.getInputStream(); var errorStream = process.getErrorStream()) { |
|
if(redirectToStdout) { |
|
infoStream.transferTo(System.out); |
|
errorStream.transferTo(System.out); |
|
} else { |
|
infoStream.transferTo(this.outStd); |
|
errorStream.transferTo(this.outError); |
|
} |
|
} |
|
status = process.waitFor(); |
|
} |
|
|
|
public void redirectToStdOut() { |
|
this.redirectToStdout = true; |
|
} |
|
|
|
public void redirectErrorStream() { |
|
this.redirectErrorStream = true; |
|
} |
|
|
|
public void setWorkingDirectory(String dir) { |
|
this.workingDirectory = Paths.get(dir).toFile(); |
|
} |
|
|
|
public void setEnvironment(Map<String, String> environment) { |
|
this.environment = environment; |
|
} |
|
|
|
public int getStatus() { |
|
return status; |
|
} |
|
|
|
public String getOutput() { |
|
return (redirectToStdout) ? "n/a" : outStd.toString(); |
|
} |
|
|
|
public String getError() { |
|
return (redirectToStdout) ? "n/a" : outError.toString(); |
|
} |
|
|
|
public boolean hasErrors() { |
|
return getStatus() != 0; |
|
} |
|
} |