[executeCommandLine] should return STDERR if STDOUT is empty (#2114)

Signed-off-by: Andrew Fiddian-Green <software@whitebear.ch>
pull/2146/head
Andrew Fiddian-Green 2021-01-16 21:20:09 +00:00 committed by GitHub
parent 074bd7a623
commit 127724c0e3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 17 additions and 27 deletions

View File

@ -78,9 +78,8 @@ public class ExecUtil {
Process processTemp = null;
Future<String> outputFuture = null;
Future<String> errorFuture = null;
cleanup: try {
Process process = processTemp = new ProcessBuilder(commandLine).start();
Process process = processTemp = new ProcessBuilder(commandLine).redirectErrorStream(true).start();
outputFuture = executor.submit(() -> {
try (InputStream inputStream = process.getInputStream();
@ -91,32 +90,13 @@ public class ExecUtil {
}
});
errorFuture = executor.submit(() -> {
try (InputStream inputStream = process.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
StringWriter output = new StringWriter();
reader.transferTo(output);
return output.toString();
}
});
int exitCode;
if (timeout == null) {
exitCode = process.waitFor();
} else if (process.waitFor(timeout.toMillis(), TimeUnit.MILLISECONDS)) {
exitCode = process.exitValue();
} else {
process.waitFor();
} else if (!process.waitFor(timeout.toMillis(), TimeUnit.MILLISECONDS)) {
logger.warn("Timeout occurred when executing commandLine '{}'", Arrays.toString(commandLine));
break cleanup;
}
if (exitCode == 0) {
return outputFuture.get();
} else {
if (logger.isDebugEnabled()) {
logger.debug("exit code '{}', result '{}', errors '{}'", exitCode, outputFuture.get(),
errorFuture.get());
}
return errorFuture.get();
}
return outputFuture.get();
} catch (ExecutionException e) {
if (logger.isDebugEnabled()) {
logger.warn("Error occurred when executing commandLine '{}'", Arrays.toString(commandLine),
@ -139,9 +119,6 @@ public class ExecUtil {
if (outputFuture != null) {
outputFuture.cancel(true);
}
if (errorFuture != null) {
errorFuture.cancel(true);
}
return null;
}
}

View File

@ -62,4 +62,17 @@ public class ExecUtilTest {
String osName = System.getProperty("os.name").toLowerCase();
return osName.indexOf("windows") >= 0;
}
@Test
public void testExecuteCommandLineAndWaitStdErrRedirection() {
final String result;
if (isWindowsSystem()) {
result = ExecUtil.executeCommandLineAndWaitResponse(Duration.ofSeconds(1), "cmd", "/c", "dir", "xxx.xxx",
"1>", "nul");
} else {
result = ExecUtil.executeCommandLineAndWaitResponse(Duration.ofSeconds(1), "ls", "xxx.xxx");
}
assertNotNull(result);
assertNotEquals("", result);
}
}