///usr/bin/env jbang "$0" "$@" ; exit $? //DEPS com.fasterxml.jackson.core:jackson-databind:2.18.4 //DEPS org.apache.commons:commons-exec:1.5.0 import java.io.ByteArrayOutputStream; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Collectors; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.PumpStreamHandler; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class Splicer { private static final Logger logger = Logger.getLogger(Splicer.class.getName()); public static void main(String[] args) throws InterruptedException, JsonProcessingException { ExecutorService executorService = Executors.newFixedThreadPool(args.length); List> callables = List.of(args).stream() .map(command -> new Callable() { @Override public ExecutionResult call() throws Exception { return executeShell(command); } }).collect(Collectors.toList()); List results = executorService.invokeAll(callables).parallelStream().map(f -> { try { return f.get(); } catch (InterruptedException | ExecutionException e) { logger.log(Level.SEVERE, "Error found!", e); } return null; }).filter(Objects::nonNull).collect(Collectors.toList()); executorService.shutdown(); System.out.println(new ObjectMapper().writeValueAsString(Map.of("results", results))); } public static ExecutionResult executeShell(String command) { ByteArrayOutputStream tempOut = new ByteArrayOutputStream(); try { CommandLine cmdLine = CommandLine.parse(command.trim()); DefaultExecutor executor = DefaultExecutor.builder().get(); PumpStreamHandler streamHandler = new PumpStreamHandler(tempOut); executor.setStreamHandler(streamHandler); int exitValue = executor.execute(cmdLine); return new ExecutionResult(command, exitValue, new String(tempOut.toByteArray())); } catch (Exception e) { logger.log(Level.SEVERE, "Execute cmd failed: " + command.trim(), e); } return new ExecutionResult(command, -1, new String(tempOut.toByteArray())); } public static record ExecutionResult(String command, Integer exitValue, String output) { } }