You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.8 KiB

///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 {
if (args.length == 0) {
System.out.println("This program allows you to run several commands at the same time."
+ "\n\nUsage: Splicer.java cmd1 cmd2 cmd3 ..."
+ "\n\nExample: ./Splicer.java \"ls -l\" \"df -kh\"\n");
return;
}
ExecutorService executorService = Executors.newFixedThreadPool(args.length);
List<Callable<ExecutionResult>> callables = List.of(args).stream()
.map(command -> new Callable<ExecutionResult>() {
@Override
public ExecutionResult call() throws Exception {
return executeShell(command);
}
}).collect(Collectors.toList());
List<ExecutionResult> 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) {
}
}