BAEL-1991 - Understanding Process (#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
This commit is contained in:
Amitabh Mandal 2018-08-30 23:38:21 +05:30 committed by pauljervis
parent 201d616c6b
commit aa2822c5fc
5 changed files with 269 additions and 0 deletions

View File

@ -0,0 +1,15 @@
package com.baeldung.java9.process;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ChildProcess {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
Logger log = Logger.getLogger(ChildProcess.class.getName());
log.log(Level.INFO, input.nextLine());
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.java9.process;
import java.util.logging.Level;
import java.util.logging.Logger;
public class OutputStreamExample {
public static void main(String[] args) {
Logger log = Logger.getLogger(OutputStreamExample.class.getName());
log.log(Level.INFO, Integer.toString(sum(1,2)));
}
public static int sum(int a, int b) {
return a + b;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.java9.process;
public class ProcessCompilationError {
//This method has been written to generate error to display
//how process errorStream() can consume error
public static void();
}

View File

@ -0,0 +1,110 @@
package com.baeldung.java9.process;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ProcessUnderstanding {
public static int compileAndRunJavaProgram() throws IOException {
Process process = Runtime.getRuntime()
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
process = Runtime.getRuntime()
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
int value = Integer.parseInt(output.readLine());
return value;
}
public static String getErrorStreamExample() throws IOException {
Process process = Runtime.getRuntime()
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String errorString = error.readLine();
return errorString;
}
public static void creatingNewProcess() throws IOException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
}
public static int filterProcessWithStreamsInSpecificRangeReturnCount() {
return (int) ProcessHandle.allProcesses()
.filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
.count();
}
public static void destroyingProcessCreatedBySameProcess() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
Thread.sleep(10000);
process.destroy();
}
public static void destroyingProcessCreatedByDifferentProcess() {
// find out the process id of current running task by checking
// task manager in windows and enter the integer value
Optional<ProcessHandle> optionalProcessHandle = ProcessHandle.of(5232);
ProcessHandle processHandle = optionalProcessHandle.get();
processHandle.destroy();
}
public static int waitForExample() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
return process.waitFor();
}
public static int exitValueExample() throws IOException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
process.destroy();
return process.exitValue();
}
public static void destroyExample() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
Thread.sleep(10000);
process.destroy();
}
public static void destroyForciblyExample() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
Thread.sleep(10000);
process.destroy();
if (process.isAlive()) {
process.destroyForcibly();
}
}
public static void outputStreamDemo() throws IOException, InterruptedException {
Logger log = Logger.getLogger(ProcessUnderstanding.class.getName());
Process pr = Runtime.getRuntime()
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java");
final Process process = Runtime.getRuntime()
.exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess");
try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) {
w.write("send to child\n");
}
new Thread(() -> {
try {
int c;
while ((c = process.getInputStream()
.read()) != -1)
System.out.write((byte) c);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
// send to child
log.log(Level.INFO, "rc=" + process.waitFor());
}
}

View File

@ -0,0 +1,121 @@
package com.baeldung.java9.process;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.String;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.lang.Integer;
import org.junit.jupiter.api.Test;
class ProcessUnderstandingTest {
@Test
public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException {
Process process = Runtime.getRuntime()
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
process = Runtime.getRuntime()
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
int value = Integer.parseInt(output.readLine());
assertEquals(3, value);
}
@Test
public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException {
Process process = Runtime.getRuntime()
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
process = Runtime.getRuntime()
.exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
int value = Integer.parseInt(output.readLine());
assertEquals(3, value);
}
@Test
public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException {
Process process = Runtime.getRuntime()
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String errorString = error.readLine();
assertNotNull(errorString);
}
//@Test - windows specific
public void givenSubProcess_thenStartSuccessIsAlive() throws IOException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
assertTrue(builder.start().isAlive());
}
//@Test - windows specific
public void givenSubProcess_whenDestroying_thenProcessNotAlive() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
Thread.sleep(10000);
process.destroy();
assertFalse(process.isAlive());
}
//@Test - windows specific
public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
Thread.sleep(10000);
process.destroy();
if (process.isAlive()) {
process.destroyForcibly();
}
assertFalse(process.isAlive());
}
//@Test - windows specific
public void givenSubProcess_checkAlive() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
Thread.sleep(10000);
process.destroy();
assertFalse(process.isAlive());
}
@Test
public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() {
Optional<ProcessHandle> optionalProcessHandle = ProcessHandle.of(5232);
ProcessHandle processHandle = optionalProcessHandle.get();
processHandle.destroy();
assertFalse(processHandle.isAlive());
}
//@Test - windows specific
public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
assertThat(process.waitFor() >= 0);
}
//@Test - windows specific
public void givenSubProcess_whenCurrentThreadWaitsAndSubProcessNotTerminated_thenProcessWaitForReturnsFalse() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
assertFalse(process.waitFor(1, TimeUnit.SECONDS));
}
//@Test - windows specific
public void givenSubProcess_whenCurrentThreadWillNotWaitIndefinitelyforSubProcessToEnd_thenProcessExitValueReturnsGrt0() throws IOException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
assertThat(process.exitValue() >= 0);
}
@Test
public void givenRunningProcesses_whenFilterOnProcessIdRange_thenGetSelectedProcessPid() {
assertThat(((int) ProcessHandle.allProcesses()
.filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
.count()) > 0);
}
}