The Unified and Autonomous Development Platform
Refactor commandline class.
robin shine3b823eb39680
diff --git a/commons.util/src/main/java/com/pmease/commons/util/execution/Argument.java b/commons.util/src/main/java/com/pmease/commons/util/execution/Argument.javanew file mode 100644index 0000000000..6753ae544f--- /dev/null+++ b/commons.util/src/main/java/com/pmease/commons/util/execution/Argument.java@@ -0,0 +1,21 @@+package com.pmease.commons.util.execution;++import com.pmease.commons.util.StringUtils;++public class Argument {++ private String[] values;++ public void setValue(String value) {+ values = new String[] {value};+ }++ public void setLine(String line) {+ values = StringUtils.parseQuoteTokens(line);+ }++ public String[] getParts() {+ return values;+ }++}\ No newline at end of filediff --git a/commons.util/src/main/java/com/pmease/commons/util/execution/Commandline.java b/commons.util/src/main/java/com/pmease/commons/util/execution/Commandline.javaindex 7f4971b355..f9f40f92e7 100644--- a/commons.util/src/main/java/com/pmease/commons/util/execution/Commandline.java+++ b/commons.util/src/main/java/com/pmease/commons/util/execution/Commandline.java@@ -5,142 +5,104 @@ import java.io.File;import java.io.IOException;import java.io.OutputStream;import java.util.ArrayList;-import java.util.Arrays;-import java.util.LinkedList;+import java.util.HashMap;import java.util.List;import java.util.Map;-import java.util.Vector;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;-import org.apache.tools.ant.types.Environment;+import javax.annotation.Nullable;+import org.slf4j.Logger;import org.slf4j.LoggerFactory;+import com.google.common.base.Preconditions;+import com.pmease.commons.bootstrap.Bootstrap;import com.pmease.commons.util.StringUtils;-public class Commandline {+public class Commandline {static final ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool();- private static final int MAX_COMMAND_LENGTH = 1024;-private static final Logger logger = LoggerFactory.getLogger(Commandline.class);- private List<Argument> arguments = new ArrayList<Argument>();-- private String executable = null;+ private String executable;++ private List<String> arguments = new ArrayList<String>();+ private File workingDir;++ private Map<String, String> environment = new HashMap<String, String>();+public Commandline(String command) {- if (command != null) {- String[] parts = StringUtils.parseQuoteTokens(command);- if (parts != null && parts.length > 0) {- setExecutable(parts[0]);- for (int i = 1; i < parts.length; i++)- addArgValue(parts[i]);- }- }+ String[] parts = StringUtils.parseQuoteTokens(command);+ Preconditions.checkArgument(parts.length != 0, "Argument 'command' is invalid.");++ executable(parts[0]);+ for (int i = 1; i < parts.length; i++)+ arguments.add(parts[i]);}- public Argument createArgument() {- return createArgument(false);+ public Commandline executable(String executable) {+ Preconditions.checkArgument(StringUtils.isNotBlank(executable), "Argument 'executable' should not be empty.");++ this.executable = executable.replace('/', File.separatorChar).replace('\\', File.separatorChar);++ return this;+ }++ public Commandline arguments(List<String> arguments) {+ this.arguments.clear();+ this.arguments.addAll(arguments);+ return this;}public Commandline addArgValue(String argValue) {- createArgument().setValue(argValue);+ arguments.add(argValue);return this;}public Commandline addArgLine(String argLine) {- createArgument().setLine(argLine);+ for (String each: StringUtils.parseQuoteTokens(argLine))+ arguments.add(each);return this;}-- public Argument createArgument(boolean insertAtStart) {- Argument argument = new Argument();- if (insertAtStart) {- arguments.add(0, argument);- } else {- arguments.add(argument);- }- return argument;- }-- public Commandline setExecutable(String executable) {- if (executable == null || executable.length() == 0)- return this;- this.executable = executable.replace('/', File.separatorChar).replace('\\', File.separatorChar);-- return this;- }-- public String getExecutable() {- return executable;- }-- public Commandline addArguments(String[] argumentValues) {- for (int i = 0; i < argumentValues.length; i++) {- createArgument().setValue(argumentValues[i]);- }- return this;- }-- public String[] getCommandParts() {- List<String> parts = new LinkedList<String>();- if (executable != null)- parts.add(executable);- parts.addAll(Arrays.asList(getArgumentParts()));- return parts.toArray(new String[parts.size()]);- }- public boolean willOverflow(String argValue) {- int length = 0;- if (executable != null) {- // executable length plus trailing space- length = executable.length() + 1;- // if contains whitespaces, surrounding quote will be used- if (executable.indexOf(' ') != -1 || executable.indexOf('\t') != -1)- length += 2;- }- for (int i = 0; i < arguments.size(); i++) {- Argument arg = arguments.get(i);- String[] s = arg.getParts();- if (s != null) {- for (int j = 0; j < s.length; j++) {- length += s[j].length() + 1;- if (s[j].indexOf(' ') != -1 || s[j].indexOf('\t') != -1)- length += 2;- }- }- }- length += argValue.length();- if (argValue.indexOf(' ') != -1 || argValue.indexOf('\t') != -1)- length += 2;-- return length > MAX_COMMAND_LENGTH;+ public Commandline workingDir(File workingDir) {+ this.workingDir = workingDir;+ return this;}-- public String[] getArgumentParts() {- List<String> parts = new ArrayList<String>(arguments.size() * 2);- for (int i = 0; i < arguments.size(); i++) {- Argument arg = arguments.get(i);- String[] s = arg.getParts();- if (s != null) {- for (int j = 0; j < s.length; j++) {- parts.add(s[j]);- }- }- }- return parts.toArray(new String[parts.size()]);++ public Commandline environment(Map<String, String> environment) {+ this.environment.clear();+ this.environment.putAll(environment);+ return this;}public String toString() {- return describe();+ List<String> command = new ArrayList<String>();+ command.add(executable);+ command.addAll(arguments);++ StringBuffer buf = new StringBuffer();+ for (String each: command) {+ if (each.contains(" ") || each.contains("\t")) {+ buf.append("\"").append(StringUtils.replace(+ each, "\n", "\\n")).append("\"").append(" ");+ } else {+ buf.append(StringUtils.replace(+ each, "\n", "\\n")).append(" ");+ }+ }+ return buf.toString();}public Commandline clear() {executable = null;arguments.clear();+ environment.clear();+ workingDir = null;+return this;}@@ -148,77 +110,38 @@ public class Commandline {arguments.clear();return this;}-- public String describe() {- String[] args = getCommandParts();- if (args == null || args.length == 0) {- return "";- }- StringBuffer buf = new StringBuffer();- for (int i = 0; i < args.length; i++) {- if (args[i].contains(" ") || args[i].contains("\t")) {- buf.append("\"").append(StringUtils.replace(- args[i], "\n", "\\n")).append("\"").append(" ");- } else {- buf.append(StringUtils.replace(- args[i], "\n", "\\n")).append(" ");- }- }- return buf.toString();- }-- public ExecuteResult execute(File workingDir, Environment execEnv, OutputStream stdoutConsumer,- LineConsumer stderrConsumer) {- return execute(workingDir, execEnv, stdoutConsumer, stderrConsumer, null);- }-- public ExecuteResult execute(File workingDir, OutputStream stdoutConsumer, LineConsumer stderrConsumer) {- return execute(workingDir, null, stdoutConsumer, stderrConsumer, null);- }public ExecuteResult execute(OutputStream stdoutConsumer, LineConsumer stderrConsumer) {- return execute(null, null, stdoutConsumer, stderrConsumer, null);+ return execute(stdoutConsumer, stderrConsumer, null);}- public ExecuteResult execute(Environment execEnv, OutputStream stdoutConsumer, LineConsumer stderrConsumer) {- return execute(null, execEnv, stdoutConsumer, stderrConsumer, null);- }-- public ExecuteResult execute(OutputStream stdoutConsumer, LineConsumer stderrConsumer, String stdinString) {- return execute(null, null, stdoutConsumer, stderrConsumer, stdinString);- }-- public ExecuteResult execute(Environment execEnv, OutputStream stdoutConsumer, LineConsumer stderrConsumer,- String stdinString) {- return execute(null, execEnv, stdoutConsumer, stderrConsumer, stdinString);- }-- private ProcessBuilder getProcessBuilder(File workingDir, Environment execEnv) {- if (workingDir == null)- workingDir = com.pmease.commons.bootstrap.Bootstrap.getBinDir();- String[] cmdParts = getCommandParts();- if (!new File(cmdParts[0]).isAbsolute()) {- if (new File(workingDir, cmdParts[0]).isFile())- cmdParts[0] = new File(workingDir, cmdParts[0]).getAbsolutePath();- else if (new File(workingDir, cmdParts[0] + ".exe").isFile())- cmdParts[0] = new File(workingDir, cmdParts[0] + ".exe").getAbsolutePath();- else if (new File(workingDir, cmdParts[0] + ".bat").isFile())- cmdParts[0] = new File(workingDir, cmdParts[0] + ".bat").getAbsolutePath();+ private ProcessBuilder createProcessBuilder() {+ File workingDir = this.workingDir;+ if (workingDir == null)+ workingDir = Bootstrap.getTempDir();++ String executable = this.executable;++ if (!new File(executable).isAbsolute()) {+ if (new File(workingDir, executable).isFile())+ executable = new File(workingDir, executable).getAbsolutePath();+ else if (new File(workingDir, executable + ".exe").isFile())+ executable = new File(workingDir, executable + ".exe").getAbsolutePath();+ else if (new File(workingDir, executable + ".bat").isFile())+ executable = new File(workingDir, executable + ".bat").getAbsolutePath();}- ProcessBuilder processBuilder = new ProcessBuilder(cmdParts);- processBuilder.directory(workingDir);-- if (execEnv != null) {- Map<String, String> procEnv = processBuilder.environment();- for (Environment.Variable var: (Vector<Environment.Variable>)execEnv.getVariablesVector()) {- if (var.getKey() != null && var.getValue() != null)- procEnv.put(var.getKey(), var.getValue());- }- }-+ List<String> command = new ArrayList<String>();+ command.add(executable);+ command.addAll(arguments);++ ProcessBuilder processBuilder = new ProcessBuilder(command);+ processBuilder.directory(workingDir);++ processBuilder.environment().putAll(environment);+if (logger.isDebugEnabled()) {- logger.debug("Executing command: " + describe());+ logger.debug("Executing command: " + this);logger.debug("Command working directory: " +processBuilder.directory().getAbsolutePath());StringBuffer buffer = new StringBuffer();@@ -231,19 +154,20 @@ public class Commandline {return processBuilder;}- public ExecuteResult execute(File workingDir, Environment execEnv, OutputStream stdoutConsumer,- final LineConsumer stderrConsumer, String stdinString) {+ public ExecuteResult execute(OutputStream stdoutConsumer, final LineConsumer stderrConsumer,+ @Nullable byte[] stdinBytes) {+Process process;try {- ProcessBuilder processBuilder = getProcessBuilder(workingDir, execEnv);+ ProcessBuilder processBuilder = createProcessBuilder();process = processBuilder.redirectErrorStream(stderrConsumer == null).start();} catch (IOException e) {- throw new RuntimeException(e.getMessage());+ throw new RuntimeException(e);}ByteArrayInputStream inputStream = null;- if (stdinString != null && stdinString.length() != 0)- inputStream = new ByteArrayInputStream(stdinString.getBytes());+ if (stdinBytes != null && stdinBytes.length != 0)+ inputStream = new ByteArrayInputStream(stdinBytes);final StringBuffer errorMessage = new StringBuffer();OutputStream errorMessageCollector = null;@@ -261,137 +185,36 @@ public class Commandline {};}- ProcessStreamPumper streamPumper = new ProcessStreamPumper(process, stdoutConsumer,+ ProcessStreamPumper streamPumper = ProcessStreamPumper.pump(process, stdoutConsumer,errorMessageCollector, inputStream);- streamPumper.start();- ExecuteResult result = new ExecuteResult();+ ExecuteResult result = new ExecuteResult(this);+try {- while (true) {- try {- result.setReturnCode(process.waitFor());- break;- } catch (InterruptedException e) {- process.destroy();- throw new RuntimeException(e);- }- }- } finally {- streamPumper.join();- Thread.interrupted();- }+ result.setReturnCode(process.waitFor());+ } catch (InterruptedException e) {+ process.destroy();+ throw new RuntimeException(e);+ } finally {+ streamPumper.waitFor();+ }+if (errorMessage.length() != 0)result.setErrorMessage(errorMessage.toString());return result;}- public void executeWithoutWait() {- executeWithoutWait(null, null);- }-- public void executeWithoutWait(File workingDir) {- executeWithoutWait(workingDir, null);- }-- public void executeWithoutWait(File workingDir, Environment execEnv) {- executeWithoutWait(workingDir, execEnv, null);- }-- public void executeWithoutWait(Environment execEnv) {- executeWithoutWait(null, execEnv);- }-- public void executeWithoutWait(File workingDir, Environment execEnv, String stdinString) {+ public void executeWithoutWait(@Nullable byte[] stdinBytes) {ByteArrayInputStream stdinStream = null;- if (stdinString != null && stdinString.length() != 0)- stdinStream = new ByteArrayInputStream(stdinString.getBytes());+ if (stdinBytes != null && stdinBytes.length != 0)+ stdinStream = new ByteArrayInputStream(stdinBytes);- final Process process;try {- process = getProcessBuilder(workingDir, execEnv).start();- new ProcessStreamPumper(process, null, null, stdinStream).start();+ ProcessStreamPumper.pump(createProcessBuilder().start(), null, null, stdinStream);} catch (IOException e) {throw new RuntimeException(e);}-- EXECUTOR_SERVICE.submit(new Runnable() {-- @Override- public void run() {- try {- process.waitFor();- } catch (InterruptedException e) {- }- }-- });-}-- public class ExecuteResult {-- private int returnCode;-- private String errorMessage;-- public int getReturnCode() {- return returnCode;- }- public void setReturnCode(int returnCode) {- this.returnCode = returnCode;- }-- public String getErrorMessage() {- return errorMessage;- }-- public void setErrorMessage(String errorMessage) {- this.errorMessage = errorMessage;- }-- /**- * Build an exception object with command description, stderr output and return code.- * @return- */- public RuntimeException buildException() {- if (errorMessage != null) {- throw new RuntimeException("Failed to run command: " + describe() +- "\nCommand return code: " + getReturnCode() +- "\nCommand error output: " + errorMessage);- } else {- throw new RuntimeException("Failed to run command: " + describe() +- "\nCommand return code: " + getReturnCode());- }-- }-- /**- * Check return code and throw exception if it does not equal to 0.- */- public void checkReturnCode() {- if (getReturnCode() != 0)- throw buildException();- }- }-- public static class Argument {-- private String[] parts;-- public void setValue(String value) {- parts = new String[] {value};- }-- public void setLine(String line) {- parts = StringUtils.parseQuoteTokens(line);- }-- public String[] getParts() {- return parts;- }-- }-}diff --git a/commons.util/src/main/java/com/pmease/commons/util/execution/ExecuteResult.java b/commons.util/src/main/java/com/pmease/commons/util/execution/ExecuteResult.javanew file mode 100644index 0000000000..29ae182253--- /dev/null+++ b/commons.util/src/main/java/com/pmease/commons/util/execution/ExecuteResult.java@@ -0,0 +1,54 @@+package com.pmease.commons.util.execution;++public class ExecuteResult {++ private int returnCode;++ private String errorMessage;++ private String commandDescription;++ public ExecuteResult(Commandline cmdline) {+ commandDescription = cmdline.toString();+ }++ public int getReturnCode() {+ return returnCode;+ }++ public void setReturnCode(int returnCode) {+ this.returnCode = returnCode;+ }++ public String getErrorMessage() {+ return errorMessage;+ }++ public void setErrorMessage(String errorMessage) {+ this.errorMessage = errorMessage;+ }++ /**+ * Build an exception object with command description, stderr output and return code.+ * @return+ */+ public RuntimeException buildException() {+ if (errorMessage != null) {+ throw new RuntimeException("Failed to run command: " + commandDescription ++ "\nCommand return code: " + getReturnCode() ++ "\nCommand error output: " + errorMessage);+ } else {+ throw new RuntimeException("Failed to run command: " + commandDescription ++ "\nCommand return code: " + getReturnCode());+ }++ }++ /**+ * Check return code and throw exception if it does not equal to 0.+ */+ public void checkReturnCode() {+ if (getReturnCode() != 0)+ throw buildException();+ }+}\ No newline at end of filediff --git a/commons.util/src/main/java/com/pmease/commons/util/execution/ProcessStreamPumper.java b/commons.util/src/main/java/com/pmease/commons/util/execution/ProcessStreamPumper.javaindex 96705a8f83..7e5e576ee8 100644--- a/commons.util/src/main/java/com/pmease/commons/util/execution/ProcessStreamPumper.java+++ b/commons.util/src/main/java/com/pmease/commons/util/execution/ProcessStreamPumper.java@@ -5,53 +5,47 @@ import java.io.InputStream;import java.io.OutputStream;import java.util.concurrent.Future;+import javax.annotation.Nullable;+import org.slf4j.Logger;import org.slf4j.LoggerFactory;-class ProcessStreamPumper {+public class ProcessStreamPumper {private static final int BUFFER_SIZE = 64000;private static final Logger logger = LoggerFactory.getLogger(ProcessStreamPumper.class);- private Future<?> stdoutPumper;+ private final Future<?> stdoutPumper;- private Future<?> stderrPumper;+ private final Future<?> stderrPumper;- private Future<?> stdinPumper;+ private final Future<?> stdinPumper;- private OutputStream stdoutStream;-- private OutputStream stderrStream;-- private InputStream stdinStream;+ private final OutputStream stdoutStream;- private Process process;+ private final OutputStream stderrStream;- /**- * @param process not null- * @param stdoutStream might be null- * @param stderrStream might be null- * @param stdinStream might be null- */- public ProcessStreamPumper(Process process, OutputStream stdoutStream, OutputStream stderrStream,- InputStream stdinStream) {- this.process = process;-+ private ProcessStreamPumper(Process process, @Nullable OutputStream stdoutStream,+ @Nullable OutputStream stderrStream, @Nullable InputStream stdinStream) {this.stdoutStream = stdoutStream;this.stderrStream = stderrStream;- this.stdinStream = stdinStream;- }-- public void start() {+stdoutPumper = createPump(process.getInputStream(), stdoutStream, false);stderrPumper = createPump(process.getErrorStream(), stderrStream, false);if (stdinStream != null)stdinPumper = createPump(stdinStream, process.getOutputStream(), true);+ else+ stdinPumper = null;}-- public void join() {++ public static ProcessStreamPumper pump(Process process, @Nullable OutputStream stdoutStream,+ @Nullable OutputStream stderrStream, @Nullable InputStream stdinStream) {+ return new ProcessStreamPumper(process, stdoutStream, stderrStream, stdinStream);+ }++ public void waitFor() {while (!stdoutPumper.isDone() || !stderrPumper.isDone() ||(stdinPumper != null && !stdinPumper.isDone())) {try {@@ -59,16 +53,20 @@ class ProcessStreamPumper {} catch (InterruptedException e) {}}- try {- if (stderrStream != null)- stderrStream.flush();- } catch (IOException e) {- }- try {- if (stdoutStream != null)- stdoutStream.flush();- } catch (IOException e) {- }+ if (stdoutStream != null) {+ try {+ stdoutStream.flush();+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+ if (stderrStream != null) {+ try {+ stderrStream.flush();+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }}private Future<?> createPump(final InputStream input, final OutputStream output,@@ -85,18 +83,14 @@ class ProcessStreamPumper {if (output != null)output.write(buf, 0, length);}- } catch (Exception e) {- logger.error("Error pumping stream.", e);- process.destroy();- } finally {+if (closeWhenExhausted && output!=null) {- try {- output.close();- } catch (IOException e) {- }+ output.close();}++ } catch (Exception e) {+ logger.error("Error pumping stream.", e);}-}});