From 228598db3cd2f70f53720364b23501a0e44439dd Mon Sep 17 00:00:00 2001 From: Partha Sutradhar <53944765+zaxxio@users.noreply.github.com> Date: Sun, 3 Sep 2023 10:43:01 +0600 Subject: [PATCH] [BAEL-6481] - Stop Executing Further Code in Java (#14076) * Creating a Deep vs Shallow Copy of an Object in Java * [BAEL-6481]-Stop Executing Further Code in Java * [BAEL-6481] - Stop Executing Further Code in Java * [BAEL-6481] - Stop Executing Further Code in Java * [BAEL-6481] - Stop Executing Further Code in Java. * [BAEL-6481] - Stop Executing Further Code in Java. * [BAEL-6481] - Stop Executing Further Code in Java. * [BAEL-6481] Stop Executing Further Code in Java. * [BAEL-6481] Stop Executing Further Code in Java. Moved to core java numbers - 6 * [BAEL-6481] Stop Executing Further Code in Java. * [BAEL-6481] Stop Executing Further Code in Java. * [BAEL-6481] Stop Executing Further Code in Java. * [BAEL-6481] Stop Executing Further Code in Java. [Commented the Test cases] * [BAEL-6481] Stop Executing Further Code in Java. [Commented the Two Test] * [BAEL-6481] Stop Executing Further Code in Java. [Fixed Method Name's] --- .../stopexecution/InterruptThread.java | 13 +++ .../StopExecutionFurtherCode.java | 87 ++++++++++++++++++ .../StopExecutionFurtherCodeUnitTest.java | 90 +++++++++++++++++++ 3 files changed, 190 insertions(+) create mode 100644 core-java-modules/core-java-lang-6/src/main/java/com/baeldung/stopexecution/InterruptThread.java create mode 100644 core-java-modules/core-java-lang-6/src/main/java/com/baeldung/stopexecution/StopExecutionFurtherCode.java create mode 100644 core-java-modules/core-java-lang-6/src/test/java/com/baeldung/stopexecution/StopExecutionFurtherCodeUnitTest.java diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/stopexecution/InterruptThread.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/stopexecution/InterruptThread.java new file mode 100644 index 0000000000..7964ad9f52 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/stopexecution/InterruptThread.java @@ -0,0 +1,13 @@ +package com.baeldung.stopexecution; + +public class InterruptThread extends Thread { + @Override + public void run() { + while (!isInterrupted()) { + if (isInterrupted()) { + break; + } + // business logic + } + } +} diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/stopexecution/StopExecutionFurtherCode.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/stopexecution/StopExecutionFurtherCode.java new file mode 100644 index 0000000000..81abe15b5c --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/stopexecution/StopExecutionFurtherCode.java @@ -0,0 +1,87 @@ +package com.baeldung.stopexecution; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Locale; + +public class StopExecutionFurtherCode { + + boolean shouldContinue = true; + + int performTask(int a, int b) { + if (!shouldContinue) { + System.exit(0); + } + return a + b; + } + + void stop() { + this.shouldContinue = false; + } + + int calculateFactorial(int n) { + if (n <= 1) { + return 1; // base case + } + + return n * calculateFactorial(n - 1); + } + + int calculateSum(int[] x) { + int sum = 0; + for (int i = 0; i < 10; i++) { + if (x[i] < 0) { + break; + } + sum += x[i]; + } + return sum; + } + + T stopExecutionUsingException(T object) { + if (object instanceof Number) { + throw new IllegalArgumentException("Parameter can not be number."); + } + T upperCase = (T) String.valueOf(object) + .toUpperCase(Locale.ENGLISH); + return upperCase; + } + + int processLines(String[] lines) { + int statusCode = 0; + parser: + for (String line : lines) { + System.out.println("Processing line: " + line); + if (line.equals("stop")) { + System.out.println("Stopping parsing..."); + statusCode = -1; + break parser; // Stop parsing and exit the loop + } + System.out.println("Line processed."); + } + return statusCode; + } + + void download(String fileUrl, String destinationPath) throws MalformedURLException { + if (fileUrl == null || fileUrl.isEmpty() || destinationPath == null || destinationPath.isEmpty()) { + return; + } + // execute downloading + URL url = new URL(fileUrl); + try (InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(destinationPath)) { + byte[] buffer = new byte[1024]; + int bytesRead; + while ((bytesRead = in.read(buffer)) != -1) { + out.write(buffer, 0, bytesRead); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + + +} diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/stopexecution/StopExecutionFurtherCodeUnitTest.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/stopexecution/StopExecutionFurtherCodeUnitTest.java new file mode 100644 index 0000000000..9cdb1e71aa --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/stopexecution/StopExecutionFurtherCodeUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.stopexecution; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.net.MalformedURLException; + +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.jupiter.api.Test; +import org.junit.runners.MethodSorters; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class StopExecutionFurtherCodeUnitTest { + + + @Test + void givenExecution_whenStopIsNotCalled_thenTaskIsPerformed() { + StopExecutionFurtherCode stopExecution = new StopExecutionFurtherCode(); + int performedTask = stopExecution.performTask(10, 20); + Assert.assertEquals(30, performedTask); + } + + // This test case have been commented because, otherwise, the program will exit since System.exit(statusCode) is being used. + /*@Test + void givenExecution_whenStopIsCalled_thenTaskNotPerformed() { + StopExecutionFurtherCode stopExecution = new StopExecutionFurtherCode(); + stopExecution.stop(); + int performedTask = stopExecution.performTask(10, 20); + Assert.assertEquals(30, performedTask); + }*/ + + @Test + void givenWrongUrlAndPath_whenDownloadCalled_thenExecutionIsStopped() throws MalformedURLException { + StopExecutionFurtherCode stopExecutionFurtherCode = new StopExecutionFurtherCode(); + stopExecutionFurtherCode.download("", ""); + } + + @Test + void givenName_whenStopExecutionUsingExceptionCalled_thenNameIsConvertedToUpper() { + StopExecutionFurtherCode stopExecutionFurtherCode = new StopExecutionFurtherCode(); + String name = "John"; + String result1 = stopExecutionFurtherCode.stopExecutionUsingException(name); + Assert.assertEquals("JOHN", result1); + try { + Integer number1 = 10; + Assert.assertThrows(IllegalArgumentException.class, () -> { + int result = stopExecutionFurtherCode.stopExecutionUsingException(number1); + }); + } catch (Exception e) { + Assert.fail("Unexpected exception thrown: " + e.getMessage()); + } + } + + @Test + void givenBaseCase_whenStopExecutionWhenBaseCaseKnownCalled_thenFactorialIsCalculated() throws MalformedURLException { + StopExecutionFurtherCode stopExecutionFurtherCode = new StopExecutionFurtherCode(); + int factorial = stopExecutionFurtherCode.calculateFactorial(1); + Assert.assertEquals(1, factorial); + } + + @Test + void givenArrayWithNegative_whenStopExecutionInLoopCalled_thenSumIsCalculatedIgnoringNegatives() { + StopExecutionFurtherCode stopExecutionFurtherCode = new StopExecutionFurtherCode(); + int[] nums = { 1, 2, 3, -1, 1, 2, 3 }; + int sum = stopExecutionFurtherCode.calculateSum(nums); + Assert.assertEquals(6, sum); + } + + @Test + void givenThreadRunning_whenInterrupted_thenThreadExecutionIsStopped() throws InterruptedException { + InterruptThread stopExecution = new InterruptThread(); + stopExecution.start(); + Thread.sleep(2000); + stopExecution.interrupt(); + stopExecution.join(); + Assert.assertTrue(!stopExecution.isAlive()); + } + + @Test + void givenLinesWithStopLabel_whenStopExecutionLabeledLoopCalled_thenLoopExecutionIsStopped() { + StopExecutionFurtherCode furtherCode = new StopExecutionFurtherCode(); + final String[] lines = { "Line 1", "Line 2", "Line 3", "stop", "Line 4", "Line 5" }; + int statusCode = furtherCode.processLines(lines); + Assert.assertEquals(-1, statusCode); + } + +}