Last active
August 14, 2023 15:02
-
-
Save jkschneider/43713e0a5e0597f4f4604dbfe82a8478 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.concurrent.*; | |
import java.util.function.Consumer; | |
ExecutorService executorService = Executors.newSingleThreadExecutor(); | |
System.out.println("Executing command: " + args[0]); | |
try { | |
Process proc = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", args[0]}); | |
StringBuilder sb = new StringBuilder(); | |
Runnable streamGobbler = new Runnable() { | |
@Override | |
public void run() { | |
new BufferedReader(new InputStreamReader(proc.getInputStream())).lines() | |
.forEach(sb::append); | |
new BufferedReader(new InputStreamReader(proc.getErrorStream())).lines() | |
.forEach(sb::append); | |
} | |
}; | |
Future<?> future = executorService.submit(streamGobbler); | |
if (!proc.waitFor(30, TimeUnit.SECONDS)) { | |
throw new IOException("Execution timed out for command: " + args[0]); | |
} | |
future.get(10, TimeUnit.SECONDS); | |
if (proc.exitValue() != 0) { | |
throw new IOException(sb.toString()); | |
} | |
System.out.println(sb.toString()); | |
} catch (IOException e) { | |
throw new UncheckedIOException(e); | |
} catch (InterruptedException | ExecutionException | TimeoutException e) { | |
throw new RuntimeException(e); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment