cn.net.wanmo.common.exec.ProcessBuilderGenerate Maven / Gradle / Ivy
package cn.net.wanmo.common.exec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class ProcessBuilderGenerate {
private static Logger logger = LoggerFactory.getLogger(ProcessBuilderGenerate.class);
public static ProcessBuilderGenerate build() {
return new ProcessBuilderGenerate();
}
/**
* 执行指令
*/
public Process getProcess() throws IOException {
logger.debug("============================= 执行指令开始 ===============================");
logger.debug("执行指令:{}", this.commands);
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(commands);
if (Objects.nonNull(this.environment) && this.environment.size() > 0) { // 设置环境变量
for (Map.Entry entry : this.environment.entrySet()) {
processBuilder.environment().put(entry.getKey(), entry.getValue());
}
}
if (Objects.nonNull(this.redirectInputFile)) { // 指令执行交互 是否重定向输入
processBuilder.redirectInput(this.redirectInputFile);
}
if (Objects.nonNull(this.redirectOutputFile)) { // 指令执行结果 是否重定向输出
processBuilder.redirectOutput(this.redirectOutputFile);
}
if (Objects.nonNull(this.redirectErrorFile)) { // 指令执行警告或错误 是否重定向输出
processBuilder.redirectError(this.redirectErrorFile);
}
return processBuilder.start();
}
/**
* 执行指令
*/
public R exec() {
R r = new R();
try {
Process process = getProcess();
r = ProcessUtil.getProcessR(process, this.isWait);
} catch (Exception e) {
r.setExceptionStr(e.getMessage());
logger.error("执行指令异常", e);
}
return r;
}
/**
* 指令
*/
private List commands = new ArrayList<>();
/**
* 是否等待,默认 false
*/
private boolean isWait = false;
/**
* 环境变量
*/
private Map environment = new HashMap<>();
/**
* 重定向输入:传递给指令的参数
*/
private File redirectInputFile;
/**
* 重定向输出:指令的执行结果
*/
private File redirectOutputFile;
/**
* 重定向错误:指令执行的警告或错误
*/
private File redirectErrorFile;
public ProcessBuilderGenerate commands(List commands) {
this.commands = commands;
return this;
}
public ProcessBuilderGenerate wait(boolean wait) {
isWait = wait;
return this;
}
public ProcessBuilderGenerate putEnv(String key, String value) {
this.environment.put(key, value);
return this;
}
public ProcessBuilderGenerate redirectInputFile(File redirectInputFile) {
this.redirectInputFile = redirectInputFile;
return this;
}
public ProcessBuilderGenerate redirectOutputFile(File redirectOutputFile) {
this.redirectOutputFile = redirectOutputFile;
return this;
}
public ProcessBuilderGenerate redirectErrorFile(File redirectErrorFile) {
this.redirectErrorFile = redirectErrorFile;
return this;
}
}