From 601275a5c99c2b930afcfca9daf2ddb79568a6da Mon Sep 17 00:00:00 2001 From: Sam Gardner Date: Wed, 13 Sep 2023 15:39:17 +0100 Subject: [PATCH 01/13] BAEL-6811 Check if letter is emoji example code --- .../core-java-string-algorithms-3/pom.xml | 10 +++++ .../findemojis/FindEmojisUnitTest.java | 44 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index 7d4adeba92..1122cbec6d 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -23,6 +23,16 @@ commons-lang3 ${apache-commons-lang3.version} + + com.kcthota + emoji4j + 6.0 + + + com.vdurmont + emoji-java + 5.1.1 + diff --git a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java new file mode 100644 index 0000000000..2400e052b3 --- /dev/null +++ b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.findemojis; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.vdurmont.emoji.EmojiManager; + +import emoji4j.EmojiUtils; + +public class FindEmojisUnitTest { + + @Test + public void givenAWord_whenUsingEmoji4J_thenDetectEmoji() { + boolean emoji = EmojiUtils.isEmoji("\uD83D\uDC3B"); + assertTrue(emoji); + + boolean notEmoji = EmojiUtils.isEmoji("w"); + assertFalse(notEmoji); + } + + @Test + public void givenAWord_whenUsingEmojiJava_thenDetectEmoji() { + boolean emoji = EmojiManager.isEmoji("\uD83D\uDC3B"); + assertTrue(emoji); + + boolean notEmoji = EmojiManager.isEmoji("w"); + assertFalse(notEmoji); + } + + @Test + public void givenAWord_whenUsingRegex_thenDetectEmoji() { + String regexPattern = "[\uD800-\uDBFF\uDC00-\uDFFF]+"; + String emojiString = "\uD83D\uDC3B"; + boolean emoji = emojiString.matches(regexPattern); + assertTrue(emoji); + + String notEmojiString = "w"; + boolean notEmoji = notEmojiString.matches(regexPattern); + assertFalse(notEmoji); + } + +} From 1fe064e7438c317e4db45486da494ee0697c1ef1 Mon Sep 17 00:00:00 2001 From: Sam Gardner Date: Thu, 14 Sep 2023 15:06:43 +0100 Subject: [PATCH 02/13] BAEL-6811 Move folders --- .../core-java-string-algorithms-3/pom.xml | 10 ---------- core-java-modules/core-java-string-algorithms/pom.xml | 7 +++++++ .../com/baeldung/findemojis/FindEmojisUnitTest.java | 0 3 files changed, 7 insertions(+), 10 deletions(-) rename core-java-modules/{core-java-string-algorithms-3 => core-java-string-algorithms}/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java (100%) diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index 1122cbec6d..7d4adeba92 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -23,16 +23,6 @@ commons-lang3 ${apache-commons-lang3.version} - - com.kcthota - emoji4j - 6.0 - - - com.vdurmont - emoji-java - 5.1.1 - diff --git a/core-java-modules/core-java-string-algorithms/pom.xml b/core-java-modules/core-java-string-algorithms/pom.xml index 10d28feb2f..ad1124474a 100644 --- a/core-java-modules/core-java-string-algorithms/pom.xml +++ b/core-java-modules/core-java-string-algorithms/pom.xml @@ -39,6 +39,11 @@ emoji-java ${emoji-java.version} + + com.kcthota + emoji4j + 6.0 + @@ -52,6 +57,8 @@ + 8 + 8 0.4.0 4.0.0 diff --git a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java similarity index 100% rename from core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java rename to core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java From 39f235d8baf8a506f1048ec092e198436dca5938 Mon Sep 17 00:00:00 2001 From: Sam Gardner Date: Thu, 14 Sep 2023 15:56:39 +0100 Subject: [PATCH 03/13] Revert "BAEL-6811 Move folders" This reverts commit 1fe064e7438c317e4db45486da494ee0697c1ef1. --- .../core-java-string-algorithms-3/pom.xml | 10 ++++++++++ .../com/baeldung/findemojis/FindEmojisUnitTest.java | 0 core-java-modules/core-java-string-algorithms/pom.xml | 7 ------- 3 files changed, 10 insertions(+), 7 deletions(-) rename core-java-modules/{core-java-string-algorithms => core-java-string-algorithms-3}/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java (100%) diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index 7d4adeba92..1122cbec6d 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -23,6 +23,16 @@ commons-lang3 ${apache-commons-lang3.version} + + com.kcthota + emoji4j + 6.0 + + + com.vdurmont + emoji-java + 5.1.1 + diff --git a/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java similarity index 100% rename from core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java rename to core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java diff --git a/core-java-modules/core-java-string-algorithms/pom.xml b/core-java-modules/core-java-string-algorithms/pom.xml index ad1124474a..10d28feb2f 100644 --- a/core-java-modules/core-java-string-algorithms/pom.xml +++ b/core-java-modules/core-java-string-algorithms/pom.xml @@ -39,11 +39,6 @@ emoji-java ${emoji-java.version} - - com.kcthota - emoji4j - 6.0 - @@ -57,8 +52,6 @@ - 8 - 8 0.4.0 4.0.0 From 913f8f55005f3b1cf6fc719f8b22390afff7ce40 Mon Sep 17 00:00:00 2001 From: Sam Gardner Date: Thu, 14 Sep 2023 16:03:19 +0100 Subject: [PATCH 04/13] BAEL-6811 remove emoji4j usage --- core-java-modules/core-java-string-algorithms-3/pom.xml | 5 ----- .../java/com/baeldung/findemojis/FindEmojisUnitTest.java | 9 --------- 2 files changed, 14 deletions(-) diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index 1122cbec6d..9c704c9f40 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -23,11 +23,6 @@ commons-lang3 ${apache-commons-lang3.version} - - com.kcthota - emoji4j - 6.0 - com.vdurmont emoji-java diff --git a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java index 2400e052b3..2c1a43fdaa 100644 --- a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java +++ b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java @@ -11,15 +11,6 @@ import emoji4j.EmojiUtils; public class FindEmojisUnitTest { - @Test - public void givenAWord_whenUsingEmoji4J_thenDetectEmoji() { - boolean emoji = EmojiUtils.isEmoji("\uD83D\uDC3B"); - assertTrue(emoji); - - boolean notEmoji = EmojiUtils.isEmoji("w"); - assertFalse(notEmoji); - } - @Test public void givenAWord_whenUsingEmojiJava_thenDetectEmoji() { boolean emoji = EmojiManager.isEmoji("\uD83D\uDC3B"); From f0719f76a7762d67774c37a41d4d3d70dd17bc9d Mon Sep 17 00:00:00 2001 From: Sam Gardner Date: Thu, 14 Sep 2023 16:09:18 +0100 Subject: [PATCH 05/13] BAEL-6811 remove unused import --- .../test/java/com/baeldung/findemojis/FindEmojisUnitTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java index 2c1a43fdaa..3cd5b1ba97 100644 --- a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java +++ b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/findemojis/FindEmojisUnitTest.java @@ -7,8 +7,6 @@ import org.junit.Test; import com.vdurmont.emoji.EmojiManager; -import emoji4j.EmojiUtils; - public class FindEmojisUnitTest { @Test From dab5b25f7e643cb48a511ae45c1cc939ede3494e Mon Sep 17 00:00:00 2001 From: Chrys Exaucet Date: Mon, 18 Sep 2023 02:58:54 +0000 Subject: [PATCH 06/13] BAEL-4091: Intro to Gradle Lint Plugin (#14674) --- gradle-modules/gradle-5/build.gradle | 19 +++++++++++++------ .../gradle-5/gradle-lint-intro.gradle | 6 ++++++ .../gradle-5/gradle-lint-intro/.gitignore | 1 + .../gradle-5/gradle-lint-intro/build.gradle | 15 +++++++++++++++ .../gradle/wrapper/gradle-wrapper.properties | 2 +- gradle-modules/gradle-5/lint.gradle | 16 ++++++++++++++++ gradle-modules/gradle-5/settings.gradle | 3 ++- 7 files changed, 54 insertions(+), 8 deletions(-) create mode 100644 gradle-modules/gradle-5/gradle-lint-intro.gradle create mode 100644 gradle-modules/gradle-5/gradle-lint-intro/.gitignore create mode 100644 gradle-modules/gradle-5/gradle-lint-intro/build.gradle create mode 100644 gradle-modules/gradle-5/lint.gradle diff --git a/gradle-modules/gradle-5/build.gradle b/gradle-modules/gradle-5/build.gradle index 84cf05bad6..bc3f233f99 100644 --- a/gradle-modules/gradle-5/build.gradle +++ b/gradle-modules/gradle-5/build.gradle @@ -1,14 +1,21 @@ -plugins{ - id "nebula.lint" version "16.9.0" +plugins { + id "nebula.lint" version "18.1.0" } + description = "Gradle 5 root project" allprojects { - apply plugin :"java" - apply plugin :"nebula.lint" + apply plugin: "java" + apply plugin: "nebula.lint" gradleLint { - rules=['unused-dependency'] + rules = [ + // 'unused-dependency', + // 'dependency-parentheses', + // 'undeclared-dependency', + // 'minimum-dependency-version' + ] reportFormat = 'text' + reportOnlyFixableViolations = true } group = "com.baeldung" version = "0.0.1" @@ -16,6 +23,6 @@ allprojects { targetCompatibility = "1.8" repositories { - jcenter() + mavenCentral() } } \ No newline at end of file diff --git a/gradle-modules/gradle-5/gradle-lint-intro.gradle b/gradle-modules/gradle-5/gradle-lint-intro.gradle new file mode 100644 index 0000000000..4b919c21e8 --- /dev/null +++ b/gradle-modules/gradle-5/gradle-lint-intro.gradle @@ -0,0 +1,6 @@ +allprojects { + apply plugin: "nebula.lint" + gradleLint { + rules = ['dependency-parenthesis'] + } +} \ No newline at end of file diff --git a/gradle-modules/gradle-5/gradle-lint-intro/.gitignore b/gradle-modules/gradle-5/gradle-lint-intro/.gitignore new file mode 100644 index 0000000000..84c048a73c --- /dev/null +++ b/gradle-modules/gradle-5/gradle-lint-intro/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/gradle-modules/gradle-5/gradle-lint-intro/build.gradle b/gradle-modules/gradle-5/gradle-lint-intro/build.gradle new file mode 100644 index 0000000000..fab83bfeec --- /dev/null +++ b/gradle-modules/gradle-5/gradle-lint-intro/build.gradle @@ -0,0 +1,15 @@ + +description = "Introduction to Gradle Lint Plugin" + +ext { + awsVersion = '2.20.83' +} + + +dependencies { + implementation platform("software.amazon.awssdk:bom:$awsVersion") + testImplementation('junit:junit:4.13.1') + gradleLint.ignore('unused-dependency', 'dependency-parentheses') { + implementation('software.amazon.awssdk:sts') + } +} diff --git a/gradle-modules/gradle-5/gradle/wrapper/gradle-wrapper.properties b/gradle-modules/gradle-5/gradle/wrapper/gradle-wrapper.properties index 4c46317507..7666e22b54 100644 --- a/gradle-modules/gradle-5/gradle/wrapper/gradle-wrapper.properties +++ b/gradle-modules/gradle-5/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip diff --git a/gradle-modules/gradle-5/lint.gradle b/gradle-modules/gradle-5/lint.gradle new file mode 100644 index 0000000000..7fc8ca780e --- /dev/null +++ b/gradle-modules/gradle-5/lint.gradle @@ -0,0 +1,16 @@ +import com.netflix.nebula.lint.plugin.GradleLintPlugin + +initscript { + repositories { mavenCentral() } + dependencies { + classpath 'com.netflix.nebula:gradle-lint-plugin:18.1.0' + } +} + +allprojects { + apply plugin: GradleLintPlugin + gradleLint { + rules=[] + alwaysRun= false + } +} \ No newline at end of file diff --git a/gradle-modules/gradle-5/settings.gradle b/gradle-modules/gradle-5/settings.gradle index c73af319a3..3173a23d5c 100644 --- a/gradle-modules/gradle-5/settings.gradle +++ b/gradle-modules/gradle-5/settings.gradle @@ -2,4 +2,5 @@ rootProject.name='gradle-5' include 'java-exec' include 'unused-dependencies' include 'source-sets' -include 'cmd-line-args' \ No newline at end of file +include 'cmd-line-args' +include 'gradle-lint-intro' \ No newline at end of file From 88139c2a9d12efbb3ba77f2b9a55fd521a641d3d Mon Sep 17 00:00:00 2001 From: Gaetano Piazzolla Date: Mon, 18 Sep 2023 10:00:51 +0200 Subject: [PATCH 07/13] JAVA-21833 | updated parent (#14782) --- spring-boot-modules/spring-boot-aws/pom.xml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/spring-boot-modules/spring-boot-aws/pom.xml b/spring-boot-modules/spring-boot-aws/pom.xml index 815766a846..460acae247 100644 --- a/spring-boot-modules/spring-boot-aws/pom.xml +++ b/spring-boot-modules/spring-boot-aws/pom.xml @@ -9,10 +9,11 @@ spring-boot-aws spring-boot-aws + - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT + org.springframework.boot + spring-boot-starter-parent + 2.7.11 From 39f5f3cdd745dbec6f14356b07e5f7636b847763 Mon Sep 17 00:00:00 2001 From: Sam Gardner Date: Mon, 18 Sep 2023 10:41:36 +0100 Subject: [PATCH 08/13] BAEL-6811 extract dependecy version number --- core-java-modules/core-java-string-algorithms-3/pom.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index 9c704c9f40..536175acc2 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -26,7 +26,7 @@ com.vdurmont emoji-java - 5.1.1 + ${emoji-java.version} @@ -57,6 +57,7 @@ 11 1.7 3.12.0 + 5.1.1 \ No newline at end of file From d6db7fd6e74fe136f24c7ddec3458e0bf6e7070b Mon Sep 17 00:00:00 2001 From: Bhaskar Ghosh Dastidar Date: Mon, 18 Sep 2023 22:56:37 +0530 Subject: [PATCH 09/13] [BAEL-6960] value based class (#14785) * [BAEL-6960] value based class * [BAEL-6960] value based class * [BAEL-6960] value based class --------- Co-authored-by: Bhaskar --- .../com/baeldung/value_based_class/Point.java | 49 +++++++++++++++++++ .../ValueBasedClassUnitTest.java | 41 ++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 core-java-modules/core-java-16/src/main/java/com/baeldung/value_based_class/Point.java create mode 100644 core-java-modules/core-java-16/src/test/java/com/baeldung/value_based_class/ValueBasedClassUnitTest.java diff --git a/core-java-modules/core-java-16/src/main/java/com/baeldung/value_based_class/Point.java b/core-java-modules/core-java-16/src/main/java/com/baeldung/value_based_class/Point.java new file mode 100644 index 0000000000..13e2238274 --- /dev/null +++ b/core-java-modules/core-java-16/src/main/java/com/baeldung/value_based_class/Point.java @@ -0,0 +1,49 @@ +package com.baeldung.value_based_class; + +import java.util.Objects; + +import jdk.internal.ValueBased; + +/** + * This class is written with the intention that it can serve as an example of + * what a Value-based class could be. + */ + +@ValueBased +public final class Point { + private final int x; + private final int y; + private final int z; + + private static Point ORIGIN = new Point(0, 0, 0); + + private Point(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } + + public static Point valueOfPoint(int x, int y, int z) { + // returns a cached instance if it is origin, or a new instance + if (isOrigin(x, y, z)) + return ORIGIN; + return new Point(x, y, z); + } + + @Override + public boolean equals(Object other) { + if (other == null || getClass() != other.getClass()) + return false; + Point point = (Point) other; + return x == point.x && y == point.y && z == point.z; + } + + @Override + public int hashCode() { + return Objects.hash(x, y, z); + } + + private static boolean isOrigin(int x, int y, int z) { + return x == 0 && y == 0 && z == 0; + } +} diff --git a/core-java-modules/core-java-16/src/test/java/com/baeldung/value_based_class/ValueBasedClassUnitTest.java b/core-java-modules/core-java-16/src/test/java/com/baeldung/value_based_class/ValueBasedClassUnitTest.java new file mode 100644 index 0000000000..781f368982 --- /dev/null +++ b/core-java-modules/core-java-16/src/test/java/com/baeldung/value_based_class/ValueBasedClassUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.value_based_class; + +import org.junit.Assert; +import org.junit.Test; + +public class ValueBasedClassUnitTest { + @Test + public void givenAutoboxedAndPrimitive_whenCompared_thenReturnEquals() { + int primitive_a = 125; + Integer obj_a = 125; // this is autoboxed + Assert.assertSame(primitive_a, obj_a); + } + + @Test + public void givenValueBasedPoint_whenCreated_thenReturnsObjects() { + Point p1 = Point.valueOfPoint(1, 2, 3); + Point p2 = Point.valueOfPoint(2, 3, 4); + + Assert.assertNotEquals(p1, p2); + } + + @Test + public void givenValueBasedPoint_whenCompared_thenReturnEquals() { + Point p1 = Point.valueOfPoint(1, 2, 3); + Point p2 = Point.valueOfPoint(1, 2, 3); + + Assert.assertEquals(p1, p2); + } + + @Test + public void givenValueBasedPoint_whenOrigin_thenReturnCachedInstance() { + Point p1 = Point.valueOfPoint(0, 0, 0); + Point p2 = Point.valueOfPoint(0, 0, 0); + Point p3 = Point.valueOfPoint(1, 2, 3); + + // the following should not be assumed for value-based classes + + Assert.assertTrue(p1 == p2); + Assert.assertFalse(p1 == p3); + } +} From 1e7471a2b3359d995a77797e8f36f0b99ca3bcc7 Mon Sep 17 00:00:00 2001 From: Eugene Kovko <37694937+eukovko@users.noreply.github.com> Date: Mon, 18 Sep 2023 19:36:58 +0200 Subject: [PATCH 10/13] BAEL-6822: Difference between Arrays.sort() and Collections.sort() (#14787) --- .../NonStableSortExample.java | 26 +++++++ .../ObjectOverheadBenchmark.java | 56 +++++++++++++++ .../PerformanceBenchmark.java | 51 +++++++++++++ .../StableSortExample.java | 23 ++++++ .../baeldung/collectionsvsarrays/Task.java | 30 ++++++++ .../baeldung/collectionsvsarrays/Tasks.java | 30 ++++++++ .../sorting/MergeSort.java | 47 ++++++++++++ .../sorting/Quicksort.java | 72 +++++++++++++++++++ 8 files changed, 335 insertions(+) create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/NonStableSortExample.java create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/ObjectOverheadBenchmark.java create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/PerformanceBenchmark.java create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/StableSortExample.java create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/Task.java create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/Tasks.java create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/sorting/MergeSort.java create mode 100644 core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/sorting/Quicksort.java diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/NonStableSortExample.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/NonStableSortExample.java new file mode 100644 index 0000000000..cd754489a6 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/NonStableSortExample.java @@ -0,0 +1,26 @@ +package com.baeldung.collectionsvsarrays; + +import com.baeldung.collectionsvsarrays.sorting.Quicksort; +import java.util.Comparator; +import java.util.List; + +public class NonStableSortExample { + + + + public static void main(String[] args) { + List tasks = Tasks.supplier.get(); + Quicksort.sort(tasks, Comparator.comparingInt(Task::getPriority)); + System.out.println("After sorting by priority:"); + for (Task task : tasks) { + System.out.println(task); + } + Quicksort.sort(tasks, Comparator.comparing(Task::getDueDate)); + System.out.println("\nAfter sorting by due date:"); + for (Task task : tasks) { + System.out.println(task); + } + } + + +} diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/ObjectOverheadBenchmark.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/ObjectOverheadBenchmark.java new file mode 100644 index 0000000000..9a8adff507 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/ObjectOverheadBenchmark.java @@ -0,0 +1,56 @@ +package com.baeldung.collectionsvsarrays; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +@Measurement(iterations = 2, time = 10, timeUnit = TimeUnit.MINUTES) +@Warmup(iterations = 5, time = 10) +@Fork(value = 2) +public class ObjectOverheadBenchmark { + + private static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current(); + + @State(Scope.Benchmark) + public static class Input { + public Supplier> randomNumbers = () -> RANDOM.ints().limit(10000).boxed().collect(Collectors.toList()); + } + + @Benchmark + @BenchmarkMode(Mode.Throughput) + public void sortingPrimitiveArray(Input input, Blackhole blackhole) { + final int[] array = input.randomNumbers.get().stream().mapToInt(Integer::intValue).toArray(); + Arrays.sort(array); + final List result = Arrays.stream(array).boxed().collect(Collectors.toList()); + blackhole.consume(result); + } + + @Benchmark + @BenchmarkMode(Mode.Throughput) + public void sortingObjectArray(Input input, Blackhole blackhole) { + final Integer[] array = input.randomNumbers.get().toArray(new Integer[0]); + Arrays.sort(array); + blackhole.consume(array); + } + + @Benchmark + @BenchmarkMode(Mode.Throughput) + public void sortingObjects(Input input, Blackhole blackhole) { + final List list = input.randomNumbers.get(); + Collections.sort(list); + blackhole.consume(list); + } +} diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/PerformanceBenchmark.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/PerformanceBenchmark.java new file mode 100644 index 0000000000..6e645b0fb9 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/PerformanceBenchmark.java @@ -0,0 +1,51 @@ +package com.baeldung.collectionsvsarrays; + +import com.baeldung.collectionsvsarrays.sorting.MergeSort; +import com.baeldung.collectionsvsarrays.sorting.Quicksort; +import java.util.Random; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import java.util.stream.IntStream; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.Warmup; + +@Measurement(iterations = 2, time = 10, timeUnit = TimeUnit.MINUTES) +@Warmup(iterations = 5, time = 10) +public class PerformanceBenchmark { + + private static final Random RANDOM = new Random(); + private static final int ARRAY_SIZE = 10000; + private static final int[] randomNumbers = RANDOM.ints(ARRAY_SIZE).toArray(); + private static final int[] sameNumbers = IntStream.generate(() -> 42).limit(ARRAY_SIZE).toArray(); + public static final Supplier randomNumbersSupplier = randomNumbers::clone; + public static final Supplier sameNumbersSupplier = sameNumbers::clone; + + @Benchmark + @BenchmarkMode(Mode.Throughput) + @Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-quick-sort-same-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"}) + public void quickSortSameNumber() { + Quicksort.sort(sameNumbersSupplier.get()); + } + @Benchmark + @BenchmarkMode(Mode.Throughput) + @Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-quick-sort-random-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"}) + public void quickSortRandomNumber() { + Quicksort.sort(randomNumbersSupplier.get()); + } + @Benchmark + @BenchmarkMode(Mode.Throughput) + @Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-merge-sort-same-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"}) + public void mergeSortSameNumber() { + MergeSort.sort(sameNumbersSupplier.get()); + } + @Benchmark + @BenchmarkMode(Mode.Throughput) + @Fork(value = 1, jvmArgs = {"-Xlog:gc:file=gc-logs-merge-sort-random-number-%t.txt,filesize=900m -Xmx6gb -Xms6gb"}) + public void mergeSortRandomNumber() { + MergeSort.sort(randomNumbersSupplier.get()); + } +} diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/StableSortExample.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/StableSortExample.java new file mode 100644 index 0000000000..336673bac8 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/StableSortExample.java @@ -0,0 +1,23 @@ +package com.baeldung.collectionsvsarrays; + + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +public class StableSortExample { + + public static void main(String[] args) { + final List tasks = Tasks.supplier.get(); + Collections.sort(tasks, Comparator.comparingInt(Task::getPriority)); + System.out.println("After sorting by priority:"); + for (Task task : tasks) { + System.out.println(task); + } + Collections.sort(tasks, Comparator.comparing(Task::getDueDate)); + System.out.println("\nAfter sorting by due date:"); + for (Task task : tasks) { + System.out.println(task); + } + } +} diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/Task.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/Task.java new file mode 100644 index 0000000000..133c39ccd2 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/Task.java @@ -0,0 +1,30 @@ +package com.baeldung.collectionsvsarrays; + +public class Task { + private final long id; + private final int priority; + private final String dueDate; + + public Task(final long id, int priority, String dueDate) { + this.id = id; + this.priority = priority; + this.dueDate = dueDate; + } + + @Override + public String toString() { + return String.format("Task: #%-2d | Priority: %d | Due Date: %s", getId(), getPriority(), getDueDate()); + } + + public int getPriority() { + return priority; + } + + public String getDueDate() { + return dueDate; + } + + private long getId() { + return id; + } +} diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/Tasks.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/Tasks.java new file mode 100644 index 0000000000..fc413f549f --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/Tasks.java @@ -0,0 +1,30 @@ +package com.baeldung.collectionsvsarrays; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +public class Tasks { + + private static final List tasks; + public static final Supplier> supplier; + + static { + tasks = new ArrayList<>(); + tasks.add(new Task(1, 1, "2023-09-01")); + tasks.add(new Task(2, 2, "2023-08-30")); + tasks.add(new Task(3, 1, "2023-08-29")); + tasks.add(new Task(4, 2, "2023-09-02")); + tasks.add(new Task(5, 3, "2023-09-05")); + tasks.add(new Task(6, 1, "2023-09-03")); + tasks.add(new Task(7, 3, "2023-08-28")); + tasks.add(new Task(8, 2, "2023-09-01")); + tasks.add(new Task(9, 1, "2023-08-28")); + tasks.add(new Task(10, 2, "2023-09-04")); + tasks.add(new Task(11, 3, "2023-08-31")); + tasks.add(new Task(12, 1, "2023-08-30")); + tasks.add(new Task(13, 3, "2023-09-02")); + + supplier = () -> new ArrayList<>(tasks); + } +} diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/sorting/MergeSort.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/sorting/MergeSort.java new file mode 100644 index 0000000000..6078db50e0 --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/sorting/MergeSort.java @@ -0,0 +1,47 @@ +package com.baeldung.collectionsvsarrays.sorting; + +public class MergeSort { + + public static void sort(int[] a) { + sort(a, a.length); + } + public static void sort(int[] a, int n) { + if (n < 2) { + return; + } + int mid = n / 2; + int[] l = new int[mid]; + int[] r = new int[n - mid]; + + for (int i = 0; i < mid; i++) { + l[i] = a[i]; + } + for (int i = mid; i < n; i++) { + r[i - mid] = a[i]; + } + sort(l, mid); + sort(r, n - mid); + + merge(a, l, r, mid, n - mid); + } + private static void merge( + int[] a, int[] l, int[] r, int left, int right) { + + int i = 0, j = 0, k = 0; + while (i < left && j < right) { + if (l[i] <= r[j]) { + a[k++] = l[i++]; + } + else { + a[k++] = r[j++]; + } + } + while (i < left) { + a[k++] = l[i++]; + } + while (j < right) { + a[k++] = r[j++]; + } + } + +} diff --git a/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/sorting/Quicksort.java b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/sorting/Quicksort.java new file mode 100644 index 0000000000..eab47b901b --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/main/java/com/baeldung/collectionsvsarrays/sorting/Quicksort.java @@ -0,0 +1,72 @@ +package com.baeldung.collectionsvsarrays.sorting; + +import java.util.Comparator; +import java.util.List; + +public class Quicksort { + + public static void sort(int arr[]) { + sort(arr, 0, arr.length - 1); + } + public static void sort(int arr[], int begin, int end) { + if (begin < end) { + int partitionIndex = partition(arr, begin, end); + + sort(arr, begin, partitionIndex-1); + sort(arr, partitionIndex+1, end); + } + } + private static int partition(int arr[], int begin, int end) { + int pivot = arr[end]; + int i = (begin-1); + + for (int j = begin; j < end; j++) { + if (arr[j] <= pivot) { + i++; + + int swapTemp = arr[i]; + arr[i] = arr[j]; + arr[j] = swapTemp; + } + } + + int swapTemp = arr[i+1]; + arr[i+1] = arr[end]; + arr[end] = swapTemp; + + return i+1; + } + + public static void sort(List list, Comparator comparator) { + sort(list, 0, list.size() - 1, comparator); + } + public static void sort(List list, int low, int high, Comparator comparator) { + if (low < high) { + int partitionIndex = partition(list, low, high, comparator); + + sort(list, low, partitionIndex - 1, comparator); + sort(list, partitionIndex + 1, high, comparator); + } + } + + private static int partition(List list, int begin, int end, Comparator comparator) { + T pivot = list.get(end); + int i = (begin-1); + + for (int j = begin; j < end; j++) { + if (comparator.compare(list.get(j), pivot) <= 0) { + i++; + + T swapTemp = list.get(i); + list.set(i, list.get(j)); + list.set(j, swapTemp); + } + } + + T swapTemp = list.get(i+1); + list.set(i+1,list.get(end)); + list.set(end, swapTemp); + + return i+1; + } +} From 5bcbd9dc00a3ff68c34ad0c3bbcce9c60c56b472 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Tue, 19 Sep 2023 15:38:32 +0300 Subject: [PATCH 11/13] JAVA-24237 Update "Spring Data MongoDB" article (#14772) Co-authored-by: timis1 --- .../spring-data-mongodb/pom.xml | 44 +++---------------- .../MongoTransactionTemplateLiveTest.java | 1 + .../MongoTransactionalLiveTest.java | 1 + 3 files changed, 8 insertions(+), 38 deletions(-) diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index 87cf1acaf8..a59fcff3d9 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -8,31 +8,19 @@ com.baeldung - parent-spring-5 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-spring-5 + ../../parent-boot-2 - org.springframework.data - spring-data-mongodb - ${org.springframework.data.version} + org.springframework.boot + spring-boot-starter-data-mongodb - org.mongodb - mongodb-driver-sync - ${mongodb-driver.version} - - - org.mongodb - mongodb-driver-reactivestreams - ${mongodb-reactivestreams.version} - - - io.projectreactor - reactor-core - ${projectreactor.version} + org.springframework.boot + spring-boot-starter-data-mongodb-reactive io.projectreactor @@ -40,23 +28,6 @@ ${projectreactor.version} test - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - - - - org.springframework - spring-test - ${spring.version} - test - com.querydsl querydsl-mongodb @@ -103,12 +74,9 @@ - 3.4.7 5.0.0 1.1.3 - 4.1.0 3.5.4 - 4.6.1 4.6.3 diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateLiveTest.java index 53b2c7a0e7..a53dfc6663 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionTemplateLiveTest.java @@ -28,6 +28,7 @@ import com.baeldung.model.User; * * This test requires: * * mongodb instance running on the environment + * Run the src/live-test/resources/live-test-setup.sh * */ @RunWith(SpringJUnit4ClassRunner.class) diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java index d92296beab..adc31ffea2 100644 --- a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/transaction/MongoTransactionalLiveTest.java @@ -26,6 +26,7 @@ import com.baeldung.repository.UserRepository; * * This test requires: * * mongodb instance running on the environment + * Run the src/live-test/resources/live-test-setup.sh * */ @RunWith(SpringJUnit4ClassRunner.class) From 556002e8d18f0dd0c6d913909136c40b0db36b0c Mon Sep 17 00:00:00 2001 From: Hangga Aji Sayekti Date: Tue, 19 Sep 2023 19:53:41 +0700 Subject: [PATCH 12/13] EOF Detection | bazeniancode@gmail.com | Hangga Aji Sayekti (#14738) * [Add] add from my experiment repo github.com/hangga/eof-detection * [Update] reorder test * [Update] add close() * [Update] try with resource * [update] be careful with typo --- .../baeldung/eofdetections/EOFDetection.java | 60 ++++++++++++++ .../eofdetections/EOFDetectionUnitTest.java | 80 +++++++++++++++++++ 2 files changed, 140 insertions(+) create mode 100644 core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/eofdetections/EOFDetection.java create mode 100644 core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/eofdetections/EOFDetectionUnitTest.java diff --git a/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/eofdetections/EOFDetection.java b/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/eofdetections/EOFDetection.java new file mode 100644 index 0000000000..c6302a3fc9 --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/eofdetections/EOFDetection.java @@ -0,0 +1,60 @@ +package com.baeldung.eofdetections; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.util.*; + +public class EOFDetection { + + public String readWithFileInputStream(String pathFile) throws IOException { + try (FileInputStream fis = new FileInputStream(pathFile); + ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + int data; + while ((data = fis.read()) != -1) { + baos.write(data); + } + return baos.toString(); + } + } + + public String readWithBufferedReader(String pathFile) throws IOException { + try (FileInputStream fis = new FileInputStream(pathFile); + InputStreamReader isr = new InputStreamReader(fis); + BufferedReader reader = new BufferedReader(isr)) { + StringBuilder actualContent = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + actualContent.append(line); + } + return actualContent.toString(); + } + } + + public String readWithScanner(String pathFile) throws IOException { + File file = new File(pathFile); + Scanner scanner = new Scanner(file); + StringBuilder actualContent = new StringBuilder(); + while (scanner.hasNext()) { + String line = scanner.nextLine(); + actualContent.append(line); + } + scanner.close(); + return actualContent.toString(); + } + + public String readFileWithFileChannelAndByteBuffer(String pathFile) throws IOException { + try (FileInputStream fis = new FileInputStream(pathFile); + FileChannel channel = fis.getChannel()) { + + ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); + while (channel.read(buffer) != -1) { + buffer.flip(); + buffer.clear(); + } + return StandardCharsets.UTF_8.decode(buffer).toString(); + } + } +} + diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/eofdetections/EOFDetectionUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/eofdetections/EOFDetectionUnitTest.java new file mode 100644 index 0000000000..525b242bf9 --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/eofdetections/EOFDetectionUnitTest.java @@ -0,0 +1,80 @@ +package com.baeldung.eofdetections; + +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class EOFDetectionUnitTest { + + static final String LOREM_IPSUM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"; + String pathToFile = "sample.txt"; // init sample file path + EOFDetection eofDetection = new EOFDetection(); + @Test + @Order(1) + public void givenDummyText_whenReadWithFileInputStream_returnText() { + try { + String actualText = eofDetection.readWithFileInputStream(pathToFile); + assertEquals(LOREM_IPSUM, actualText); + } catch (IOException e) { + fail(e.getMessage()); + } + } + + @Test + @Order(2) + public void givenDummyText_whenReadFileWithBufferedReader_returnText() { + try { + String actualText = eofDetection.readWithBufferedReader(pathToFile); + assertEquals(LOREM_IPSUM, actualText); + } catch (IOException e) { + fail(e.getMessage()); + } + } + + @Test + @Order(3) + public void givenDummyText_whenReadFileWithScanner_returnText() { + try { + String actualText = eofDetection.readWithScanner(pathToFile); + assertEquals(LOREM_IPSUM, actualText); + } catch (IOException e) { + fail(e.getMessage()); + } + } + + @Test + @Order(4) + public void givenDummyText_whenReadFileWithFileChannelAndByteBuffer_returnText() { + try { + String actualText = eofDetection.readFileWithFileChannelAndByteBuffer(pathToFile); + assertEquals(LOREM_IPSUM, actualText); + } catch (IOException e) { + fail(e.getMessage()); + } + } + @Test + @Order(0) + public void prepareFileForTest() { + File file = new File(pathToFile); + + if (!file.exists()) { + try { + file.createNewFile(); + FileWriter writer = new FileWriter(file); + writer.write(LOREM_IPSUM); + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } +} From 2e58e30ffa7490fa11cbd6c553893df00c0f5e70 Mon Sep 17 00:00:00 2001 From: Jonathan Cook Date: Tue, 19 Sep 2023 18:51:33 +0200 Subject: [PATCH 13/13] BAEL-6221 Get Mocks from MockedConstruction in Mockito (#14776) Co-authored-by: jcook02 --- .../baeldung/construction/CoffeeMachine.java | 23 ++++++++ .../java/com/baeldung/construction/Fruit.java | 12 ++++ .../com/baeldung/construction/Grinder.java | 19 +++++++ .../com/baeldung/construction/WaterTank.java | 27 +++++++++ .../construction/CoffeeMachineUnitTest.java | 56 +++++++++++++++++++ .../baeldung/construction/FruitUnitTest.java | 50 +++++++++++++++++ 6 files changed, 187 insertions(+) create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/construction/CoffeeMachine.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/construction/Fruit.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/construction/Grinder.java create mode 100644 testing-modules/mockito-2/src/main/java/com/baeldung/construction/WaterTank.java create mode 100644 testing-modules/mockito-2/src/test/java/com/baeldung/construction/CoffeeMachineUnitTest.java create mode 100644 testing-modules/mockito-2/src/test/java/com/baeldung/construction/FruitUnitTest.java diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/construction/CoffeeMachine.java b/testing-modules/mockito-2/src/main/java/com/baeldung/construction/CoffeeMachine.java new file mode 100644 index 0000000000..5cf1d4eecb --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/construction/CoffeeMachine.java @@ -0,0 +1,23 @@ +package com.baeldung.construction; + +public class CoffeeMachine { + + private Grinder grinder; + private WaterTank tank; + + public CoffeeMachine() { + this.grinder = new Grinder(); + this.tank = new WaterTank(); + } + + public CoffeeMachine(int mils) { + this.grinder = new Grinder(); + this.tank = new WaterTank(mils); + } + + public String makeCoffee() { + String type = this.tank.isEspresso() ? "Espresso" : "Americano"; + return String.format("Finished making a delicious %s made with %s beans", type, this.grinder.getBeans()); + } + +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/construction/Fruit.java b/testing-modules/mockito-2/src/main/java/com/baeldung/construction/Fruit.java new file mode 100644 index 0000000000..c63f28d25f --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/construction/Fruit.java @@ -0,0 +1,12 @@ +package com.baeldung.construction; + +public class Fruit { + + public String getName() { + return "Apple"; + } + + public String getColour() { + return "Red"; + } +} diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/construction/Grinder.java b/testing-modules/mockito-2/src/main/java/com/baeldung/construction/Grinder.java new file mode 100644 index 0000000000..e62b690bb2 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/construction/Grinder.java @@ -0,0 +1,19 @@ +package com.baeldung.construction; + +public class Grinder { + + private String beans; + + public Grinder() { + this.beans = "Guatemalan"; + } + + public String getBeans() { + return beans; + } + + public void setBeans(String beans) { + this.beans = beans; + } + +} \ No newline at end of file diff --git a/testing-modules/mockito-2/src/main/java/com/baeldung/construction/WaterTank.java b/testing-modules/mockito-2/src/main/java/com/baeldung/construction/WaterTank.java new file mode 100644 index 0000000000..bf744930a0 --- /dev/null +++ b/testing-modules/mockito-2/src/main/java/com/baeldung/construction/WaterTank.java @@ -0,0 +1,27 @@ +package com.baeldung.construction; + +public class WaterTank { + + private int mils; + + public WaterTank() { + this.mils = 25; + } + + public WaterTank(int mils) { + this.mils = mils; + } + + public int getMils() { + return mils; + } + + public void setMils(int mils) { + this.mils = mils; + } + + public boolean isEspresso() { + return getMils() < 50; + } + +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/construction/CoffeeMachineUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/construction/CoffeeMachineUnitTest.java new file mode 100644 index 0000000000..7b93ad9db6 --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/construction/CoffeeMachineUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.construction; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; +import org.mockito.MockedConstruction; + +class CoffeeMachineUnitTest { + + @Test + void givenNoMockedContructor_whenCoffeeMade_thenRealDependencyReturned() { + CoffeeMachine machine = new CoffeeMachine(); + assertEquals("Finished making a delicious Espresso made with Guatemalan beans", machine.makeCoffee()); + } + + @Test + void givenMockedContructor_whenCoffeeMade_thenMockDependencyReturned() { + try (MockedConstruction mockTank = mockConstruction(WaterTank.class); MockedConstruction mockGrinder = mockConstruction(Grinder.class)) { + + CoffeeMachine machine = new CoffeeMachine(); + + WaterTank tank = mockTank.constructed() + .get(0); + Grinder grinder = mockGrinder.constructed() + .get(0); + + when(tank.isEspresso()).thenReturn(false); + when(grinder.getBeans()).thenReturn("Peruvian"); + + assertEquals("Finished making a delicious Americano made with Peruvian beans", machine.makeCoffee()); + } + + } + + @Test + void givenMockedContructorWithArgument_whenCoffeeMade_thenMockDependencyReturned() { + try (MockedConstruction mockTank = mockConstruction(WaterTank.class, (mock, context) -> { + int mils = (int) context.arguments().get(0); + when(mock.getMils()).thenReturn(mils); + }); + MockedConstruction mockGrinder = mockConstruction(Grinder.class)) { + + CoffeeMachine machine = new CoffeeMachine(100); + + Grinder grinder = mockGrinder.constructed() + .get(0); + + when(grinder.getBeans()).thenReturn("Kenyan"); + assertEquals("Finished making a delicious Americano made with Kenyan beans", machine.makeCoffee()); + } + + } + +} diff --git a/testing-modules/mockito-2/src/test/java/com/baeldung/construction/FruitUnitTest.java b/testing-modules/mockito-2/src/test/java/com/baeldung/construction/FruitUnitTest.java new file mode 100644 index 0000000000..c7baa1cc7d --- /dev/null +++ b/testing-modules/mockito-2/src/test/java/com/baeldung/construction/FruitUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.construction; + +import org.junit.jupiter.api.Test; +import org.mockito.Answers; +import org.mockito.MockedConstruction; + +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; + +import static org.mockito.Mockito.mockConstruction; + +class FruitUnitTest { + + @Test + void givenMockedContructor_whenFruitCreated_thenMockIsReturned() { + assertEquals("Apple", new Fruit().getName()); + assertEquals("Red", new Fruit().getColour()); + + try (MockedConstruction mock = mockConstruction(Fruit.class)) { + + Fruit fruit = new Fruit(); + when(fruit.getName()).thenReturn("Banana"); + when(fruit.getColour()).thenReturn("Yellow"); + + assertEquals("Banana", fruit.getName()); + assertEquals("Yellow", fruit.getColour()); + + List constructed = mock.constructed(); + assertEquals(1, constructed.size()); + } + } + + @Test + void givenMockedContructorWithNewDefaultAnswer_whenFruitCreated_thenRealMethodInvoked() { + try (MockedConstruction mock = mockConstruction(Fruit.class, withSettings().defaultAnswer(Answers.CALLS_REAL_METHODS))) { + + Fruit fruit = new Fruit(); + + assertEquals("Apple", fruit.getName()); + assertEquals("Red", fruit.getColour()); + + List constructed = mock.constructed(); + assertEquals(1, constructed.size()); + } + } + +}