Skip to content

Commit aa2822c

Browse files
amitabhmandalpauljervis
authored andcommitted
BAEL-1991 - Understanding Process (eugenp#4863)
* Understanding Process * Refactored names * Refactored junit names based on document guidance * Added alive * renamed junits as behavior Driven requirements * Added alive method junit * added waitFor method time interval junit * getOutputStream * changed exception * dummy commit * Dummy Commit with blank lines * Fixed assert and commented @test * fixed asserts * Replaced System.out.println with logging * replaced system.out.println with logging * Dummy commit to ensure clean build * Renamed Junit * Fixed extra spaces and typo * Uncommented @test for 3 methods
1 parent 201d616 commit aa2822c

5 files changed

Lines changed: 269 additions & 0 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.baeldung.java9.process;
2+
3+
import java.util.Scanner;
4+
import java.util.logging.Level;
5+
import java.util.logging.Logger;
6+
7+
public class ChildProcess {
8+
9+
public static void main(String[] args) {
10+
@SuppressWarnings("resource")
11+
Scanner input = new Scanner(System.in);
12+
Logger log = Logger.getLogger(ChildProcess.class.getName());
13+
log.log(Level.INFO, input.nextLine());
14+
}
15+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.baeldung.java9.process;
2+
3+
import java.util.logging.Level;
4+
import java.util.logging.Logger;
5+
6+
public class OutputStreamExample {
7+
8+
public static void main(String[] args) {
9+
Logger log = Logger.getLogger(OutputStreamExample.class.getName());
10+
log.log(Level.INFO, Integer.toString(sum(1,2)));
11+
}
12+
13+
public static int sum(int a, int b) {
14+
return a + b;
15+
}
16+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.baeldung.java9.process;
2+
3+
public class ProcessCompilationError {
4+
//This method has been written to generate error to display
5+
//how process errorStream() can consume error
6+
public static void();
7+
}
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
package com.baeldung.java9.process;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.io.OutputStreamWriter;
7+
import java.io.Writer;
8+
import java.util.Optional;
9+
import java.util.logging.Level;
10+
import java.util.logging.Logger;
11+
12+
public class ProcessUnderstanding {
13+
14+
public static int compileAndRunJavaProgram() throws IOException {
15+
Process process = Runtime.getRuntime()
16+
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
17+
process = Runtime.getRuntime()
18+
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
19+
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
20+
int value = Integer.parseInt(output.readLine());
21+
return value;
22+
}
23+
24+
public static String getErrorStreamExample() throws IOException {
25+
Process process = Runtime.getRuntime()
26+
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
27+
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
28+
String errorString = error.readLine();
29+
return errorString;
30+
}
31+
32+
public static void creatingNewProcess() throws IOException {
33+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
34+
Process process = builder.start();
35+
}
36+
37+
public static int filterProcessWithStreamsInSpecificRangeReturnCount() {
38+
return (int) ProcessHandle.allProcesses()
39+
.filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
40+
.count();
41+
}
42+
43+
public static void destroyingProcessCreatedBySameProcess() throws IOException, InterruptedException {
44+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
45+
Process process = builder.start();
46+
Thread.sleep(10000);
47+
process.destroy();
48+
}
49+
50+
public static void destroyingProcessCreatedByDifferentProcess() {
51+
// find out the process id of current running task by checking
52+
// task manager in windows and enter the integer value
53+
Optional<ProcessHandle> optionalProcessHandle = ProcessHandle.of(5232);
54+
ProcessHandle processHandle = optionalProcessHandle.get();
55+
processHandle.destroy();
56+
}
57+
58+
public static int waitForExample() throws IOException, InterruptedException {
59+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
60+
Process process = builder.start();
61+
return process.waitFor();
62+
}
63+
64+
public static int exitValueExample() throws IOException {
65+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
66+
Process process = builder.start();
67+
process.destroy();
68+
return process.exitValue();
69+
}
70+
71+
public static void destroyExample() throws IOException, InterruptedException {
72+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
73+
Process process = builder.start();
74+
Thread.sleep(10000);
75+
process.destroy();
76+
}
77+
78+
public static void destroyForciblyExample() throws IOException, InterruptedException {
79+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
80+
Process process = builder.start();
81+
Thread.sleep(10000);
82+
process.destroy();
83+
if (process.isAlive()) {
84+
process.destroyForcibly();
85+
}
86+
}
87+
88+
public static void outputStreamDemo() throws IOException, InterruptedException {
89+
Logger log = Logger.getLogger(ProcessUnderstanding.class.getName());
90+
Process pr = Runtime.getRuntime()
91+
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java");
92+
final Process process = Runtime.getRuntime()
93+
.exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess");
94+
try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) {
95+
w.write("send to child\n");
96+
}
97+
new Thread(() -> {
98+
try {
99+
int c;
100+
while ((c = process.getInputStream()
101+
.read()) != -1)
102+
System.out.write((byte) c);
103+
} catch (Exception e) {
104+
e.printStackTrace();
105+
}
106+
}).start();
107+
// send to child
108+
log.log(Level.INFO, "rc=" + process.waitFor());
109+
}
110+
}
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
package com.baeldung.java9.process;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
import static org.junit.Assert.assertTrue;
5+
import static org.junit.jupiter.api.Assertions.*;
6+
7+
import java.io.BufferedReader;
8+
import java.io.IOException;
9+
import java.io.InputStreamReader;
10+
import java.lang.String;
11+
import java.util.Optional;
12+
import java.util.concurrent.TimeUnit;
13+
import java.lang.Integer;
14+
15+
import org.junit.jupiter.api.Test;
16+
17+
class ProcessUnderstandingTest {
18+
19+
@Test
20+
public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException {
21+
Process process = Runtime.getRuntime()
22+
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
23+
process = Runtime.getRuntime()
24+
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
25+
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
26+
int value = Integer.parseInt(output.readLine());
27+
assertEquals(3, value);
28+
}
29+
30+
@Test
31+
public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException {
32+
Process process = Runtime.getRuntime()
33+
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
34+
process = Runtime.getRuntime()
35+
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
36+
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
37+
int value = Integer.parseInt(output.readLine());
38+
assertEquals(3, value);
39+
}
40+
41+
@Test
42+
public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException {
43+
Process process = Runtime.getRuntime()
44+
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
45+
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
46+
String errorString = error.readLine();
47+
assertNotNull(errorString);
48+
}
49+
50+
//@Test - windows specific
51+
public void givenSubProcess_thenStartSuccessIsAlive() throws IOException {
52+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
53+
assertTrue(builder.start().isAlive());
54+
}
55+
56+
//@Test - windows specific
57+
public void givenSubProcess_whenDestroying_thenProcessNotAlive() throws IOException, InterruptedException {
58+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
59+
Process process = builder.start();
60+
Thread.sleep(10000);
61+
process.destroy();
62+
assertFalse(process.isAlive());
63+
}
64+
65+
//@Test - windows specific
66+
public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException, InterruptedException {
67+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
68+
Process process = builder.start();
69+
Thread.sleep(10000);
70+
process.destroy();
71+
if (process.isAlive()) {
72+
process.destroyForcibly();
73+
}
74+
assertFalse(process.isAlive());
75+
}
76+
77+
//@Test - windows specific
78+
public void givenSubProcess_checkAlive() throws IOException, InterruptedException {
79+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
80+
Process process = builder.start();
81+
Thread.sleep(10000);
82+
process.destroy();
83+
assertFalse(process.isAlive());
84+
}
85+
86+
@Test
87+
public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() {
88+
Optional<ProcessHandle> optionalProcessHandle = ProcessHandle.of(5232);
89+
ProcessHandle processHandle = optionalProcessHandle.get();
90+
processHandle.destroy();
91+
assertFalse(processHandle.isAlive());
92+
}
93+
94+
//@Test - windows specific
95+
public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException {
96+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
97+
Process process = builder.start();
98+
assertThat(process.waitFor() >= 0);
99+
}
100+
101+
//@Test - windows specific
102+
public void givenSubProcess_whenCurrentThreadWaitsAndSubProcessNotTerminated_thenProcessWaitForReturnsFalse() throws IOException, InterruptedException {
103+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
104+
Process process = builder.start();
105+
assertFalse(process.waitFor(1, TimeUnit.SECONDS));
106+
}
107+
108+
//@Test - windows specific
109+
public void givenSubProcess_whenCurrentThreadWillNotWaitIndefinitelyforSubProcessToEnd_thenProcessExitValueReturnsGrt0() throws IOException {
110+
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
111+
Process process = builder.start();
112+
assertThat(process.exitValue() >= 0);
113+
}
114+
115+
@Test
116+
public void givenRunningProcesses_whenFilterOnProcessIdRange_thenGetSelectedProcessPid() {
117+
assertThat(((int) ProcessHandle.allProcesses()
118+
.filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
119+
.count()) > 0);
120+
}
121+
}

0 commit comments

Comments
 (0)