com.jslsolucoes.runtime.se.RuntimeBuilder Maven / Gradle / Ivy
package com.jslsolucoes.runtime.se;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.zeroturnaround.exec.ProcessExecutor;
import org.zeroturnaround.exec.ProcessResult;
public class RuntimeBuilder {
private String command;
private Path directory;
private Map enviroment;
private Integer timeout;
private RuntimeBuilder() {
}
public static RuntimeBuilder newRuntime() {
return new RuntimeBuilder();
}
public RuntimeBuilder withCommand(String command) {
this.command = command;
return this;
}
public RuntimeBuilder withDirectory(String directory) {
this.directory = Paths.get(directory);
return this;
}
public RuntimeBuilder withDirectory(Path directory) {
this.directory = directory;
return this;
}
public RuntimeBuilder withDirectory(File directory) {
this.directory = directory.toPath();
return this;
}
public RuntimeBuilder withEnviroment(Map enviroment) {
this.enviroment = enviroment;
return this;
}
public RuntimeBuilder withTimeout(Integer timeout) {
this.timeout = timeout;
return this;
}
public RuntimeResult sync() {
return async().join();
}
public CompletableFuture async() {
return CompletableFuture.supplyAsync(() -> {
RuntimeResult runtimeResult = new RuntimeResult();
runtimeResult.setCommand(command);
runtimeResult.setDirectory(directory);
runtimeResult.setEnviroment(enviroment);
runtimeResult.setTimeout(timeout);
try {
ProcessExecutor processExecutor = new ProcessExecutor();
processExecutor.commandSplit(command);
processExecutor.readOutput(true);
if (directory != null) {
processExecutor.directory(directory.toFile());
}
if (enviroment != null) {
processExecutor.environment(enviroment);
}
if (timeout != null) {
processExecutor.timeout(timeout, TimeUnit.SECONDS);
}
ProcessResult processResult = processExecutor.execute();
String output = processResult.outputUTF8();
if (!StringUtils.isEmpty(output)) {
runtimeResult.setOutput(output);
}
runtimeResult.setExitValue(processResult.getExitValue());
if (processResult.getExitValue() == 0) {
runtimeResult.setRuntimeResultType(RuntimeResultType.SUCCESS);
} else {
runtimeResult.setRuntimeResultType(RuntimeResultType.ERROR);
}
} catch (Exception exception) {
runtimeResult.setExitValue(1);
runtimeResult.setRuntimeResultType(RuntimeResultType.ERROR);
runtimeResult.setOutput(ExceptionUtils.getThrowableList(exception).stream()
.map(throwable -> throwable.getMessage()).collect(Collectors.joining(", ")));
}
return runtimeResult;
});
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy