LocalCommandExecutor implements CommandExecutor { @Override public ExecutionResult tryExecute(Path workingDirectory, String... cmd) throws IOException { logger.debug("Executing `" + StringUtils.join(cmd, ' ') + " in " + workingDirectory); File workdir = workingDirectory == null ? null : workingDirectory.toFile(); Process process = Runtime.getRuntime().exec(cmd, null, workdir); String stdout = IOUtils.toString(process.getInputStream()); String stderr = IOUtils.toString(process.getErrorStream()); try { process.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Thread was interrupted before command finished", e); } int exitCode = process.exitValue(); return new ExecutionResult(exitCode, stdout, stderr); } protected  LocalCommandExecutor(); @Override ExecutionResult tryExecute(Path workingDirectory, String... cmd);  }
@Test public void testExitCode0() throws IOException, InterruptedException { CommandExecutor executor = new LocalCommandExecutor(); ExecutionResult result = executor.tryExecute("true"); assertThat(result.getExitCode(), is(0)); }
@Test public void testExitCode1() throws IOException, InterruptedException { CommandExecutor executor = new LocalCommandExecutor(); ExecutionResult result = executor.tryExecute("false"); assertThat(result.getExitCode(), is(1)); }
@Test public void testOutput() throws IOException, InterruptedException { CommandExecutor executor = new LocalCommandExecutor(); ExecutionResult result = executor.tryExecute("echo", "test string!"); assertThat(result.getOutput().trim(), is("test string!")); }
@Test(expected = IOException.class) public void testTryExecuteThrowsOnNonExistantCommand() throws IOException, InterruptedException { CommandExecutor executor = new LocalCommandExecutor(); executor.tryExecute("thisdoesnotexist"); }