Skip to content

Commit b98e03b

Browse files
Merge pull request eugenp#616 from christian-raedel/craedel-shell-commands
Craedel shell commands
2 parents d8493fe + 2745a8f commit b98e03b

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package org.baeldung.java.shell;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
import java.io.*;
7+
import java.util.concurrent.Executors;
8+
import java.util.function.Consumer;
9+
10+
public class JavaProcessUnitTest {
11+
private static final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
12+
13+
private static class StreamGobbler implements Runnable {
14+
private InputStream inputStream;
15+
private Consumer<String> consumer;
16+
17+
public StreamGobbler(InputStream inputStream, Consumer<String> consumer) {
18+
this.inputStream = inputStream;
19+
this.consumer = consumer;
20+
}
21+
22+
@Override
23+
public void run() {
24+
new BufferedReader(new InputStreamReader(inputStream)).lines().forEach(consumer);
25+
}
26+
}
27+
28+
private Consumer<String> consumer = new Consumer<String>() {
29+
@Override
30+
public void accept(String s) {
31+
Assert.assertNotNull(s);
32+
}
33+
};
34+
35+
private String homeDirectory = System.getProperty("user.home");
36+
37+
@Test
38+
public void givenProcess_whenCreatingViaRuntime_shouldSucceed() throws Exception {
39+
Process process;
40+
if (IS_WINDOWS) {
41+
process = Runtime.getRuntime().exec(String.format("cmd.exe /c dir %s", homeDirectory));
42+
} else {
43+
process = Runtime.getRuntime().exec(String.format("sh -c ls %s", homeDirectory));
44+
}
45+
StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer);
46+
Executors.newSingleThreadExecutor().submit(streamGobbler);
47+
int exitCode = process.waitFor();
48+
Assert.assertEquals(0, exitCode);
49+
}
50+
51+
@Test
52+
public void givenProcess_whenCreatingViaProcessBuilder_shouldSucceed() throws Exception {
53+
ProcessBuilder builder = new ProcessBuilder();
54+
if (IS_WINDOWS) {
55+
builder.command("cmd.exe", "/c", "dir");
56+
} else {
57+
builder.command("sh", "-c", "ls");
58+
}
59+
builder.directory(new File(homeDirectory));
60+
Process process = builder.start();
61+
StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), consumer);
62+
Executors.newSingleThreadExecutor().submit(streamGobbler);
63+
int exitCode = process.waitFor();
64+
Assert.assertEquals(0, exitCode);
65+
}
66+
}

0 commit comments

Comments
 (0)