BAEL-2541 - Guide to ProcessBuilder API

- Update test commands to work on windows
This commit is contained in:
Jonathan Paul Cook 2019-02-20 22:58:18 +01:00
parent f14c3fbab3
commit 1dac10b247
1 changed files with 181 additions and 159 deletions

View File

@ -1,159 +1,181 @@
package com.baeldung.processbuilder; package com.baeldung.processbuilder;
import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals; import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.BufferedReader;
import java.io.File; import java.io.BufferedReader;
import java.io.IOException; import java.io.File;
import java.io.InputStream; import java.io.IOException;
import java.io.InputStreamReader; import java.io.InputStream;
import java.lang.ProcessBuilder.Redirect; import java.io.InputStreamReader;
import java.nio.file.Files; import java.lang.ProcessBuilder.Redirect;
import java.util.Arrays; import java.nio.file.Files;
import java.util.List; import java.util.Arrays;
import java.util.Map; import java.util.List;
import java.util.concurrent.ExecutionException; import java.util.Map;
import java.util.stream.Collectors; import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import org.junit.Rule;
import org.junit.Test; import org.junit.Rule;
import org.junit.rules.TemporaryFolder; import org.junit.Test;
import org.junit.rules.TemporaryFolder;
public class ProcessBuilderUnitTest {
public class ProcessBuilderUnitTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Test
public void givenProcessBuilder_whenInvokeStart_thenSuccess() throws IOException, InterruptedException, ExecutionException { @Test
ProcessBuilder processBuilder = new ProcessBuilder("java", "-version"); public void givenProcessBuilder_whenInvokeStart_thenSuccess() throws IOException, InterruptedException, ExecutionException {
processBuilder.redirectErrorStream(true); ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
Process process = processBuilder.start();
List<String> results = readOutput(process.getInputStream());
assertThat("Results should not be empty", results, is(not(empty()))); List<String> results = readOutput(process.getInputStream());
assertThat("Results should contain java version: ", results, hasItem(containsString("java version"))); assertThat("Results should not be empty", results, is(not(empty())));
assertThat("Results should contain java version: ", results, hasItem(containsString("java version")));
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode); int exitCode = process.waitFor();
} assertEquals("No errors should be detected", 0, exitCode);
}
@Test
public void givenProcessBuilder_whenModifyEnvironment_thenSuccess() throws IOException, InterruptedException { @Test
ProcessBuilder processBuilder = new ProcessBuilder(); public void givenProcessBuilder_whenModifyEnvironment_thenSuccess() throws IOException, InterruptedException {
Map<String, String> environment = processBuilder.environment(); ProcessBuilder processBuilder = new ProcessBuilder();
environment.forEach((key, value) -> System.out.println(key + value)); Map<String, String> environment = processBuilder.environment();
environment.forEach((key, value) -> System.out.println(key + value));
environment.put("GREETING", "Hola Mundo");
environment.put("GREETING", "Hola Mundo");
processBuilder.command("/bin/bash", "-c", "echo $GREETING");
Process process = processBuilder.start(); List<String> command = getGreetingCommand();
processBuilder.command(command);
List<String> results = readOutput(process.getInputStream()); Process process = processBuilder.start();
assertThat("Results should not be empty", results, is(not(empty())));
assertThat("Results should contain a greeting ", results, hasItem(containsString("Hola Mundo"))); List<String> results = readOutput(process.getInputStream());
assertThat("Results should not be empty", results, is(not(empty())));
int exitCode = process.waitFor(); assertThat("Results should contain a greeting ", results, hasItem(containsString("Hola Mundo")));
assertEquals("No errors should be detected", 0, exitCode);
} int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
@Test }
public void givenProcessBuilder_whenModifyWorkingDir_thenSuccess() throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "ls"); @Test
public void givenProcessBuilder_whenModifyWorkingDir_thenSuccess() throws IOException, InterruptedException {
processBuilder.directory(new File("src")); List<String> command = getDirectoryListingCommand();
Process process = processBuilder.start(); ProcessBuilder processBuilder = new ProcessBuilder(command);
List<String> results = readOutput(process.getInputStream()); processBuilder.directory(new File("src"));
assertThat("Results should not be empty", results, is(not(empty()))); Process process = processBuilder.start();
assertThat("Results should contain directory listing: ", results, contains("main", "test"));
List<String> results = readOutput(process.getInputStream());
int exitCode = process.waitFor(); assertThat("Results should not be empty", results, is(not(empty())));
assertEquals("No errors should be detected", 0, exitCode); assertThat("Results should contain directory listing: ", results, hasItems(containsString("main"), containsString("test")));
}
int exitCode = process.waitFor();
@Test assertEquals("No errors should be detected", 0, exitCode);
public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessWriting() throws IOException, InterruptedException { }
ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
private List<String> getDirectoryListingCommand() {
processBuilder.redirectErrorStream(true); return isWindows() ? Arrays.asList("cmd.exe", "/c", "dir") : Arrays.asList("/bin/sh", "-c", "ls");
File log = tempFolder.newFile("java-version.log"); }
processBuilder.redirectOutput(log);
private List<String> getGreetingCommand() {
Process process = processBuilder.start(); return isWindows() ? Arrays.asList("cmd.exe", "/c", "echo %GREETING%") : Arrays.asList("/bin/bash", "-c", "echo $GREETING");
}
assertEquals("If redirected, should be -1 ", -1, process.getInputStream()
.read()); private List<String> getEchoCommand() {
int exitCode = process.waitFor(); return isWindows() ? Arrays.asList("cmd.exe", "/c", "echo hello") : Arrays.asList("/bin/sh", "-c", "echo hello");
assertEquals("No errors should be detected", 0, exitCode); }
List<String> lines = Files.lines(log.toPath()) private boolean isWindows() {
.collect(Collectors.toList()); return System.getProperty("os.name")
.toLowerCase()
assertThat("Results should not be empty", lines, is(not(empty()))); .startsWith("windows");
assertThat("Results should contain java version: ", lines, hasItem(containsString("java version"))); }
}
@Test
@Test public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessWriting() throws IOException, InterruptedException {
public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessAppending() throws IOException, InterruptedException { ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
processBuilder.redirectErrorStream(true);
File log = tempFolder.newFile("java-version-append.log"); File log = tempFolder.newFile("java-version.log");
processBuilder.redirectErrorStream(true); processBuilder.redirectOutput(log);
processBuilder.redirectOutput(Redirect.appendTo(log));
Process process = processBuilder.start();
Process process = processBuilder.start();
assertEquals("If redirected, should be -1 ", -1, process.getInputStream()
assertEquals("If redirected output, should be -1 ", -1, process.getInputStream() .read());
.read()); int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode); List<String> lines = Files.lines(log.toPath())
.collect(Collectors.toList());
List<String> lines = Files.lines(log.toPath())
.collect(Collectors.toList()); assertThat("Results should not be empty", lines, is(not(empty())));
assertThat("Results should contain java version: ", lines, hasItem(containsString("java version")));
assertThat("Results should not be empty", lines, is(not(empty()))); }
assertThat("Results should contain java version: ", lines, hasItem(containsString("java version")));
} @Test
public void givenProcessBuilder_whenRedirectStandardOutput_thenSuccessAppending() throws IOException, InterruptedException {
@Test ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");
public void givenProcessBuilder_whenStartingPipeline_thenSuccess() throws IOException, InterruptedException {
List<ProcessBuilder> builders = Arrays.asList( File log = tempFolder.newFile("java-version-append.log");
new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), processBuilder.redirectErrorStream(true);
new ProcessBuilder("wc", "-l")); processBuilder.redirectOutput(Redirect.appendTo(log));
List<Process> processes = ProcessBuilder.startPipeline(builders); Process process = processBuilder.start();
Process last = processes.get(processes.size() - 1);
assertEquals("If redirected output, should be -1 ", -1, process.getInputStream()
List<String> output = readOutput(last.getInputStream()); .read());
assertThat("Results should not be empty", output, is(not(empty())));
} int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
@Test
public void givenProcessBuilder_whenInheritIO_thenSuccess() throws IOException, InterruptedException { List<String> lines = Files.lines(log.toPath())
ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "echo hello"); .collect(Collectors.toList());
processBuilder.inheritIO(); assertThat("Results should not be empty", lines, is(not(empty())));
Process process = processBuilder.start(); assertThat("Results should contain java version: ", lines, hasItem(containsString("java version")));
}
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode); /* @Test
} public void givenProcessBuilder_whenStartingPipeline_thenSuccess() throws IOException, InterruptedException {
List<ProcessBuilder> builders = Arrays.asList(
private List<String> readOutput(InputStream inputStream) throws IOException { new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"),
try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) { new ProcessBuilder("wc", "-l"));
return output.lines()
.collect(Collectors.toList()); List<Process> processes = ProcessBuilder.startPipeline(builders);
} Process last = processes.get(processes.size() - 1);
}
List<String> output = readOutput(last.getInputStream());
} assertThat("Results should not be empty", output, is(not(empty())));
}*/
@Test
public void givenProcessBuilder_whenInheritIO_thenSuccess() throws IOException, InterruptedException {
List<String> command = getEchoCommand();
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.inheritIO();
Process process = processBuilder.start();
int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);
}
private List<String> readOutput(InputStream inputStream) throws IOException {
try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) {
return output.lines()
.collect(Collectors.toList());
}
}
}