Skip to content

Instantly share code, notes, and snippets.

@Exerosis
Created February 17, 2018 23:27
Show Gist options
  • Save Exerosis/da874651e864748adb32cd80318ea014 to your computer and use it in GitHub Desktop.
Save Exerosis/da874651e864748adb32cd80318ea014 to your computer and use it in GitHub Desktop.
private CommandLine(String command,
OutputStream err,
OutputStream out,
boolean redirect,
int buffer) throws IOException {
this.buffer = buffer;
executor = newFixedThreadPool(redirect ? 1 : 2);
process = new ProcessBuilder(command)
.redirectErrorStream(redirect)
.start();
if (out != null)
this.out = pipe(process.getInputStream(), out);
if (err != null)
this.err = pipe(process.getErrorStream(), err);
}
public ExecutorService getExecutor() {
return executor;
}
public Process getProcess() {
return process;
}
public CommandLine execute(String... commands) {
return execute(() -> new Iterator<String>() {
int index = 0;
@Override
public boolean hasNext() {
return index < commands.length;
}
@Override
public String next() {
return commands[index++];
}
});
}
public CommandLine execute(Iterable<String> commands) {
try {
for (String line : commands) {
process.getOutputStream().write(line.getBytes());
if (!line.endsWith(RETURN))
process.getOutputStream().write(RETURN_DATA);
process.getOutputStream().flush();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return this;
}
private void drain(InputStream in) throws IOException {
for (int $ = 0; $ != -1; $ = in.read()) ;
}
private Closeable pipe(InputStream in, OutputStream out) {
final Future<?> task = executor.submit(() -> {
final byte[] buffer = new byte[this.buffer];
for (int length = 0; ; length = in.read(buffer)) {
out.write(buffer, 0, length);
out.flush();
}
});
return () -> task.cancel(true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment