From 183e213f0e14b740fa23c294f1f0304cf492d6fc Mon Sep 17 00:00:00 2001 From: Neetika Khandelwal Date: Thu, 10 Aug 2023 23:11:25 +0530 Subject: [PATCH 01/91] Shallow and Deep Copy example --- .../com/baeldung/shallowdeepcopy/Student.java | 27 +++++++++++++++ .../ShallowDeepCopyExampleTest.java | 34 +++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java new file mode 100644 index 0000000000..df75db23ac --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java @@ -0,0 +1,27 @@ +package com.baeldung.shallowdeepcopy; + +class Student { + private String name; + private int rollno; + + public Student(String name, int rollno) { + this.name = name; + this.rollno = rollno; + } + + public String getName() { + return name; + } + public int getRollno() { + return rollno; + } + + public void setRollno(int rollno) { + this.rollno = rollno; + } + + public void setName(String name) { + this.name = name; + } +} + diff --git a/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java new file mode 100644 index 0000000000..68836a96f8 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java @@ -0,0 +1,34 @@ +package com.baeldung.shallowdeepcopy; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +public class ShallowDeepCopyExampleTest { + + @Test + void testShallowCopy() { + Student originalStudent = new Student("John", 20); + Student shallowCopy = originalStudent; + + shallowCopy.setName("Baeldung"); + shallowCopy.setRollno(10); + + assertEquals("Baeldung", originalStudent.getName()); + assertEquals(10, originalStudent.getRollno()); + } + + @Test + void testDeepCopy() { + Student originalStudent = new Student("John", 20); + Student deepCopy = new Student(originalStudent.getName(), originalStudent.getRollno()); + + deepCopy.setName("Baeldung"); + deepCopy.setRollno(10); + + assertEquals("John", originalStudent.getName()); + assertEquals(20, originalStudent.getRollno()); + + assertEquals("Baeldung", deepCopy.getName()); + assertEquals(10, deepCopy.getRollno()); + } +} From 601d051f32e0745819ee0d781d882d9927e4e3db Mon Sep 17 00:00:00 2001 From: Neetika23 <42495275+Neetika23@users.noreply.github.com> Date: Fri, 22 Sep 2023 22:30:54 +0530 Subject: [PATCH 02/91] Student.java --- .../com/baeldung/shallowdeepcopy/Student.java | 33 +++++++------------ 1 file changed, 11 insertions(+), 22 deletions(-) diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java index df75db23ac..a3f726b64b 100644 --- a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java @@ -1,27 +1,16 @@ package com.baeldung.shallowdeepcopy; -class Student { - private String name; - private int rollno; - - public Student(String name, int rollno) { - this.name = name; +class Student { + private String name; + private int age; + private School school; + public Student(String name, int age, School school) { + this.name = name; this.rollno = rollno; - } - - public String getName() { - return name; - } - public int getRollno() { - return rollno; - } - - public void setRollno(int rollno) { - this.rollno = rollno; - } - - public void setName(String name) { - this.name = name; - } + this.school = school; + } + public Student(Student st) { + this(st.getName(), st.getAge(), st.getSchool()); + } // standard getters and setters } From fc07da9edae917f0c8e6f2f0ebc42d78db203a3c Mon Sep 17 00:00:00 2001 From: Neetika KHANDELWAL Date: Fri, 22 Sep 2023 23:06:36 +0530 Subject: [PATCH 03/91] Modified code for Test --- .../com/baeldung/shallowdeepcopy/School.java | 22 ++++++++ .../com/baeldung/shallowdeepcopy/Student.java | 33 ++++++++---- .../ShallowDeepCopyExampleTest.java | 53 +++++++++++-------- 3 files changed, 74 insertions(+), 34 deletions(-) create mode 100644 core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/School.java diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/School.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/School.java new file mode 100644 index 0000000000..28a751741e --- /dev/null +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/School.java @@ -0,0 +1,22 @@ +package com.baeldung.shallowdeepcopy; + +class School { + private String schoolName; + public School(School sc) { + this(sc.getSchoolName()); + } + public School(String schoolName) { + this.schoolName = schoolName; + } + // standard getters and setters +} + +@Override +public Object clone() { + try { + return (School) super.clone(); + } catch (CloneNotSupportedException e) { + return new School(this.getSchoolName()); + } +} + diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java index a3f726b64b..2fc34ba709 100644 --- a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java +++ b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java @@ -1,16 +1,27 @@ package com.baeldung.shallowdeepcopy; class Student { - private String name; - private int age; - private School school; - public Student(String name, int age, School school) { - this.name = name; - this.rollno = rollno; - this.school = school; - } - public Student(Student st) { - this(st.getName(), st.getAge(), st.getSchool()); - } // standard getters and setters + private String name; + private int age; + private School school; + public Student(String name, int age, School school) { + this.name = name; + this.rollno = rollno; + this.school = school; + } + public Student(Student st) { + this(st.getName(), st.getAge(), st.getSchool()); + } // standard getters and setters } +@Override +public Object clone() { + Student student = null; + try { + student = (Student) super.clone(); + } catch (CloneNotSupportedException e) { + student = new Student(this.getName(), this.getAge(), this.getSchool()); + } + student.school= (School) this.school.clone(); + return student; +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java index 68836a96f8..a14a621dcc 100644 --- a/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java +++ b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java @@ -4,31 +4,38 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class ShallowDeepCopyExampleTest { + + @Test + public void whenPerformShallowCopy_thenObjectsNotSame() { + School school = new School("Baeldung School"); + Student originalStudent = new Student("John", 20, school); + Student shallowCopy = new Student(originalStudent.getName(), originalStudent.getAge(), originalStudent.getSchool()); + assertNotSame(shallowCopy, originalStudent); + } + + @Test public void whenModifyingActualObject_thenCopyAlsoChange() { + School school = new School("Baeldung School"); + Student originalStudent = new Student("John", 20, school); + Student shallowCopy = new Student(originalStudent.getName(), originalStudent.getAge(), originalStudent.getSchool()); + school.setSchoolName("New Baeldung School"); + assertEquals(shallowCopy.getSchool().getSchoolName(), originalStudent.getSchool().getSchoolName()); + } @Test - void testShallowCopy() { - Student originalStudent = new Student("John", 20); - Student shallowCopy = originalStudent; + public void whenModifyingActualObject_thenCloneCopyNotChange() { + School school = new School("New School"); + Student originalStudent = new Student("Alice", 10, school); + Student deepCopy = (Student) originalStudent.clone(); + school.setSchoolName("New Baeldung School"); + assertNotEquals(deepCopy.getSchool().getSchoolName(), originalStudent.getSchool().getSchoolName()); + } - shallowCopy.setName("Baeldung"); - shallowCopy.setRollno(10); - - assertEquals("Baeldung", originalStudent.getName()); - assertEquals(10, originalStudent.getRollno()); - } - - @Test - void testDeepCopy() { - Student originalStudent = new Student("John", 20); - Student deepCopy = new Student(originalStudent.getName(), originalStudent.getRollno()); - - deepCopy.setName("Baeldung"); - deepCopy.setRollno(10); - - assertEquals("John", originalStudent.getName()); - assertEquals(20, originalStudent.getRollno()); - - assertEquals("Baeldung", deepCopy.getName()); - assertEquals(10, deepCopy.getRollno()); + @Test + public void whenModifyingActualObject_thenCopyNotChange() { + School school = new School("Baeldung School"); + Student originalStudent = new Student("Alice", 30, school); + Student deepCopy = new Student(originalStudent); + school.setSchoolName("New Baeldung School"); + assertNotEquals( originalStudent.getSchool().getSchoolName(), deepCopy.getSchool().getSchoolName()); } } From 78d8f62ef7f5453f02522eba2999b124338bc126 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Tue, 26 Sep 2023 10:05:04 +0700 Subject: [PATCH 04/91] [Add] completablefuture timeout test --- .../core-java-concurrency-simple/pom.xml | 9 ++ .../CompletableFutureTimeoutUnitTest.java | 83 +++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java diff --git a/core-java-modules/core-java-concurrency-simple/pom.xml b/core-java-modules/core-java-concurrency-simple/pom.xml index a16df4fc97..720ab5a0ed 100644 --- a/core-java-modules/core-java-concurrency-simple/pom.xml +++ b/core-java-modules/core-java-concurrency-simple/pom.xml @@ -12,6 +12,15 @@ 0.0.1-SNAPSHOT + + + org.wiremock + wiremock + 3.1.0 + test + + + core-java-concurrency-simple diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java new file mode 100644 index 0000000000..f54e5f4af5 --- /dev/null +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.concurrent.completablefuture; + +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.concurrent.*; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +public class CompletableFutureTimeoutUnitTest { + private static WireMockServer wireMockServer; + private static ScheduledExecutorService executorService; + private static final int DEFAULT_TIMEOUT = 500; //0.5 seconds + private static final int TIMEOUT_STATUS_CODE = 408; //0.5 seconds + + @BeforeAll + public static void setUp() { + wireMockServer = new WireMockServer(8080); + wireMockServer.start(); + WireMock.configureFor("localhost", 8080); + + stubFor(get(urlEqualTo("/api/dummy")) + .willReturn(aResponse() + .withFixedDelay(5000) // must be > DEFAULT_TIMEOUT for a timeout to occur. + .withStatus(408))); + + executorService = Executors.newScheduledThreadPool(1); + } + + + @AfterAll + public static void tearDown() { + executorService.shutdown(); + wireMockServer.stop(); + } + + private CompletableFuture createDummyRequest() { + return CompletableFuture.supplyAsync(() -> { + try { + URL url = new URL("http://localhost:8080/api/dummy"); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + try { + return connection.getResponseCode(); + } finally { + connection.disconnect(); + } + } catch (IOException e) { + return TIMEOUT_STATUS_CODE; + } + }); + } + + @Test + public void whenorTimeout_thenGetThrow() { + CompletableFuture completableFuture = createDummyRequest() + .orTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); + assertThrows(ExecutionException.class, completableFuture::get); + } + + @Test + public void whencompleteOnTimeout_thenReturnValue() throws ExecutionException, InterruptedException { + CompletableFuture completableFuture = createDummyRequest() + .completeOnTimeout(TIMEOUT_STATUS_CODE, DEFAULT_TIMEOUT, + TimeUnit.MILLISECONDS); + assertEquals(TIMEOUT_STATUS_CODE, completableFuture.get()); + } + + @Test + public void whencompleteExceptionally_thenGetThrow() { + CompletableFuture completableFuture = createDummyRequest(); + executorService.schedule(() -> completableFuture + .completeExceptionally(new TimeoutException("Timeout occurred")), DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); + assertThrows(ExecutionException.class, completableFuture::get); + } + +} From e9536ff0c4709a54c89d5b3f08e58c29bb7dd62b Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Wed, 27 Sep 2023 09:20:07 +0700 Subject: [PATCH 05/91] [Update] set DEFAULT_TIMEOUT to 1000 --- .../completablefuture/CompletableFutureTimeoutUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java index f54e5f4af5..43b8075ebd 100644 --- a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -17,7 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows; public class CompletableFutureTimeoutUnitTest { private static WireMockServer wireMockServer; private static ScheduledExecutorService executorService; - private static final int DEFAULT_TIMEOUT = 500; //0.5 seconds + private static final int DEFAULT_TIMEOUT = 1000; //1 seconds private static final int TIMEOUT_STATUS_CODE = 408; //0.5 seconds @BeforeAll From 05f4487d6357ebfc6eb017b026483876a9e6bd02 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Sun, 8 Oct 2023 05:12:47 +0700 Subject: [PATCH 06/91] [Update] no need to be public --- .../CompletableFutureTimeoutUnitTest.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java index 43b8075ebd..99f572f25a 100644 --- a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -14,14 +14,15 @@ import java.util.concurrent.*; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -public class CompletableFutureTimeoutUnitTest { + +class CompletableFutureTimeoutUnitTest { private static WireMockServer wireMockServer; private static ScheduledExecutorService executorService; private static final int DEFAULT_TIMEOUT = 1000; //1 seconds private static final int TIMEOUT_STATUS_CODE = 408; //0.5 seconds @BeforeAll - public static void setUp() { + static void setUp() { wireMockServer = new WireMockServer(8080); wireMockServer.start(); WireMock.configureFor("localhost", 8080); @@ -36,7 +37,7 @@ public class CompletableFutureTimeoutUnitTest { @AfterAll - public static void tearDown() { + static void tearDown() { executorService.shutdown(); wireMockServer.stop(); } @@ -58,14 +59,14 @@ public class CompletableFutureTimeoutUnitTest { } @Test - public void whenorTimeout_thenGetThrow() { + void whenorTimeout_thenGetThrow() { CompletableFuture completableFuture = createDummyRequest() .orTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); assertThrows(ExecutionException.class, completableFuture::get); } @Test - public void whencompleteOnTimeout_thenReturnValue() throws ExecutionException, InterruptedException { + void whencompleteOnTimeout_thenReturnValue() throws ExecutionException, InterruptedException { CompletableFuture completableFuture = createDummyRequest() .completeOnTimeout(TIMEOUT_STATUS_CODE, DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); @@ -73,7 +74,7 @@ public class CompletableFutureTimeoutUnitTest { } @Test - public void whencompleteExceptionally_thenGetThrow() { + void whencompleteExceptionally_thenGetThrow() { CompletableFuture completableFuture = createDummyRequest(); executorService.schedule(() -> completableFuture .completeExceptionally(new TimeoutException("Timeout occurred")), DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); From 92d038dc3caca20feb9cd72293fbca02e99daca6 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Sun, 8 Oct 2023 20:33:43 +0700 Subject: [PATCH 07/91] add default --- .../CompletableFutureTimeoutUnitTest.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java index 99f572f25a..f41730f7df 100644 --- a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -81,4 +81,16 @@ class CompletableFutureTimeoutUnitTest { assertThrows(ExecutionException.class, completableFuture::get); } + @Test + void whencompletableDefault_thenGetReturn() { + CompletableFuture completableFuture = createDummyRequest(); + try { + int result = completableFuture.get(); + assertEquals(TIMEOUT_STATUS_CODE, result); + } catch (InterruptedException | ExecutionException e) { + //System.out.println("ERROR->"+e.getMessage()); + throw new RuntimeException(e); + } + } + } From 70e6dcd47b4eea4c9f6b57265ff114f4d5f03644 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Mon, 9 Oct 2023 20:16:40 +0700 Subject: [PATCH 08/91] non static --- .../CompletableFutureTimeoutUnitTest.java | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java index f41730f7df..449ebc5bbc 100644 --- a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -80,17 +80,4 @@ class CompletableFutureTimeoutUnitTest { .completeExceptionally(new TimeoutException("Timeout occurred")), DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); assertThrows(ExecutionException.class, completableFuture::get); } - - @Test - void whencompletableDefault_thenGetReturn() { - CompletableFuture completableFuture = createDummyRequest(); - try { - int result = completableFuture.get(); - assertEquals(TIMEOUT_STATUS_CODE, result); - } catch (InterruptedException | ExecutionException e) { - //System.out.println("ERROR->"+e.getMessage()); - throw new RuntimeException(e); - } - } - } From e3ef6b62759b7651fac57ab072fdc5a92c7c614a Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Mon, 9 Oct 2023 20:40:45 +0700 Subject: [PATCH 09/91] [Update] non static --- .../CompletableFutureTimeoutUnitTest.java | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java index 449ebc5bbc..8070ef620a 100644 --- a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -5,6 +5,7 @@ import com.github.tomakehurst.wiremock.client.WireMock; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; import java.io.IOException; import java.net.HttpURLConnection; @@ -15,14 +16,15 @@ import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +@TestInstance(TestInstance.Lifecycle.PER_CLASS) class CompletableFutureTimeoutUnitTest { - private static WireMockServer wireMockServer; - private static ScheduledExecutorService executorService; + private WireMockServer wireMockServer; + private ScheduledExecutorService executorService; private static final int DEFAULT_TIMEOUT = 1000; //1 seconds private static final int TIMEOUT_STATUS_CODE = 408; //0.5 seconds @BeforeAll - static void setUp() { + void setUp() { wireMockServer = new WireMockServer(8080); wireMockServer.start(); WireMock.configureFor("localhost", 8080); @@ -37,7 +39,7 @@ class CompletableFutureTimeoutUnitTest { @AfterAll - static void tearDown() { + void tearDown() { executorService.shutdown(); wireMockServer.stop(); } @@ -52,7 +54,7 @@ class CompletableFutureTimeoutUnitTest { } finally { connection.disconnect(); } - } catch (IOException e) { + } catch (Exception e) { return TIMEOUT_STATUS_CODE; } }); @@ -60,16 +62,15 @@ class CompletableFutureTimeoutUnitTest { @Test void whenorTimeout_thenGetThrow() { - CompletableFuture completableFuture = createDummyRequest() - .orTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); + CompletableFuture completableFuture = createDummyRequest(); + completableFuture.orTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); assertThrows(ExecutionException.class, completableFuture::get); } @Test void whencompleteOnTimeout_thenReturnValue() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = createDummyRequest() - .completeOnTimeout(TIMEOUT_STATUS_CODE, DEFAULT_TIMEOUT, - TimeUnit.MILLISECONDS); + CompletableFuture completableFuture = createDummyRequest(); + completableFuture.completeOnTimeout(TIMEOUT_STATUS_CODE, DEFAULT_TIMEOUT,TimeUnit.MILLISECONDS); assertEquals(TIMEOUT_STATUS_CODE, completableFuture.get()); } From 7e924cefe4a2bb82bd54100095ed2e486e238196 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Mon, 16 Oct 2023 17:31:19 +0700 Subject: [PATCH 10/91] [update] method name, result, flow --- .../CompletableFutureTimeoutUnitTest.java | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java index 8070ef620a..a332f816b2 100644 --- a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -7,7 +7,9 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.*; @@ -21,18 +23,19 @@ class CompletableFutureTimeoutUnitTest { private WireMockServer wireMockServer; private ScheduledExecutorService executorService; private static final int DEFAULT_TIMEOUT = 1000; //1 seconds - private static final int TIMEOUT_STATUS_CODE = 408; //0.5 seconds + private static final String DEFAULT_PRODUCT = "default_product"; + private static final String PRODUCT_OFFERS = "product_offers"; @BeforeAll void setUp() { wireMockServer = new WireMockServer(8080); wireMockServer.start(); WireMock.configureFor("localhost", 8080); - + System.out.println("stubing"); stubFor(get(urlEqualTo("/api/dummy")) .willReturn(aResponse() .withFixedDelay(5000) // must be > DEFAULT_TIMEOUT for a timeout to occur. - .withStatus(408))); + .withBody(PRODUCT_OFFERS))); executorService = Executors.newScheduledThreadPool(1); } @@ -44,39 +47,47 @@ class CompletableFutureTimeoutUnitTest { wireMockServer.stop(); } - private CompletableFuture createDummyRequest() { + private CompletableFuture fetchProductData() { return CompletableFuture.supplyAsync(() -> { try { URL url = new URL("http://localhost:8080/api/dummy"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try { - return connection.getResponseCode(); + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String inputLine; + StringBuffer response = new StringBuffer(); + + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + return response.toString(); } finally { connection.disconnect(); } - } catch (Exception e) { - return TIMEOUT_STATUS_CODE; + } catch (IOException e) { + return ""; } }); } @Test void whenorTimeout_thenGetThrow() { - CompletableFuture completableFuture = createDummyRequest(); + CompletableFuture completableFuture = fetchProductData(); completableFuture.orTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); assertThrows(ExecutionException.class, completableFuture::get); } @Test void whencompleteOnTimeout_thenReturnValue() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = createDummyRequest(); - completableFuture.completeOnTimeout(TIMEOUT_STATUS_CODE, DEFAULT_TIMEOUT,TimeUnit.MILLISECONDS); - assertEquals(TIMEOUT_STATUS_CODE, completableFuture.get()); + CompletableFuture completableFuture = fetchProductData(); + completableFuture.completeOnTimeout(DEFAULT_PRODUCT, DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); + assertEquals(DEFAULT_PRODUCT, completableFuture.get()); } @Test void whencompleteExceptionally_thenGetThrow() { - CompletableFuture completableFuture = createDummyRequest(); + CompletableFuture completableFuture = fetchProductData(); executorService.schedule(() -> completableFuture .completeExceptionally(new TimeoutException("Timeout occurred")), DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); assertThrows(ExecutionException.class, completableFuture::get); From c1f53973cd2ae694d7c672fb5f105bea888c31cc Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Mon, 16 Oct 2023 18:33:15 +0700 Subject: [PATCH 11/91] [Update] clean trash --- .../completablefuture/CompletableFutureTimeoutUnitTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java index a332f816b2..c1de38ad37 100644 --- a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -31,7 +31,7 @@ class CompletableFutureTimeoutUnitTest { wireMockServer = new WireMockServer(8080); wireMockServer.start(); WireMock.configureFor("localhost", 8080); - System.out.println("stubing"); + stubFor(get(urlEqualTo("/api/dummy")) .willReturn(aResponse() .withFixedDelay(5000) // must be > DEFAULT_TIMEOUT for a timeout to occur. @@ -61,6 +61,7 @@ class CompletableFutureTimeoutUnitTest { response.append(inputLine); } in.close(); + return response.toString(); } finally { connection.disconnect(); From 2efe2c7987e399c75e52c0eb528e47a81838ed4d Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Tue, 17 Oct 2023 13:50:31 +0700 Subject: [PATCH 12/91] using json body for sample --- .../CompletableFutureTimeoutUnitTest.java | 93 ++++++++++++++++++- 1 file changed, 90 insertions(+), 3 deletions(-) diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java index c1de38ad37..62cf00930b 100644 --- a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -1,7 +1,9 @@ package com.baeldung.concurrent.completablefuture; +import com.fasterxml.jackson.databind.JsonNode; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; +import net.minidev.json.writer.JsonReader; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -13,6 +15,7 @@ import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.*; +import java.util.function.Supplier; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -23,8 +26,93 @@ class CompletableFutureTimeoutUnitTest { private WireMockServer wireMockServer; private ScheduledExecutorService executorService; private static final int DEFAULT_TIMEOUT = 1000; //1 seconds - private static final String DEFAULT_PRODUCT = "default_product"; - private static final String PRODUCT_OFFERS = "product_offers"; + private static final String DEFAULT_PRODUCT = "{\n" + + " \"products\": [\n" + + " {\n" + + " \"id\": 2,\n" + + " \"title\": \"iPhone X\",\n" + + " \"description\": \"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...\",\n" + + " \"price\": 899,\n" + + " \"discountPercentage\": 0.0,\n" + + " \"rating\": 4.44,\n" + + " \"stock\": 34,\n" + + " \"brand\": \"Apple\",\n" + + " \"category\": \"smartphones\"\n" + + " },\n" + + " {\n" + + " \"id\": 3,\n" + + " \"title\": \"Samsung Universe 9\",\n" + + " \"description\": \"Samsung's new variant which goes beyond Galaxy to the Universe\",\n" + + " \"price\": 1249,\n" + + " \"discountPercentage\": 0.0,\n" + + " \"rating\": 4.09,\n" + + " \"stock\": 36,\n" + + " \"brand\": \"Samsung\",\n" + + " \"category\": \"smartphones\"\n" + + " }\n" + + " ],\n" + + " \"total\": 2\n" + + "}"; + private static final String PRODUCT_OFFERS = "{\n" + + " \"products\": [\n" + + " {\n" + + " \"id\": 1,\n" + + " \"title\": \"iPhone 9\",\n" + + " \"description\": \"An apple mobile which is nothing like apple\",\n" + + " \"price\": 549,\n" + + " \"discountPercentage\": 12.96,\n" + + " \"rating\": 4.69,\n" + + " \"stock\": 94,\n" + + " \"brand\": \"Apple\",\n" + + " \"category\": \"smartphones\"\n" + + " },\n" + + " {\n" + + " \"id\": 2,\n" + + " \"title\": \"iPhone X\",\n" + + " \"description\": \"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...\",\n" + + " \"price\": 899,\n" + + " \"discountPercentage\": 17.94,\n" + + " \"rating\": 4.44,\n" + + " \"stock\": 34,\n" + + " \"brand\": \"Apple\",\n" + + " \"category\": \"smartphones\"\n" + + " },\n" + + " {\n" + + " \"id\": 3,\n" + + " \"title\": \"Samsung Universe 9\",\n" + + " \"description\": \"Samsung's new variant which goes beyond Galaxy to the Universe\",\n" + + " \"price\": 1249,\n" + + " \"discountPercentage\": 15.46,\n" + + " \"rating\": 4.09,\n" + + " \"stock\": 36,\n" + + " \"brand\": \"Samsung\",\n" + + " \"category\": \"smartphones\"\n" + + " },\n" + + " {\n" + + " \"id\": 4,\n" + + " \"title\": \"OPPOF19\",\n" + + " \"description\": \"OPPO F19 is officially announced on April 2021.\",\n" + + " \"price\": 280,\n" + + " \"discountPercentage\": 17.91,\n" + + " \"rating\": 4.3,\n" + + " \"stock\": 123,\n" + + " \"brand\": \"OPPO\",\n" + + " \"category\": \"smartphones\"\n" + + " },\n" + + " {\n" + + " \"id\": 5,\n" + + " \"title\": \"Huawei P30\",\n" + + " \"description\": \"Huawei’s re-badged P30 Pro New Edition was officially unveiled yesterday in Germany and now the device has made its way to the UK.\",\n" + + " \"price\": 499,\n" + + " \"discountPercentage\": 10.58,\n" + + " \"rating\": 4.09,\n" + + " \"stock\": 32,\n" + + " \"brand\": \"Huawei\",\n" + + " \"category\": \"smartphones\"\n" + + " }\n" + + " ],\n" + + " \"total\": 5\n" + + "}"; @BeforeAll void setUp() { @@ -40,7 +128,6 @@ class CompletableFutureTimeoutUnitTest { executorService = Executors.newScheduledThreadPool(1); } - @AfterAll void tearDown() { executorService.shutdown(); From 38d4d8f621f8fc91f72979d0ad5790b1e585a654 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Tue, 17 Oct 2023 18:24:02 +0700 Subject: [PATCH 13/91] text block --- .../CompletableFutureTimeoutUnitTest.java | 181 +++++++++--------- 1 file changed, 90 insertions(+), 91 deletions(-) diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java index 62cf00930b..bb538f2584 100644 --- a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -1,9 +1,7 @@ package com.baeldung.concurrent.completablefuture; -import com.fasterxml.jackson.databind.JsonNode; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.client.WireMock; -import net.minidev.json.writer.JsonReader; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -15,7 +13,6 @@ import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.*; -import java.util.function.Supplier; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -26,100 +23,102 @@ class CompletableFutureTimeoutUnitTest { private WireMockServer wireMockServer; private ScheduledExecutorService executorService; private static final int DEFAULT_TIMEOUT = 1000; //1 seconds - private static final String DEFAULT_PRODUCT = "{\n" + - " \"products\": [\n" + - " {\n" + - " \"id\": 2,\n" + - " \"title\": \"iPhone X\",\n" + - " \"description\": \"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...\",\n" + - " \"price\": 899,\n" + - " \"discountPercentage\": 0.0,\n" + - " \"rating\": 4.44,\n" + - " \"stock\": 34,\n" + - " \"brand\": \"Apple\",\n" + - " \"category\": \"smartphones\"\n" + - " },\n" + - " {\n" + - " \"id\": 3,\n" + - " \"title\": \"Samsung Universe 9\",\n" + - " \"description\": \"Samsung's new variant which goes beyond Galaxy to the Universe\",\n" + - " \"price\": 1249,\n" + - " \"discountPercentage\": 0.0,\n" + - " \"rating\": 4.09,\n" + - " \"stock\": 36,\n" + - " \"brand\": \"Samsung\",\n" + - " \"category\": \"smartphones\"\n" + - " }\n" + - " ],\n" + - " \"total\": 2\n" + - "}"; - private static final String PRODUCT_OFFERS = "{\n" + - " \"products\": [\n" + - " {\n" + - " \"id\": 1,\n" + - " \"title\": \"iPhone 9\",\n" + - " \"description\": \"An apple mobile which is nothing like apple\",\n" + - " \"price\": 549,\n" + - " \"discountPercentage\": 12.96,\n" + - " \"rating\": 4.69,\n" + - " \"stock\": 94,\n" + - " \"brand\": \"Apple\",\n" + - " \"category\": \"smartphones\"\n" + - " },\n" + - " {\n" + - " \"id\": 2,\n" + - " \"title\": \"iPhone X\",\n" + - " \"description\": \"SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...\",\n" + - " \"price\": 899,\n" + - " \"discountPercentage\": 17.94,\n" + - " \"rating\": 4.44,\n" + - " \"stock\": 34,\n" + - " \"brand\": \"Apple\",\n" + - " \"category\": \"smartphones\"\n" + - " },\n" + - " {\n" + - " \"id\": 3,\n" + - " \"title\": \"Samsung Universe 9\",\n" + - " \"description\": \"Samsung's new variant which goes beyond Galaxy to the Universe\",\n" + - " \"price\": 1249,\n" + - " \"discountPercentage\": 15.46,\n" + - " \"rating\": 4.09,\n" + - " \"stock\": 36,\n" + - " \"brand\": \"Samsung\",\n" + - " \"category\": \"smartphones\"\n" + - " },\n" + - " {\n" + - " \"id\": 4,\n" + - " \"title\": \"OPPOF19\",\n" + - " \"description\": \"OPPO F19 is officially announced on April 2021.\",\n" + - " \"price\": 280,\n" + - " \"discountPercentage\": 17.91,\n" + - " \"rating\": 4.3,\n" + - " \"stock\": 123,\n" + - " \"brand\": \"OPPO\",\n" + - " \"category\": \"smartphones\"\n" + - " },\n" + - " {\n" + - " \"id\": 5,\n" + - " \"title\": \"Huawei P30\",\n" + - " \"description\": \"Huawei’s re-badged P30 Pro New Edition was officially unveiled yesterday in Germany and now the device has made its way to the UK.\",\n" + - " \"price\": 499,\n" + - " \"discountPercentage\": 10.58,\n" + - " \"rating\": 4.09,\n" + - " \"stock\": 32,\n" + - " \"brand\": \"Huawei\",\n" + - " \"category\": \"smartphones\"\n" + - " }\n" + - " ],\n" + - " \"total\": 5\n" + - "}"; + private static final String DEFAULT_PRODUCT = """ + { + "products": [ + { + "id": 2, + "title": "iPhone X", + "description": "SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...", + "price": 899, + "discountPercentage": 0.0, + "rating": 4.44, + "stock": 34, + "brand": "Apple", + "category": "smartphones" + }, + { + "id": 3, + "title": "Samsung Universe 9", + "description": "Samsung's new variant which goes beyond Galaxy to the Universe", + "price": 1249, + "discountPercentage": 0.0, + "rating": 4.09, + "stock": 36, + "brand": "Samsung", + "category": "smartphones" + } + ], + "total": 2 + }"""; + private static final String PRODUCT_OFFERS = """ + { + "products": [ + { + "id": 1, + "title": "iPhone 9", + "description": "An apple mobile which is nothing like apple", + "price": 549, + "discountPercentage": 12.96, + "rating": 4.69, + "stock": 94, + "brand": "Apple", + "category": "smartphones" + }, + { + "id": 2, + "title": "iPhone X", + "description": "SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...", + "price": 899, + "discountPercentage": 17.94, + "rating": 4.44, + "stock": 34, + "brand": "Apple", + "category": "smartphones" + }, + { + "id": 3, + "title": "Samsung Universe 9", + "description": "Samsung's new variant which goes beyond Galaxy to the Universe", + "price": 1249, + "discountPercentage": 15.46, + "rating": 4.09, + "stock": 36, + "brand": "Samsung", + "category": "smartphones" + }, + { + "id": 4, + "title": "OPPOF19", + "description": "OPPO F19 is officially announced on April 2021.", + "price": 280, + "discountPercentage": 17.91, + "rating": 4.3, + "stock": 123, + "brand": "OPPO", + "category": "smartphones" + }, + { + "id": 5, + "title": "Huawei P30", + "description": "Huawei’s re-badged P30 Pro New Edition was officially unveiled yesterday in Germany and now the device has made its way to the UK.", + "price": 499, + "discountPercentage": 10.58, + "rating": 4.09, + "stock": 32, + "brand": "Huawei", + "category": "smartphones" + } + ], + "total": 5 + }"""; @BeforeAll void setUp() { wireMockServer = new WireMockServer(8080); wireMockServer.start(); WireMock.configureFor("localhost", 8080); - + System.out.println(PRODUCT_OFFERS); stubFor(get(urlEqualTo("/api/dummy")) .willReturn(aResponse() .withFixedDelay(5000) // must be > DEFAULT_TIMEOUT for a timeout to occur. From 3f40e66508517cb871ca166f39795fb80ee1aa9b Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Tue, 17 Oct 2023 18:29:26 +0700 Subject: [PATCH 14/91] clean unused --- .../completablefuture/CompletableFutureTimeoutUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java index bb538f2584..1932c03486 100644 --- a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -118,7 +118,7 @@ class CompletableFutureTimeoutUnitTest { wireMockServer = new WireMockServer(8080); wireMockServer.start(); WireMock.configureFor("localhost", 8080); - System.out.println(PRODUCT_OFFERS); + stubFor(get(urlEqualTo("/api/dummy")) .willReturn(aResponse() .withFixedDelay(5000) // must be > DEFAULT_TIMEOUT for a timeout to occur. From 223c0bd32f661914004053038213bcfc423629fc Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Tue, 17 Oct 2023 18:45:08 +0700 Subject: [PATCH 15/91] [Update] rename completableFuture to productDataFuture --- .../CompletableFutureTimeoutUnitTest.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java index 1932c03486..116093b6c3 100644 --- a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -160,23 +160,23 @@ class CompletableFutureTimeoutUnitTest { @Test void whenorTimeout_thenGetThrow() { - CompletableFuture completableFuture = fetchProductData(); - completableFuture.orTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); - assertThrows(ExecutionException.class, completableFuture::get); + CompletableFuture productDataFuture = fetchProductData(); + productDataFuture.orTimeout(DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); + assertThrows(ExecutionException.class, productDataFuture::get); } @Test void whencompleteOnTimeout_thenReturnValue() throws ExecutionException, InterruptedException { - CompletableFuture completableFuture = fetchProductData(); - completableFuture.completeOnTimeout(DEFAULT_PRODUCT, DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); - assertEquals(DEFAULT_PRODUCT, completableFuture.get()); + CompletableFuture productDataFuture = fetchProductData(); + productDataFuture.completeOnTimeout(DEFAULT_PRODUCT, DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); + assertEquals(DEFAULT_PRODUCT, productDataFuture.get()); } @Test void whencompleteExceptionally_thenGetThrow() { - CompletableFuture completableFuture = fetchProductData(); - executorService.schedule(() -> completableFuture + CompletableFuture productDataFuture = fetchProductData(); + executorService.schedule(() -> productDataFuture .completeExceptionally(new TimeoutException("Timeout occurred")), DEFAULT_TIMEOUT, TimeUnit.MILLISECONDS); - assertThrows(ExecutionException.class, completableFuture::get); + assertThrows(ExecutionException.class, productDataFuture::get); } } From 7eef9b46b7be751e72c79e0c528fe8cfda49e5a1 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Tue, 17 Oct 2023 20:18:28 +0700 Subject: [PATCH 16/91] [Optimize] using try-with-resources --- .../completablefuture/CompletableFutureTimeoutUnitTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java index 116093b6c3..d04865026b 100644 --- a/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java +++ b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/concurrent/completablefuture/CompletableFutureTimeoutUnitTest.java @@ -138,15 +138,14 @@ class CompletableFutureTimeoutUnitTest { try { URL url = new URL("http://localhost:8080/api/dummy"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - try { - BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + + try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } - in.close(); return response.toString(); } finally { @@ -158,6 +157,7 @@ class CompletableFutureTimeoutUnitTest { }); } + @Test void whenorTimeout_thenGetThrow() { CompletableFuture productDataFuture = fetchProductData(); From 5230638d73f6291c5fc8f0aeb1b343b51324e454 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Thu, 19 Oct 2023 19:32:23 +0530 Subject: [PATCH 17/91] BAEL-7135 A Guide to Spring 6 JdbcClient API --- persistence-modules/spring-jdbc-2/pom.xml | 96 ++++++++++++++++ .../jdbcClient/JdbcClientDemoApplication.java | 14 +++ .../baeldung/jdbcClient/dao/StudentDao.java | 95 ++++++++++++++++ .../baeldung/jdbcClient/model/Student.java | 60 ++++++++++ .../model/StudentResultExtractor.java | 26 +++++ .../jdbcClient/model/StudentRowMapper.java | 20 ++++ .../application.properties | 5 + .../com.baeldung.jdbcClient/drop_student.sql | 1 + .../com.baeldung.jdbcClient/student.sql | 98 ++++++++++++++++ .../jdbcClient/JdbcClientUnitTest.java | 106 ++++++++++++++++++ .../src/test/resources/logback-test.xml | 12 ++ 11 files changed, 533 insertions(+) create mode 100644 persistence-modules/spring-jdbc-2/pom.xml create mode 100644 persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/JdbcClientDemoApplication.java create mode 100644 persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/dao/StudentDao.java create mode 100644 persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/Student.java create mode 100644 persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentResultExtractor.java create mode 100644 persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentRowMapper.java create mode 100644 persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/application.properties create mode 100644 persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/drop_student.sql create mode 100644 persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/student.sql create mode 100644 persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcClient/JdbcClientUnitTest.java create mode 100644 persistence-modules/spring-jdbc-2/src/test/resources/logback-test.xml diff --git a/persistence-modules/spring-jdbc-2/pom.xml b/persistence-modules/spring-jdbc-2/pom.xml new file mode 100644 index 0000000000..79c5ad100c --- /dev/null +++ b/persistence-modules/spring-jdbc-2/pom.xml @@ -0,0 +1,96 @@ + + + 4.0.0 + + org.example + spring-jdbc-2 + 1.0-SNAPSHOT + spring-jdbc-2 + Demo project for Spring Jdbc + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + + + + + org.springframework.boot + spring-boot-starter-jdbc + + + + com.h2database + h2 + runtime + + + org.springframework.boot + spring-boot-starter-test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + + --enable-preview + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + + 17 + 3.2.0-SNAPSHOT + UTF-8 + + + \ No newline at end of file diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/JdbcClientDemoApplication.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/JdbcClientDemoApplication.java new file mode 100644 index 0000000000..fe1a203eff --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/JdbcClientDemoApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.jdbcClient; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = "com.baeldung.jdbcClient") +public class JdbcClientDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(JdbcClientDemoApplication.class, args); + } +} diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/dao/StudentDao.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/dao/StudentDao.java new file mode 100644 index 0000000000..4ca2046a0e --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/dao/StudentDao.java @@ -0,0 +1,95 @@ +package com.baeldung.jdbcClient.dao; + +import com.baeldung.jdbcClient.model.Student; +import com.baeldung.jdbcClient.model.StudentResultExtractor; +import com.baeldung.jdbcClient.model.StudentRowMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.RowCountCallbackHandler; +import org.springframework.jdbc.core.simple.JdbcClient; +import org.springframework.stereotype.Repository; + +import java.sql.Types; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +@Repository +public class StudentDao { + + private static final Logger logger = LoggerFactory.getLogger(StudentDao.class); + @Autowired + private JdbcClient jdbcClient; + + public Integer insertWithSetParamWithNamedParamAndSqlType(Student student) { + String sql = "INSERT INTO student (student_name, age, grade, gender, state)" + + "VALUES (:name, :age, :grade, :gender, :state)"; + Integer noOfrowsAffected = this.jdbcClient.sql(sql) + .param("name", student.getStudentName(), Types.VARCHAR) + .param("age", student.getAge(), Types.INTEGER) + .param("grade", student.getGrade(), Types.INTEGER) + .param("gender", student.getStudentGender(), Types.VARCHAR) + .param("state", student.getState(), Types.VARCHAR) + .update(); + logger.info("No. of rows affected: " + noOfrowsAffected); + return noOfrowsAffected; + } + + public List getStudentsOfGradeStateAndGenderWithPositionalParams(int grade, String state, String gender) { + String sql = "select student_id, student_name, age, grade, gender, state from student" + + " where grade = ? and state = ? and gender = ?"; + return jdbcClient.sql(sql) + .param(grade) + .param(state) + .param(gender) + .query(new StudentRowMapper()).list(); + } + + public List getStudentsOfGradeStateAndGenderWithParamIndex(int grade, String state, String gender) { + String sql = "select student_id, student_name, age, grade, gender, state from student" + + " where grade = ? and state = ? and gender = ?"; + return jdbcClient.sql(sql) + .param(1,grade) + .param(2, state) + .param(3, gender) + .query(new StudentResultExtractor()); + } + + public Student getStudentsOfGradeStateAndGenderWithParamsInVarargs(int grade, String state, String gender) { + String sql = "select student_id, student_name, age, grade, gender, state from student" + + " where grade = ? and state = ? and gender = ? limit 1"; + return jdbcClient.sql(sql) + .params(grade, state, gender) + .query(new StudentRowMapper()).single(); + } + + public Optional getStudentsOfGradeStateAndGenderWithParamsInList(List params) { + String sql = "select student_id, student_name, age, grade, gender, state from student" + + " where grade = ? and state = ? and gender = ? limit 1"; + return jdbcClient.sql(sql) + .params(params) + .query(new StudentRowMapper()).optional(); + } + + + public int getCountOfStudentsOfGradeStateAndGenderWithNamedParam(int grade, String state, String gender) { + String sql = "select student_id, student_name, age, grade, gender, state from student" + + " where grade = :grade and state = :state and gender = :gender"; + RowCountCallbackHandler countCallbackHandler = new RowCountCallbackHandler(); + jdbcClient.sql(sql) + .param("grade", grade) + .param("state", state) + .param("gender", gender) + .query(countCallbackHandler); + return countCallbackHandler.getRowCount(); + } + + public List getStudentsOfGradeStateAndGenderWithParamMap(Map paramMap) { + String sql = "select student_id, student_name, age, grade, gender, state from student" + + " where grade = :grade and state = :state and gender = :gender"; + return jdbcClient.sql(sql) + .params(paramMap) + .query(new StudentRowMapper()).list(); + } +} diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/Student.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/Student.java new file mode 100644 index 0000000000..2e4ff69464 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/Student.java @@ -0,0 +1,60 @@ +package com.baeldung.jdbcClient.model; + +public class Student { + private Integer studentId; + private String studentName; + private String studentGender; + private Integer age; + private Integer grade; + + public Integer getStudentId() { + return studentId; + } + + public void setStudentId(Integer studentId) { + this.studentId = studentId; + } + + public String getStudentName() { + return studentName; + } + + public void setStudentName(String studentName) { + this.studentName = studentName; + } + + public String getStudentGender() { + return studentGender; + } + + public void setStudentGender(String studentGender) { + this.studentGender = studentGender; + } + + public Integer getAge() { + return age; + } + + public void setAge(Integer age) { + this.age = age; + } + + public Integer getGrade() { + return grade; + } + + public void setGrade(Integer grade) { + this.grade = grade; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + private String state; + +} diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentResultExtractor.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentResultExtractor.java new file mode 100644 index 0000000000..2bc8a249c5 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentResultExtractor.java @@ -0,0 +1,26 @@ +package com.baeldung.jdbcClient.model; + +import org.springframework.jdbc.core.ResultSetExtractor; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class StudentResultExtractor implements ResultSetExtractor> { + @Override + public List extractData(ResultSet rs) throws SQLException { + List students = new ArrayList(); + while(rs.next()) { + Student student = new Student(); + student.setStudentId(rs.getInt("student_id")); + student.setStudentName(rs.getString("student_name")); + student.setAge(rs.getInt("age")); + student.setStudentGender(rs.getString("gender")); + student.setGrade(rs.getInt("grade")); + student.setState(rs.getString("state")); + students.add(student); + } + return students; + } +} diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentRowMapper.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentRowMapper.java new file mode 100644 index 0000000000..22a98e0efa --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentRowMapper.java @@ -0,0 +1,20 @@ +package com.baeldung.jdbcClient.model; + +import org.springframework.jdbc.core.RowMapper; + +import java.sql.ResultSet; +import java.sql.SQLException; + +public class StudentRowMapper implements RowMapper { + @Override + public Student mapRow(ResultSet rs, int rowNum) throws SQLException { + Student student = new Student(); + student.setStudentId(rs.getInt("student_id")); + student.setStudentName(rs.getString("student_name")); + student.setAge(rs.getInt("age")); + student.setStudentGender(rs.getString("gender")); + student.setGrade(rs.getInt("grade")); + student.setState(rs.getString("state")); + return student; + } +} diff --git a/persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/application.properties b/persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/application.properties new file mode 100644 index 0000000000..04c963ebf4 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/application.properties @@ -0,0 +1,5 @@ +# DataSource Configuration +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driverClassName=org.h2.Driver +spring.datasource.username=user +spring.datasource.password= # Leave this empty \ No newline at end of file diff --git a/persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/drop_student.sql b/persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/drop_student.sql new file mode 100644 index 0000000000..954545a862 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/drop_student.sql @@ -0,0 +1 @@ +DROP TABLE student; \ No newline at end of file diff --git a/persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/student.sql b/persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/student.sql new file mode 100644 index 0000000000..0e137f5445 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/student.sql @@ -0,0 +1,98 @@ + +CREATE TABLE student ( + student_id INT AUTO_INCREMENT PRIMARY KEY, + student_name VARCHAR(255) NOT NULL, + age INT, + grade INT NOT NULL, + gender VARCHAR(10) NOT NULL, + state VARCHAR(100) NOT NULL +); +-- Student 1 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('John Smith', 18, 3, 'Male', 'California'); + +-- Student 2 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Emily Johnson', 17, 2, 'Female', 'New York'); + +-- Student 3 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Michael Davis', 4, 1, 'Male', 'Texas'); + +-- Student 4 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Sophia Martinez', 2, 1, 'Female', 'Florida'); + +-- Student 5 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('William Brown', 5, 5, 'Male', 'California'); + +-- Student 6 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Olivia Garcia', 4, 2, 'Female', 'Texas'); + +-- Student 7 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Ethan Rodriguez', 3, 1, 'Male', 'New York'); + +-- Student 8 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Ava Hernandez', 2, 1, 'Female', 'Florida'); + +-- Student 9 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('James Wilson', 5, 4, 'Male', 'Texas'); + +-- Student 10 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Emma Miller', 3, 1, 'Female', 'California'); + +-- Student 11 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Benjamin Brown', 4, 1, 'Male', 'New York'); + +-- Student 12 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Mia Smith', 2, 1, 'Female', 'Florida'); + +-- Student 13 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Daniel Johnson', 5, 4, 'Male', 'California'); + +-- Student 14 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Ava Davis', 4, 2, 'Female', 'Texas'); + +-- Student 15 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Matthew Martinez', 3, 1, 'Male', 'New York'); + +-- Student 16 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Sophia Taylor', 2, 1, 'Female', 'Florida'); + +-- Student 17 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Alexander White', 5, 4, 'Male', 'California'); + +-- Student 18 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Olivia Johnson', 4, 2, 'Female', 'Texas'); + +-- Student 19 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Christopher Lee', 3, 1, 'Male', 'New York'); + +-- Student 20 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Emma Wilson', 2, 1, 'Female', 'Florida'); + +-- Student 21 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Elijah Smith', 5, 3, 'Male', 'Texas'); + +-- Student 22 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Isabella Davis', 4, 2, 'Female', 'California'); + +-- Student 23 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Liam Johnson', 3, 1, 'Male', 'New York'); + +-- Student 24 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Olivia Garcia', 2, 1, 'Female', 'Florida'); + +-- Student 25 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Noah Rodriguez', 5, 3, 'Male', 'Texas'); + +-- Student 26 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Sophia Hernandez', 4, 2, 'Female', 'California'); + +-- Student 27 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Mason Smith', 3, 1, 'Male', 'New York'); + +-- Student 28 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Ava Taylor', 2, 1, 'Female', 'Florida'); + +-- Student 29 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('William Brown', 5, 5, 'Male', 'Texas'); + +-- Student 30 +INSERT INTO student (student_name, age, grade, gender, state) VALUES ('Olivia Martinez', 4, 4, 'Female', 'California'); diff --git a/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcClient/JdbcClientUnitTest.java b/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcClient/JdbcClientUnitTest.java new file mode 100644 index 0000000000..b07a3c16f0 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcClient/JdbcClientUnitTest.java @@ -0,0 +1,106 @@ +package com.baeldung.jdbcClient; + +import com.baeldung.jdbcClient.dao.StudentDao; +import com.baeldung.jdbcClient.model.Student; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; + +@RunWith(SpringRunner.class) +@Sql(value = "/com.baeldung.jdbcClient/student.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) +@Sql(value = "/com.baeldung.jdbcClient/drop_student.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@SpringBootTest(classes = JdbcClientDemoApplication.class) +@TestPropertySource(locations = {"classpath:com.baeldung.jdbcClient/application.properties"}) +public class JdbcClientUnitTest { + private static final Logger logger = LoggerFactory.getLogger(JdbcClientUnitTest.class); + + @Autowired + private StudentDao studentDao; + + @Test + public void givenJdbcClient_whenInsertWithNamedParamAndSqlType_thenSuccess() { + logger.info("testing invoked successfully"); + Student student = getSampleStudent("Johny Dep", 8, 4, "Male", "New York"); + assertEquals(1, studentDao.insertWithSetParamWithNamedParamAndSqlType(student)); + } + + @Test + public void givenJdbcClient_whenQueryWithPositionalParams_thenSuccess() { + logger.info("testing invoked successfully"); + List students = studentDao.getStudentsOfGradeStateAndGenderWithPositionalParams( + 1, "New York", "Male"); + logger.info("number of students fetched " + students.size()); + assertEquals(6, students.size()); + } + + @Test + public void givenJdbcClient_whenQueryWithParamsInVarargs_thenSuccess() { + logger.info("testing invoked successfully"); + Student student = studentDao.getStudentsOfGradeStateAndGenderWithParamsInVarargs( + 1, "New York", "Male"); + assertNotNull(student); + } + + @Test + public void givenJdbcClient_whenQueryWithParamsInList_thenSuccess() { + logger.info("testing invoked successfully"); + List params = List.of(1, "New York", "Male"); + Optional optional = studentDao.getStudentsOfGradeStateAndGenderWithParamsInList(params); + if(optional.isPresent()) { + assertNotNull(optional.get()); + } else { + assertThrows(NoSuchElementException.class, () -> optional.get()); + } + } + + @Test + public void givenJdbcClient_whenQueryWithParamsIndex_thenSuccess() { + logger.info("testing invoked successfully"); + List students = studentDao.getStudentsOfGradeStateAndGenderWithParamIndex( + 1, "New York", "Male"); + assertEquals(6, students.size()); + } + @Test + public void givenJdbcClient_whenQueryWithNamedParam_thenSuccess() { + logger.info("testing invoked successfully"); + Integer count = studentDao.getCountOfStudentsOfGradeStateAndGenderWithNamedParam( + 1, "New York", "Male"); + logger.info("number of students fetched " + count); + assertEquals(6, count); + } + @Test + public void givenJdbcClient_whenQueryWithParamMap_thenSuccess() { + logger.info("testing invoked successfully"); + Map paramMap = Map.of( + "grade", 1, + "gender", "Male", + "state", "New York" + ); + List students = studentDao.getStudentsOfGradeStateAndGenderWithParamMap(paramMap); + logger.info("number of students fetched " + students.size()); + assertEquals(6, students.size()); + } + + private Student getSampleStudent(String name, int age, int grade, String gender, String state) { + Student student = new Student(); + student.setStudentName(name); + student.setStudentGender(gender); + student.setAge(age); + student.setGrade(grade); + student.setState(state); + return student; + } +} diff --git a/persistence-modules/spring-jdbc-2/src/test/resources/logback-test.xml b/persistence-modules/spring-jdbc-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-jdbc-2/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file From e46cc0443294523c6544e8ca85fb92ed912480af Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Thu, 19 Oct 2023 20:58:43 +0530 Subject: [PATCH 18/91] BAEL-7135 A Guide to Spring 6 JdbcClient API --- persistence-modules/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index f35b22a19d..867c12291a 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -105,6 +105,7 @@ spring-jpa spring-jpa-2 spring-jdbc + spring-jdbc-2 spring-jooq spring-mybatis spring-persistence-simple From 94d1847f9d1ff5ae13aec00094cf15967c84fa7a Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Thu, 19 Oct 2023 21:09:34 +0530 Subject: [PATCH 19/91] BAEL-7135 A Guide to Spring 6 JdbcClient API --- persistence-modules/spring-jdbc-2/pom.xml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/persistence-modules/spring-jdbc-2/pom.xml b/persistence-modules/spring-jdbc-2/pom.xml index 79c5ad100c..24744b28dc 100644 --- a/persistence-modules/spring-jdbc-2/pom.xml +++ b/persistence-modules/spring-jdbc-2/pom.xml @@ -44,9 +44,6 @@ org.apache.maven.plugins maven-compiler-plugin - - --enable-preview - @@ -88,7 +85,6 @@ - 17 3.2.0-SNAPSHOT UTF-8 From 1a7d3aff21733046c7fc019e1c3da01c3b9a87a8 Mon Sep 17 00:00:00 2001 From: timis1 Date: Sat, 21 Oct 2023 20:10:35 +0300 Subject: [PATCH 20/91] JAVA-23808 Rewrite Custom Spliterator Section of Introduction to Spliterator Article --- .../spliterator/CustomSpliterator.java | 48 ++++++++++++++++++ .../com/baeldung/spliterator/Executor.java | 12 ----- .../spliterator/RelatedAuthorCounter.java | 27 ---------- .../spliterator/RelatedAuthorSpliterator.java | 49 ------------------ .../spliterator/ExecutorUnitTest.java | 50 ++++++++++++++----- 5 files changed, 86 insertions(+), 100 deletions(-) create mode 100644 core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/CustomSpliterator.java delete mode 100644 core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Executor.java delete mode 100644 core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorCounter.java delete mode 100644 core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorSpliterator.java diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/CustomSpliterator.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/CustomSpliterator.java new file mode 100644 index 0000000000..2f806cccda --- /dev/null +++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/CustomSpliterator.java @@ -0,0 +1,48 @@ +package com.baeldung.spliterator; + +import java.util.List; +import java.util.Spliterator; +import java.util.function.Consumer; + +public class CustomSpliterator implements Spliterator { + private final List elements; + private int currentIndex; + + public CustomSpliterator(List elements) { + this.elements = elements; + this.currentIndex = 0; + } + + @Override + public boolean tryAdvance(Consumer action) { + if (currentIndex < elements.size()) { + action.accept(elements.get(currentIndex)); + currentIndex++; + return true; + } + return false; + } + + @Override + public Spliterator trySplit() { + int currentSize = elements.size() - currentIndex; + if (currentSize < 2) { + return null; + } + + int splitIndex = currentIndex + currentSize / 2; + CustomSpliterator newSpliterator = new CustomSpliterator(elements.subList(currentIndex, splitIndex)); + currentIndex = splitIndex; + return newSpliterator; + } + + @Override + public long estimateSize() { + return elements.size() - currentIndex; + } + + @Override + public int characteristics() { + return ORDERED | SIZED | SUBSIZED | NONNULL; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Executor.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Executor.java deleted file mode 100644 index 3dc2fa06bb..0000000000 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/Executor.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.spliterator; - -import java.util.stream.Stream; - -public class Executor { - - public static int countAutors(Stream stream) { - RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true), - RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine); - return wordCounter.getCounter(); - } -} \ No newline at end of file diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorCounter.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorCounter.java deleted file mode 100644 index 8800eac55b..0000000000 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorCounter.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.spliterator; - -public class RelatedAuthorCounter { - private final int counter; - private final boolean isRelated; - - public RelatedAuthorCounter(int counter, boolean isRelated) { - this.counter = counter; - this.isRelated = isRelated; - } - - public RelatedAuthorCounter accumulate(Author author) { - if (author.getRelatedArticleId() == 0) { - return isRelated ? this : new RelatedAuthorCounter(counter, true); - } else { - return isRelated ? new RelatedAuthorCounter(counter + 1, false) : this; - } - } - - public RelatedAuthorCounter combine(RelatedAuthorCounter RelatedAuthorCounter) { - return new RelatedAuthorCounter(counter + RelatedAuthorCounter.counter, RelatedAuthorCounter.isRelated); - } - - public int getCounter() { - return counter; - } -} diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorSpliterator.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorSpliterator.java deleted file mode 100644 index 93c83b8127..0000000000 --- a/core-java-modules/core-java-8/src/main/java/com/baeldung/spliterator/RelatedAuthorSpliterator.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.baeldung.spliterator; - -import java.util.List; -import java.util.Spliterator; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; - -public class RelatedAuthorSpliterator implements Spliterator { - private final List list; - AtomicInteger current = new AtomicInteger(); - - public RelatedAuthorSpliterator(List list) { - this.list = list; - } - - @Override - public boolean tryAdvance(Consumer action) { - - action.accept(list.get(current.getAndIncrement())); - return current.get() < list.size(); - } - - @Override - public Spliterator trySplit() { - int currentSize = list.size() - current.get(); - if (currentSize < 10) { - return null; - } - for (int splitPos = currentSize / 2 + current.intValue(); splitPos < list.size(); splitPos++) { - if (list.get(splitPos).getRelatedArticleId() == 0) { - Spliterator spliterator = new RelatedAuthorSpliterator(list.subList(current.get(), splitPos)); - current.set(splitPos); - return spliterator; - } - } - return null; - } - - @Override - public long estimateSize() { - return list.size() - current.get(); - } - - @Override - public int characteristics() { - return CONCURRENT; - } - -} diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/spliterator/ExecutorUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/spliterator/ExecutorUnitTest.java index 4628f95481..30760ddf6f 100644 --- a/core-java-modules/core-java-8/src/test/java/com/baeldung/spliterator/ExecutorUnitTest.java +++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/spliterator/ExecutorUnitTest.java @@ -6,10 +6,10 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Spliterator; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.Stream; -import java.util.stream.StreamSupport; - import org.junit.Before; import org.junit.Test; @@ -18,22 +18,50 @@ import lombok.extern.slf4j.Slf4j; @Slf4j public class ExecutorUnitTest { Article article; - Stream stream; - Spliterator spliterator; @Before public void init() { article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0); - - spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors()); } @Test - public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() { - Stream stream2 = StreamSupport.stream(spliterator, true); - assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9); + public void givenAStreamOfIntegers_whenProcessedSequentialCustomSpliterator_countProducesRightOutput() { + List numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + numbers.add(3); + numbers.add(4); + numbers.add(5); + + CustomSpliterator customSpliterator = new CustomSpliterator(numbers); + + AtomicInteger sum = new AtomicInteger(); + + customSpliterator.forEachRemaining(sum::addAndGet); + assertThat(sum.get()).isEqualTo(15); + } + + @Test + public void givenAStreamOfIntegers_whenProcessedInParallelWithCustomSpliterator_countProducesRightOutput() { + List numbers = new ArrayList<>(); + numbers.add(1); + numbers.add(2); + numbers.add(3); + numbers.add(4); + numbers.add(5); + + CustomSpliterator customSpliterator = new CustomSpliterator(numbers); + + // Create a ForkJoinPool for parallel processing + ForkJoinPool forkJoinPool = ForkJoinPool.commonPool(); + + AtomicInteger sum = new AtomicInteger(0); + + // Process elements in parallel using parallelStream + forkJoinPool.submit(() -> customSpliterator.forEachRemaining(sum::addAndGet)).join(); + assertThat(sum.get()).isEqualTo(15); } @Test @@ -43,9 +71,7 @@ public class ExecutorUnitTest { .collect(Collectors.toList()); Spliterator
spliterator = articles.spliterator(); - while (spliterator.tryAdvance(article -> article.setName(article.getName() - .concat("- published by Baeldung")))) - ; + while(spliterator.tryAdvance(article -> article.setName(article.getName().concat("- published by Baeldung")))); articles.forEach(article -> assertThat(article.getName()).isEqualTo("Java- published by Baeldung")); } From 8282238126d5cf8a04a60039fa1604534ecc5ae9 Mon Sep 17 00:00:00 2001 From: timis1 Date: Sat, 21 Oct 2023 22:49:58 +0300 Subject: [PATCH 21/91] JAVA-25525 Verify reactive-systems module --- reactive-systems/docker-compose.yml | 18 ++++++++++++++++++ reactive-systems/inventory-service/Dockerfile | 2 +- reactive-systems/order-service/Dockerfile | 2 +- reactive-systems/shipping-service/Dockerfile | 2 +- 4 files changed, 21 insertions(+), 3 deletions(-) create mode 100644 reactive-systems/docker-compose.yml diff --git a/reactive-systems/docker-compose.yml b/reactive-systems/docker-compose.yml new file mode 100644 index 0000000000..2e40d1999a --- /dev/null +++ b/reactive-systems/docker-compose.yml @@ -0,0 +1,18 @@ +version: '3' +services: + frontend: + build: ./frontend + ports: + - "80:80" + order-service: + build: ./order-service + ports: + - "8080:8080" + inventory-service: + build: ./inventory-service + ports: + - "8081:8081" + shipping-service: + build: ./shipping-service + ports: + - "8082:8082" \ No newline at end of file diff --git a/reactive-systems/inventory-service/Dockerfile b/reactive-systems/inventory-service/Dockerfile index d37887cf34..d0900decfa 100644 --- a/reactive-systems/inventory-service/Dockerfile +++ b/reactive-systems/inventory-service/Dockerfile @@ -1,3 +1,3 @@ FROM openjdk:8-jdk-alpine -COPY target/inventory-service-async-0.0.1-SNAPSHOT.jar app.jar +COPY target/inventory-service-0.0.1-SNAPSHOT.jar app.jar ENTRYPOINT ["java","-jar","-Dspring.profiles.active=docker","/app.jar"] \ No newline at end of file diff --git a/reactive-systems/order-service/Dockerfile b/reactive-systems/order-service/Dockerfile index 516e088a05..e48c19c2b1 100644 --- a/reactive-systems/order-service/Dockerfile +++ b/reactive-systems/order-service/Dockerfile @@ -1,3 +1,3 @@ FROM openjdk:8-jdk-alpine -COPY target/order-service-async-0.0.1-SNAPSHOT.jar app.jar +COPY target/order-service-0.0.1-SNAPSHOT.jar app.jar ENTRYPOINT ["java","-jar","-Dspring.profiles.active=docker","/app.jar"] \ No newline at end of file diff --git a/reactive-systems/shipping-service/Dockerfile b/reactive-systems/shipping-service/Dockerfile index 4906d1d9a8..ff57bb953d 100644 --- a/reactive-systems/shipping-service/Dockerfile +++ b/reactive-systems/shipping-service/Dockerfile @@ -1,3 +1,3 @@ FROM openjdk:8-jdk-alpine -COPY target/shipping-service-async-0.0.1-SNAPSHOT.jar app.jar +COPY target/shipping-service-0.0.1-SNAPSHOT.jar app.jar ENTRYPOINT ["java","-jar","-Dspring.profiles.active=docker","/app.jar"] \ No newline at end of file From 7392b003f1cee2c312f29a17d1f46cb86aa0bcd9 Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Mon, 23 Oct 2023 14:33:05 +0530 Subject: [PATCH 22/91] Adding sourcecode for reference in the article tracked under BAEL-6970. --- libraries-llms/README.md | 6 ++ libraries-llms/pom.xml | 43 ++++++++ libraries-llms/src/main/resources/logback.xml | 17 ++++ .../langchain/ChainWithDocumentLiveTests.java | 98 +++++++++++++++++++ .../langchain/ChatWithDocumentLiveTests.java | 80 +++++++++++++++ .../langchain/ChatWithMemoryLiveTests.java | 45 +++++++++ .../com/baeldung/langchain/Constants.java | 7 ++ .../langchain/PromptTemplatesLiveTests.java | 42 ++++++++ .../langchain/ServiceWithToolsLiveTests.java | 52 ++++++++++ .../example-files/simpson's_adventures.txt | 28 ++++++ pom.xml | 2 + 11 files changed, 420 insertions(+) create mode 100644 libraries-llms/README.md create mode 100644 libraries-llms/pom.xml create mode 100644 libraries-llms/src/main/resources/logback.xml create mode 100644 libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTests.java create mode 100644 libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTests.java create mode 100644 libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTests.java create mode 100644 libraries-llms/src/test/java/com/baeldung/langchain/Constants.java create mode 100644 libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTests.java create mode 100644 libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTests.java create mode 100644 libraries-llms/src/test/resources/example-files/simpson's_adventures.txt diff --git a/libraries-llms/README.md b/libraries-llms/README.md new file mode 100644 index 0000000000..2e250d42d6 --- /dev/null +++ b/libraries-llms/README.md @@ -0,0 +1,6 @@ +## Language Model Integration Libraries + +This module contains articles about libraries for language model integration in Java. + +### Relevant articles +- [Introduction to LangChain](https://www.baeldung.com/langchain) \ No newline at end of file diff --git a/libraries-llms/pom.xml b/libraries-llms/pom.xml new file mode 100644 index 0000000000..3d5ed6830e --- /dev/null +++ b/libraries-llms/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + libraries-llms + libraries-llms + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + dev.langchain4j + langchain4j + ${langchain4j.version} + + + dev.langchain4j + langchain4j-embeddings + ${langchain4j.version} + + + dev.langchain4j + langchain4j-open-ai + ${langchain4j.version} + + + dev.langchain4j + langchain4j-embeddings-all-minilm-l6-v2 + ${langchain4j.version} + + + + + 0.23.0 + + + \ No newline at end of file diff --git a/libraries-llms/src/main/resources/logback.xml b/libraries-llms/src/main/resources/logback.xml new file mode 100644 index 0000000000..23c5605a05 --- /dev/null +++ b/libraries-llms/src/main/resources/logback.xml @@ -0,0 +1,17 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - + %msg%n + + + + + + + + + + \ No newline at end of file diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTests.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTests.java new file mode 100644 index 0000000000..4ab5eaa68d --- /dev/null +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTests.java @@ -0,0 +1,98 @@ +package com.baeldung.langchain; + +import static dev.langchain4j.data.document.FileSystemDocumentLoader.loadDocument; +import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; +import static java.time.Duration.ofSeconds; +import static java.util.stream.Collectors.joining; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + +import org.junit.Assert; +import org.junit.Test; + +import dev.langchain4j.data.document.Document; +import dev.langchain4j.data.document.DocumentSplitter; +import dev.langchain4j.data.document.splitter.DocumentSplitters; +import dev.langchain4j.data.embedding.Embedding; +import dev.langchain4j.data.message.AiMessage; +import dev.langchain4j.data.segment.TextSegment; +import dev.langchain4j.model.chat.ChatLanguageModel; +import dev.langchain4j.model.embedding.AllMiniLmL6V2EmbeddingModel; +import dev.langchain4j.model.embedding.EmbeddingModel; +import dev.langchain4j.model.input.Prompt; +import dev.langchain4j.model.input.PromptTemplate; +import dev.langchain4j.model.openai.OpenAiChatModel; +import dev.langchain4j.model.openai.OpenAiTokenizer; +import dev.langchain4j.store.embedding.EmbeddingMatch; +import dev.langchain4j.store.embedding.EmbeddingStore; +import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore; + +public class ChainWithDocumentLiveTests { + + @Test + public void givenChainWithDocument_whenPrompted_thenValidResponse() { + + Document document = loadDocument(toPath("src/test/resources/example-files/simpson's_adventures.txt")); + DocumentSplitter splitter = DocumentSplitters.recursive(100, 0, new OpenAiTokenizer(GPT_3_5_TURBO)); + List segments = splitter.split(document); + + EmbeddingModel embeddingModel = new AllMiniLmL6V2EmbeddingModel(); + List embeddings = embeddingModel.embedAll(segments) + .content(); + EmbeddingStore embeddingStore = new InMemoryEmbeddingStore<>(); + embeddingStore.addAll(embeddings, segments); + + String question = "Who is Simpson?"; + Embedding questionEmbedding = embeddingModel.embed(question) + .content(); + int maxResults = 3; + double minScore = 0.7; + List> relevantEmbeddings = embeddingStore.findRelevant(questionEmbedding, maxResults, minScore); + + PromptTemplate promptTemplate = PromptTemplate.from("Answer the following question to the best of your ability:\n" + "\n" + "Question:\n" + "{{question}}\n" + "\n" + "Base your answer on the following information:\n" + "{{information}}"); + + String information = relevantEmbeddings.stream() + .map(match -> match.embedded() + .text()) + .collect(joining("\n\n")); + + Map variables = new HashMap<>(); + variables.put("question", question); + variables.put("information", information); + + Prompt prompt = promptTemplate.apply(variables); + ChatLanguageModel chatModel = OpenAiChatModel.builder() + .apiKey(Constants.OPEN_API_KEY) + .timeout(ofSeconds(60)) + .build(); + AiMessage aiMessage = chatModel.generate(prompt.toUserMessage()) + .content(); + + Logger.getGlobal() + .info(aiMessage.text()); + Assert.assertNotNull(aiMessage.text()); + + } + + private static Path toPath(String fileName) { + try { + URL fileUrl = new File(fileName).toURI() + .toURL(); + System.out.println(new File(fileName).toURI() + .toURL()); + return Paths.get(fileUrl.toURI()); + } catch (URISyntaxException | MalformedURLException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTests.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTests.java new file mode 100644 index 0000000000..e75465e5b7 --- /dev/null +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTests.java @@ -0,0 +1,80 @@ +package com.baeldung.langchain; + +import static dev.langchain4j.data.document.FileSystemDocumentLoader.loadDocument; +import static java.time.Duration.ofSeconds; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.logging.Logger; + +import org.junit.Assert; +import org.junit.Test; + +import dev.langchain4j.chain.ConversationalRetrievalChain; +import dev.langchain4j.data.document.Document; +import dev.langchain4j.data.document.splitter.DocumentSplitters; +import dev.langchain4j.data.segment.TextSegment; +import dev.langchain4j.model.chat.ChatLanguageModel; +import dev.langchain4j.model.embedding.AllMiniLmL6V2EmbeddingModel; +import dev.langchain4j.model.embedding.EmbeddingModel; +import dev.langchain4j.model.openai.OpenAiChatModel; +import dev.langchain4j.retriever.EmbeddingStoreRetriever; +import dev.langchain4j.store.embedding.EmbeddingStore; +import dev.langchain4j.store.embedding.EmbeddingStoreIngestor; +import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore; + +public class ChatWithDocumentLiveTests { + + @Test + public void givenDocument_whenPrompted_thenValidResponse() { + + EmbeddingModel embeddingModel = new AllMiniLmL6V2EmbeddingModel(); + + EmbeddingStore embeddingStore = new InMemoryEmbeddingStore<>(); + + EmbeddingStoreIngestor ingestor = EmbeddingStoreIngestor.builder() + .documentSplitter(DocumentSplitters.recursive(500, 0)) + .embeddingModel(embeddingModel) + .embeddingStore(embeddingStore) + .build(); + + Document document = loadDocument(toPath("src/test/resources/example-files/simpson's_adventures.txt")); + ingestor.ingest(document); + + ChatLanguageModel chatModel = OpenAiChatModel.builder() + .apiKey(Constants.OPEN_API_KEY) + .timeout(ofSeconds(60)) + .build(); + + ConversationalRetrievalChain chain = ConversationalRetrievalChain.builder() + .chatLanguageModel(chatModel) + .retriever(EmbeddingStoreRetriever.from(embeddingStore, embeddingModel)) + // .chatMemory() // you can override default chat memory + // .promptTemplate() // you can override default prompt template + .build(); + + String answer = chain.execute("Who is Simpson?"); + + Logger.getGlobal() + .info(answer); + Assert.assertNotNull(answer); + + } + + private static Path toPath(String fileName) { + try { + URL fileUrl = new File(fileName).toURI() + .toURL(); + System.out.println(new File(fileName).toURI() + .toURL()); + return Paths.get(fileUrl.toURI()); + } catch (URISyntaxException | MalformedURLException e) { + throw new RuntimeException(e); + } + } + +} diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTests.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTests.java new file mode 100644 index 0000000000..4395c52274 --- /dev/null +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTests.java @@ -0,0 +1,45 @@ +package com.baeldung.langchain; + +import dev.langchain4j.data.message.AiMessage; +import dev.langchain4j.memory.ChatMemory; +import dev.langchain4j.memory.chat.TokenWindowChatMemory; +import dev.langchain4j.model.chat.ChatLanguageModel; +import dev.langchain4j.model.openai.OpenAiChatModel; +import dev.langchain4j.model.openai.OpenAiTokenizer; + +import static dev.langchain4j.data.message.UserMessage.userMessage; +import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; + +import java.util.logging.Logger; + +import org.junit.Assert; +import org.junit.Test; + +public class ChatWithMemoryLiveTests { + + @Test + public void givenMemory_whenPrompted_thenValidResponse() { + + ChatLanguageModel model = OpenAiChatModel.withApiKey(Constants.OPEN_API_KEY); + ChatMemory chatMemory = TokenWindowChatMemory.withMaxTokens(300, new OpenAiTokenizer(GPT_3_5_TURBO)); + + chatMemory.add(userMessage("Hello, my name is Kumar")); + AiMessage answer = model.generate(chatMemory.messages()) + .content(); + Logger.getGlobal() + .info(answer.text()); + Assert.assertNotNull(answer.text()); + chatMemory.add(answer); + + chatMemory.add(userMessage("What is my name?")); + AiMessage answerWithName = model.generate(chatMemory.messages()) + .content(); + Logger.getGlobal() + .info(answerWithName.text()); + Assert.assertTrue(answerWithName.text() + .contains("Kumar")); + chatMemory.add(answerWithName); + + } + +} diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java b/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java new file mode 100644 index 0000000000..15645ce68e --- /dev/null +++ b/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java @@ -0,0 +1,7 @@ +package com.baeldung.langchain; + +public class Constants { + + public static String OPEN_API_KEY = "demo"; + +} diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTests.java b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTests.java new file mode 100644 index 0000000000..c485b9cdf6 --- /dev/null +++ b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTests.java @@ -0,0 +1,42 @@ +package com.baeldung.langchain; + +import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; + +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + +import org.junit.Test; + +import dev.langchain4j.model.chat.ChatLanguageModel; +import dev.langchain4j.model.input.Prompt; +import dev.langchain4j.model.input.PromptTemplate; +import dev.langchain4j.model.openai.OpenAiChatModel; + +import org.junit.Assert; + +public class PromptTemplatesLiveTests { + + @Test + public void givenPromptTemplate_whenSuppliedInput_thenValidResponse() { + + PromptTemplate promptTemplate = PromptTemplate.from("Tell me a {{adjective}} joke about {{content}}.."); + Map variables = new HashMap<>(); + variables.put("adjective", "funny"); + variables.put("content", "humans"); + Prompt prompt = promptTemplate.apply(variables); + + ChatLanguageModel model = OpenAiChatModel.builder() + .apiKey(Constants.OPEN_API_KEY) + .modelName(GPT_3_5_TURBO) + .temperature(0.3) + .build(); + + String response = model.generate(prompt.text()); + Logger.getGlobal() + .info(response); + Assert.assertNotNull(response); + + } + +} diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTests.java b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTests.java new file mode 100644 index 0000000000..1e4b356334 --- /dev/null +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTests.java @@ -0,0 +1,52 @@ +package com.baeldung.langchain; + +import java.util.logging.Logger; + +import org.junit.Assert; +import org.junit.Test; + +import dev.langchain4j.agent.tool.Tool; +import dev.langchain4j.memory.chat.MessageWindowChatMemory; +import dev.langchain4j.model.openai.OpenAiChatModel; +import dev.langchain4j.service.AiServices; + +public class ServiceWithToolsLiveTests { + + static class Calculator { + + @Tool("Calculates the length of a string") + int stringLength(String s) { + return s.length(); + } + + @Tool("Calculates the sum of two numbers") + int add(int a, int b) { + return a + b; + } + + } + + interface Assistant { + + String chat(String userMessage); + } + + @Test + public void givenServiceWithTools_whenPrompted_thenValidResponse() { + + Assistant assistant = AiServices.builder(Assistant.class) + .chatLanguageModel(OpenAiChatModel.withApiKey(Constants.OPEN_API_KEY)) + .tools(new Calculator()) + .chatMemory(MessageWindowChatMemory.withMaxMessages(10)) + .build(); + + String question = "What is the sum of the numbers of letters in the words \"language\" and \"model\"?"; + String answer = assistant.chat(question); + + Logger.getGlobal() + .info(answer); + Assert.assertNotNull(answer); + + } + +} diff --git a/libraries-llms/src/test/resources/example-files/simpson's_adventures.txt b/libraries-llms/src/test/resources/example-files/simpson's_adventures.txt new file mode 100644 index 0000000000..ae6de80be0 --- /dev/null +++ b/libraries-llms/src/test/resources/example-files/simpson's_adventures.txt @@ -0,0 +1,28 @@ +Once upon a time in the town of VeggieVille, there lived a cheerful carrot named Simpson. +Simpson was a radiant carrot, always beaming with joy and positivity. +His vibrant orange skin and lush green top were a sight to behold, but it was his infectious laughter and warm personality that really set him apart. + +Simpson had a diverse group of friends, each a vegetable with their own unique characteristics. +There was Bella the blushing beetroot, always ready with a riddle or two; Timmy the timid tomato, a gentle soul with a heart of gold; and Percy the prankster potato, whose jokes always brought a smile to everyone's faces. +Despite their differences, they shared a close bond, their friendship as robust as their natural goodness. + +Their lives were filled with delightful adventures, from playing hide-and-seek amidst the leafy lettuce to swimming in the dewy droplets that pooled on the cabbage leaves. +Their favorite place, though, was the sunlit corner of the vegetable patch, where they would bask in the warmth of the sun, share stories, and have hearty laughs. + +One day, a bunch of pesky caterpillars invaded VeggieVille. +The vegetables were terrified, fearing they would be nibbled to nothingness. +But Simpson, with his usual sunny disposition, had an idea. +He proposed they host a grand feast for the caterpillars, with the juiciest leaves from the outskirts of the town. +Simpson's optimism was contagious, and his friends eagerly joined in to prepare the feast. + +When the caterpillars arrived, they were pleasantly surprised. +They enjoyed the feast and were so impressed with the vegetables' hospitality that they promised not to trouble VeggieVille again. +In return, they agreed to help pollinate the flowers, contributing to a more lush and vibrant VeggieVille. + +Simpson's idea had saved the day, but he humbly attributed the success to their teamwork and friendship. +They celebrated their victory with a grand party, filled with laughter, dance, and merry games. +That night, under the twinkling stars, they made a pact to always stand by each other, come what may. + +From then on, the story of the happy carrot and his friends spread far and wide, a tale of friendship, unity, and positivity. +Simpson, Bella, Timmy, and Percy continued to live their joyful lives, their laughter echoing through VeggieVille. +And so, the tale of the happy carrot and his friends serves as a reminder that no matter the challenge, with optimism, teamwork, and a bit of creativity, anything is possible. \ No newline at end of file diff --git a/pom.xml b/pom.xml index 3f4da4bdb0..a391a1c774 100644 --- a/pom.xml +++ b/pom.xml @@ -936,6 +936,7 @@ spring-di-4 spring-kafka-2 + libraries-llms @@ -1223,6 +1224,7 @@ spring-di-4 spring-kafka-2 + libraries-llms From 9796fd51979d6f002451db45d36941b42dd988a2 Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Mon, 23 Oct 2023 16:04:27 +0530 Subject: [PATCH 23/91] Adding sourcecode for reference in the article tracked under BAEL-6970. --- ...nWithDocumentLiveTests.java => ChainWithDocumentLiveTest.java} | 0 ...atWithDocumentLiveTests.java => ChatWithDocumentLiveTest.java} | 0 .../{ChatWithMemoryLiveTests.java => ChatWithMemoryLiveTest.java} | 0 ...PromptTemplatesLiveTests.java => PromptTemplatesLiveTest.java} | 0 ...rviceWithToolsLiveTests.java => ServiceWithToolsLiveTest.java} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename libraries-llms/src/test/java/com/baeldung/langchain/{ChainWithDocumentLiveTests.java => ChainWithDocumentLiveTest.java} (100%) rename libraries-llms/src/test/java/com/baeldung/langchain/{ChatWithDocumentLiveTests.java => ChatWithDocumentLiveTest.java} (100%) rename libraries-llms/src/test/java/com/baeldung/langchain/{ChatWithMemoryLiveTests.java => ChatWithMemoryLiveTest.java} (100%) rename libraries-llms/src/test/java/com/baeldung/langchain/{PromptTemplatesLiveTests.java => PromptTemplatesLiveTest.java} (100%) rename libraries-llms/src/test/java/com/baeldung/langchain/{ServiceWithToolsLiveTests.java => ServiceWithToolsLiveTest.java} (100%) diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTests.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java similarity index 100% rename from libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTests.java rename to libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTests.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java similarity index 100% rename from libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTests.java rename to libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTests.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java similarity index 100% rename from libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTests.java rename to libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTests.java b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java similarity index 100% rename from libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTests.java rename to libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTests.java b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java similarity index 100% rename from libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTests.java rename to libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java From c36a6cc5a4f70ca32cd6397f45ad83a890248deb Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Mon, 23 Oct 2023 16:05:03 +0530 Subject: [PATCH 24/91] Changed the name of tests from LiveTests to LiveTest --- .../java/com/baeldung/langchain/ChainWithDocumentLiveTest.java | 2 +- .../java/com/baeldung/langchain/ChatWithDocumentLiveTest.java | 2 +- .../java/com/baeldung/langchain/ChatWithMemoryLiveTest.java | 2 +- .../java/com/baeldung/langchain/PromptTemplatesLiveTest.java | 2 +- .../java/com/baeldung/langchain/ServiceWithToolsLiveTest.java | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java index 4ab5eaa68d..b1db486d84 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java @@ -36,7 +36,7 @@ import dev.langchain4j.store.embedding.EmbeddingMatch; import dev.langchain4j.store.embedding.EmbeddingStore; import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore; -public class ChainWithDocumentLiveTests { +public class ChainWithDocumentLiveTest { @Test public void givenChainWithDocument_whenPrompted_thenValidResponse() { diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java index e75465e5b7..643c56520e 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java @@ -27,7 +27,7 @@ import dev.langchain4j.store.embedding.EmbeddingStore; import dev.langchain4j.store.embedding.EmbeddingStoreIngestor; import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore; -public class ChatWithDocumentLiveTests { +public class ChatWithDocumentLiveTest { @Test public void givenDocument_whenPrompted_thenValidResponse() { diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java index 4395c52274..5e0057d23c 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java @@ -15,7 +15,7 @@ import java.util.logging.Logger; import org.junit.Assert; import org.junit.Test; -public class ChatWithMemoryLiveTests { +public class ChatWithMemoryLiveTest { @Test public void givenMemory_whenPrompted_thenValidResponse() { diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java index c485b9cdf6..5f155d3dba 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java @@ -15,7 +15,7 @@ import dev.langchain4j.model.openai.OpenAiChatModel; import org.junit.Assert; -public class PromptTemplatesLiveTests { +public class PromptTemplatesLiveTest { @Test public void givenPromptTemplate_whenSuppliedInput_thenValidResponse() { diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java index 1e4b356334..024c1523e8 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java @@ -10,7 +10,7 @@ import dev.langchain4j.memory.chat.MessageWindowChatMemory; import dev.langchain4j.model.openai.OpenAiChatModel; import dev.langchain4j.service.AiServices; -public class ServiceWithToolsLiveTests { +public class ServiceWithToolsLiveTest { static class Calculator { From 9756cb1d102271b8a71d2efa217108dc3d6d34bf Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Mon, 23 Oct 2023 23:44:18 +0530 Subject: [PATCH 25/91] Add UnicodeLetterChecker to check if String contains Unicode --- .../unicode/UnicodeLetterChecker.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/unicode/UnicodeLetterChecker.java diff --git a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/unicode/UnicodeLetterChecker.java b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/unicode/UnicodeLetterChecker.java new file mode 100644 index 0000000000..df561c88ea --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/unicode/UnicodeLetterChecker.java @@ -0,0 +1,27 @@ +package com.baeldung.unicode; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.apache.commons.lang3.StringUtils; + +public class UnicodeLetterChecker { + public boolean characterClassCheck(String input) { + for (char c : input.toCharArray()) { + if (!Character.isLetter(c)) { + return false; + } + } + return true; + } + public boolean regexCheck(String input) { + Pattern pattern = Pattern.compile("^\\p{L}+$"); + Matcher matcher = pattern.matcher(input); + return matcher.matches(); + } + public boolean isAlphaCheck(String input) { + return StringUtils.isAlpha(input); + } + public boolean StreamsCheck(String input){ + return input.codePoints().allMatch(Character::isLetter); + } +} From e99ce4da19dfa17e27999855c13ce9a1b0eabcb1 Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Mon, 23 Oct 2023 23:45:43 +0530 Subject: [PATCH 26/91] Add tests for UnicodeLetterChecker --- .../unicode/UnicodeLetterCheckerUnitTest.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/unicode/UnicodeLetterCheckerUnitTest.java diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/unicode/UnicodeLetterCheckerUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/unicode/UnicodeLetterCheckerUnitTest.java new file mode 100644 index 0000000000..a7ed9e5db9 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/unicode/UnicodeLetterCheckerUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.unicode; + +import org.junit.Test; +import static org.junit.Assert.assertTrue; + +public class UnicodeLetterCheckerUnitTest { + @Test + public void givenString_whenUsingIsLetter_thenReturnTrue() { + UnicodeLetterChecker checker = new UnicodeLetterChecker(); + + boolean isUnicodeLetter = checker.characterClassCheck("HelloWorld"); + assertTrue(isUnicodeLetter); + } + + @Test + public void givenString_whenUsingRegex_thenReturnTrue() { + UnicodeLetterChecker checker = new UnicodeLetterChecker(); + + boolean isUnicodeLetter = checker.regexCheck("HelloWorld"); + assertTrue(isUnicodeLetter); + } + + @Test + public void givenString_whenUsingIsAlpha_thenReturnTrue() { + UnicodeLetterChecker checker = new UnicodeLetterChecker(); + + boolean isUnicodeLetter = checker.isAlphaCheck("HelloWorld"); + assertTrue(isUnicodeLetter); + } + + @Test + public void givenString_whenUsingStreams_thenReturnTrue() { + UnicodeLetterChecker checker = new UnicodeLetterChecker(); + + boolean isUnicodeLetter = checker.StreamsCheck("HelloWorld"); + assertTrue(isUnicodeLetter); + } +} From 03c9dce8cf0a141e8dfd705d03aaaef06579dd30 Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Wed, 25 Oct 2023 10:40:32 +0530 Subject: [PATCH 27/91] Incorporated some review comments on the code. --- libraries-llms/src/main/resources/logback.xml | 17 ---- .../langchain/ChainWithDocumentLiveTest.java | 73 +++++++---------- .../langchain/ChatWithDocumentLiveTest.java | 78 ++++++++++++------- .../langchain/ChatWithMemoryLiveTest.java | 18 ++--- .../com/baeldung/langchain/Constants.java | 7 +- .../langchain/PromptTemplatesLiveTest.java | 10 ++- .../langchain/ServiceWithToolsLiveTest.java | 13 ++-- pom.xml | 4 +- 8 files changed, 110 insertions(+), 110 deletions(-) delete mode 100644 libraries-llms/src/main/resources/logback.xml diff --git a/libraries-llms/src/main/resources/logback.xml b/libraries-llms/src/main/resources/logback.xml deleted file mode 100644 index 23c5605a05..0000000000 --- a/libraries-llms/src/main/resources/logback.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - - %msg%n - - - - - - - - - - \ No newline at end of file diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java index b1db486d84..556f394866 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java @@ -1,9 +1,7 @@ package com.baeldung.langchain; import static dev.langchain4j.data.document.FileSystemDocumentLoader.loadDocument; -import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; import static java.time.Duration.ofSeconds; -import static java.util.stream.Collectors.joining; import java.io.File; import java.net.MalformedURLException; @@ -11,75 +9,64 @@ import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.logging.Logger; import org.junit.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import dev.langchain4j.chain.ConversationalRetrievalChain; import dev.langchain4j.data.document.Document; -import dev.langchain4j.data.document.DocumentSplitter; import dev.langchain4j.data.document.splitter.DocumentSplitters; -import dev.langchain4j.data.embedding.Embedding; -import dev.langchain4j.data.message.AiMessage; import dev.langchain4j.data.segment.TextSegment; +import dev.langchain4j.memory.chat.MessageWindowChatMemory; import dev.langchain4j.model.chat.ChatLanguageModel; import dev.langchain4j.model.embedding.AllMiniLmL6V2EmbeddingModel; import dev.langchain4j.model.embedding.EmbeddingModel; -import dev.langchain4j.model.input.Prompt; import dev.langchain4j.model.input.PromptTemplate; import dev.langchain4j.model.openai.OpenAiChatModel; -import dev.langchain4j.model.openai.OpenAiTokenizer; -import dev.langchain4j.store.embedding.EmbeddingMatch; +import dev.langchain4j.retriever.EmbeddingStoreRetriever; import dev.langchain4j.store.embedding.EmbeddingStore; +import dev.langchain4j.store.embedding.EmbeddingStoreIngestor; import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore; public class ChainWithDocumentLiveTest { + + Logger logger = LoggerFactory.getLogger(ChainWithDocumentLiveTest.class); @Test - public void givenChainWithDocument_whenPrompted_thenValidResponse() { - - Document document = loadDocument(toPath("src/test/resources/example-files/simpson's_adventures.txt")); - DocumentSplitter splitter = DocumentSplitters.recursive(100, 0, new OpenAiTokenizer(GPT_3_5_TURBO)); - List segments = splitter.split(document); + public void givenDocument_whenPrompted_thenValidResponse() { EmbeddingModel embeddingModel = new AllMiniLmL6V2EmbeddingModel(); - List embeddings = embeddingModel.embedAll(segments) - .content(); + EmbeddingStore embeddingStore = new InMemoryEmbeddingStore<>(); - embeddingStore.addAll(embeddings, segments); - String question = "Who is Simpson?"; - Embedding questionEmbedding = embeddingModel.embed(question) - .content(); - int maxResults = 3; - double minScore = 0.7; - List> relevantEmbeddings = embeddingStore.findRelevant(questionEmbedding, maxResults, minScore); + EmbeddingStoreIngestor ingestor = EmbeddingStoreIngestor.builder() + .documentSplitter(DocumentSplitters.recursive(500, 0)) + .embeddingModel(embeddingModel) + .embeddingStore(embeddingStore) + .build(); - PromptTemplate promptTemplate = PromptTemplate.from("Answer the following question to the best of your ability:\n" + "\n" + "Question:\n" + "{{question}}\n" + "\n" + "Base your answer on the following information:\n" + "{{information}}"); + Document document = loadDocument(toPath("src/test/resources/example-files/simpson's_adventures.txt")); + ingestor.ingest(document); - String information = relevantEmbeddings.stream() - .map(match -> match.embedded() - .text()) - .collect(joining("\n\n")); - - Map variables = new HashMap<>(); - variables.put("question", question); - variables.put("information", information); - - Prompt prompt = promptTemplate.apply(variables); ChatLanguageModel chatModel = OpenAiChatModel.builder() - .apiKey(Constants.OPEN_API_KEY) + .apiKey(Constants.OPEN_AI_KEY) .timeout(ofSeconds(60)) .build(); - AiMessage aiMessage = chatModel.generate(prompt.toUserMessage()) - .content(); - Logger.getGlobal() - .info(aiMessage.text()); - Assert.assertNotNull(aiMessage.text()); + ConversationalRetrievalChain chain = ConversationalRetrievalChain.builder() + .chatLanguageModel(chatModel) + .retriever(EmbeddingStoreRetriever.from(embeddingStore, embeddingModel)) + .chatMemory(MessageWindowChatMemory.withMaxMessages(10)) + .promptTemplate(PromptTemplate + .from("Answer the following question to the best of your ability: {{question}}\n\nBase your answer on the following information:\n{{information}}")) + .build(); + + String answer = chain.execute("Who is Simpson?"); + + logger.info(answer); + Assert.assertNotNull(answer); } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java index 643c56520e..a7dc89afde 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java @@ -1,7 +1,9 @@ package com.baeldung.langchain; import static dev.langchain4j.data.document.FileSystemDocumentLoader.loadDocument; +import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; import static java.time.Duration.ofSeconds; +import static java.util.stream.Collectors.joining; import java.io.File; import java.net.MalformedURLException; @@ -9,59 +11,77 @@ import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.logging.Logger; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.junit.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import dev.langchain4j.chain.ConversationalRetrievalChain; import dev.langchain4j.data.document.Document; +import dev.langchain4j.data.document.DocumentSplitter; import dev.langchain4j.data.document.splitter.DocumentSplitters; +import dev.langchain4j.data.embedding.Embedding; +import dev.langchain4j.data.message.AiMessage; import dev.langchain4j.data.segment.TextSegment; import dev.langchain4j.model.chat.ChatLanguageModel; import dev.langchain4j.model.embedding.AllMiniLmL6V2EmbeddingModel; import dev.langchain4j.model.embedding.EmbeddingModel; +import dev.langchain4j.model.input.Prompt; +import dev.langchain4j.model.input.PromptTemplate; import dev.langchain4j.model.openai.OpenAiChatModel; -import dev.langchain4j.retriever.EmbeddingStoreRetriever; +import dev.langchain4j.model.openai.OpenAiTokenizer; +import dev.langchain4j.store.embedding.EmbeddingMatch; import dev.langchain4j.store.embedding.EmbeddingStore; -import dev.langchain4j.store.embedding.EmbeddingStoreIngestor; import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore; public class ChatWithDocumentLiveTest { + + Logger logger = LoggerFactory.getLogger(ChatWithDocumentLiveTest.class); @Test - public void givenDocument_whenPrompted_thenValidResponse() { - - EmbeddingModel embeddingModel = new AllMiniLmL6V2EmbeddingModel(); - - EmbeddingStore embeddingStore = new InMemoryEmbeddingStore<>(); - - EmbeddingStoreIngestor ingestor = EmbeddingStoreIngestor.builder() - .documentSplitter(DocumentSplitters.recursive(500, 0)) - .embeddingModel(embeddingModel) - .embeddingStore(embeddingStore) - .build(); + public void givenChainWithDocument_whenPrompted_thenValidResponse() { Document document = loadDocument(toPath("src/test/resources/example-files/simpson's_adventures.txt")); - ingestor.ingest(document); + DocumentSplitter splitter = DocumentSplitters.recursive(100, 0, new OpenAiTokenizer(GPT_3_5_TURBO)); + List segments = splitter.split(document); + EmbeddingModel embeddingModel = new AllMiniLmL6V2EmbeddingModel(); + List embeddings = embeddingModel.embedAll(segments) + .content(); + EmbeddingStore embeddingStore = new InMemoryEmbeddingStore<>(); + embeddingStore.addAll(embeddings, segments); + + String question = "Who is Simpson?"; + Embedding questionEmbedding = embeddingModel.embed(question) + .content(); + int maxResults = 3; + double minScore = 0.7; + List> relevantEmbeddings = embeddingStore.findRelevant(questionEmbedding, maxResults, minScore); + + PromptTemplate promptTemplate = PromptTemplate.from("Answer the following question to the best of your ability:\n" + "\n" + "Question:\n" + "{{question}}\n" + "\n" + "Base your answer on the following information:\n" + "{{information}}"); + + String information = relevantEmbeddings.stream() + .map(match -> match.embedded() + .text()) + .collect(joining("\n\n")); + + Map variables = new HashMap<>(); + variables.put("question", question); + variables.put("information", information); + + Prompt prompt = promptTemplate.apply(variables); ChatLanguageModel chatModel = OpenAiChatModel.builder() - .apiKey(Constants.OPEN_API_KEY) + .apiKey(Constants.OPEN_AI_KEY) .timeout(ofSeconds(60)) .build(); + AiMessage aiMessage = chatModel.generate(prompt.toUserMessage()) + .content(); - ConversationalRetrievalChain chain = ConversationalRetrievalChain.builder() - .chatLanguageModel(chatModel) - .retriever(EmbeddingStoreRetriever.from(embeddingStore, embeddingModel)) - // .chatMemory() // you can override default chat memory - // .promptTemplate() // you can override default prompt template - .build(); - - String answer = chain.execute("Who is Simpson?"); - - Logger.getGlobal() - .info(answer); - Assert.assertNotNull(answer); + logger.info(aiMessage.text()); + Assert.assertNotNull(aiMessage.text()); } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java index 5e0057d23c..8f7dcca1cb 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java @@ -9,35 +9,35 @@ import dev.langchain4j.model.openai.OpenAiTokenizer; import static dev.langchain4j.data.message.UserMessage.userMessage; import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; - -import java.util.logging.Logger; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class ChatWithMemoryLiveTest { + + Logger logger = LoggerFactory.getLogger(ChatWithMemoryLiveTest.class); @Test public void givenMemory_whenPrompted_thenValidResponse() { - ChatLanguageModel model = OpenAiChatModel.withApiKey(Constants.OPEN_API_KEY); + ChatLanguageModel model = OpenAiChatModel.withApiKey(Constants.OPEN_AI_KEY); ChatMemory chatMemory = TokenWindowChatMemory.withMaxTokens(300, new OpenAiTokenizer(GPT_3_5_TURBO)); chatMemory.add(userMessage("Hello, my name is Kumar")); AiMessage answer = model.generate(chatMemory.messages()) .content(); - Logger.getGlobal() - .info(answer.text()); + logger.info(answer.text()); Assert.assertNotNull(answer.text()); chatMemory.add(answer); chatMemory.add(userMessage("What is my name?")); AiMessage answerWithName = model.generate(chatMemory.messages()) .content(); - Logger.getGlobal() - .info(answerWithName.text()); - Assert.assertTrue(answerWithName.text() - .contains("Kumar")); + logger.info(answerWithName.text()); + assertThat(answerWithName.text().contains("Kumar")); chatMemory.add(answerWithName); } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java b/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java index 15645ce68e..149858f351 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java @@ -2,6 +2,11 @@ package com.baeldung.langchain; public class Constants { - public static String OPEN_API_KEY = "demo"; + /** + * A limited access key for access to OpenAI language models can be generated by first + * registering for free at (https://platform.openai.com/signup) and then by navigating + * to "Create new secret key" page at (https://platform.openai.com/account/api-keys). + */ + public static String OPEN_AI_KEY = ""; } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java index 5f155d3dba..31698ee0c7 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java @@ -4,9 +4,10 @@ import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import dev.langchain4j.model.chat.ChatLanguageModel; import dev.langchain4j.model.input.Prompt; @@ -16,6 +17,8 @@ import dev.langchain4j.model.openai.OpenAiChatModel; import org.junit.Assert; public class PromptTemplatesLiveTest { + + Logger logger = LoggerFactory.getLogger(PromptTemplatesLiveTest.class); @Test public void givenPromptTemplate_whenSuppliedInput_thenValidResponse() { @@ -27,14 +30,13 @@ public class PromptTemplatesLiveTest { Prompt prompt = promptTemplate.apply(variables); ChatLanguageModel model = OpenAiChatModel.builder() - .apiKey(Constants.OPEN_API_KEY) + .apiKey(Constants.OPEN_AI_KEY) .modelName(GPT_3_5_TURBO) .temperature(0.3) .build(); String response = model.generate(prompt.text()); - Logger.getGlobal() - .info(response); + logger.info(response); Assert.assertNotNull(response); } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java index 024c1523e8..6a6144aa21 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java @@ -1,9 +1,11 @@ package com.baeldung.langchain; -import java.util.logging.Logger; +import static org.assertj.core.api.Assertions.assertThat; import org.junit.Assert; import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import dev.langchain4j.agent.tool.Tool; import dev.langchain4j.memory.chat.MessageWindowChatMemory; @@ -11,6 +13,8 @@ import dev.langchain4j.model.openai.OpenAiChatModel; import dev.langchain4j.service.AiServices; public class ServiceWithToolsLiveTest { + + Logger logger = LoggerFactory.getLogger(ServiceWithToolsLiveTest.class); static class Calculator { @@ -35,7 +39,7 @@ public class ServiceWithToolsLiveTest { public void givenServiceWithTools_whenPrompted_thenValidResponse() { Assistant assistant = AiServices.builder(Assistant.class) - .chatLanguageModel(OpenAiChatModel.withApiKey(Constants.OPEN_API_KEY)) + .chatLanguageModel(OpenAiChatModel.withApiKey(Constants.OPEN_AI_KEY)) .tools(new Calculator()) .chatMemory(MessageWindowChatMemory.withMaxMessages(10)) .build(); @@ -43,9 +47,8 @@ public class ServiceWithToolsLiveTest { String question = "What is the sum of the numbers of letters in the words \"language\" and \"model\"?"; String answer = assistant.chat(question); - Logger.getGlobal() - .info(answer); - Assert.assertNotNull(answer); + logger.info(answer); + assertThat(answer).contains("13"); } diff --git a/pom.xml b/pom.xml index a391a1c774..cc433f0946 100644 --- a/pom.xml +++ b/pom.xml @@ -936,7 +936,7 @@ spring-di-4 spring-kafka-2 - libraries-llms + libraries-llms @@ -1224,7 +1224,7 @@ spring-di-4 spring-kafka-2 - libraries-llms + libraries-llms From ba64b644124ea0d4dca06c891589a61aebe8c743 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Wed, 25 Oct 2023 13:18:34 +0530 Subject: [PATCH 28/91] Update pom.xml fixed Formatting --- persistence-modules/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 867c12291a..7787e0bda8 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -105,7 +105,7 @@ spring-jpa spring-jpa-2 spring-jdbc - spring-jdbc-2 + spring-jdbc-2 spring-jooq spring-mybatis spring-persistence-simple From 90f25fc44970c1ce0103b1c20cb2cec1841ec8f9 Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Wed, 25 Oct 2023 13:31:26 +0530 Subject: [PATCH 29/91] BAEL-7135 renamed package --- .../JdbcClientDemoApplication.java | 4 ++-- .../{jdbcClient => jdbcclient}/dao/StudentDao.java | 8 ++++---- .../{jdbcClient => jdbcclient}/model/Student.java | 2 +- .../model/StudentResultExtractor.java | 2 +- .../model/StudentRowMapper.java | 2 +- .../application.properties | 0 .../drop_student.sql | 0 .../student.sql | 0 .../JdbcClientUnitTest.java | 12 ++++++------ 9 files changed, 15 insertions(+), 15 deletions(-) rename persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/{jdbcClient => jdbcclient}/JdbcClientDemoApplication.java (80%) rename persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/{jdbcClient => jdbcclient}/dao/StudentDao.java (95%) rename persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/{jdbcClient => jdbcclient}/model/Student.java (96%) rename persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/{jdbcClient => jdbcclient}/model/StudentResultExtractor.java (95%) rename persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/{jdbcClient => jdbcclient}/model/StudentRowMapper.java (94%) rename persistence-modules/spring-jdbc-2/src/main/resources/{com.baeldung.jdbcClient => jdbcclient}/application.properties (100%) rename persistence-modules/spring-jdbc-2/src/main/resources/{com.baeldung.jdbcClient => jdbcclient}/drop_student.sql (100%) rename persistence-modules/spring-jdbc-2/src/main/resources/{com.baeldung.jdbcClient => jdbcclient}/student.sql (100%) rename persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/{jdbcClient => jdbcclient}/JdbcClientUnitTest.java (89%) diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/JdbcClientDemoApplication.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/JdbcClientDemoApplication.java similarity index 80% rename from persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/JdbcClientDemoApplication.java rename to persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/JdbcClientDemoApplication.java index fe1a203eff..3453671cca 100644 --- a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/JdbcClientDemoApplication.java +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/JdbcClientDemoApplication.java @@ -1,11 +1,11 @@ -package com.baeldung.jdbcClient; +package com.baeldung.jdbcclient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication -@ComponentScan(basePackages = "com.baeldung.jdbcClient") +@ComponentScan(basePackages = "jdbcclient") public class JdbcClientDemoApplication { public static void main(String[] args) { diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/dao/StudentDao.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/dao/StudentDao.java similarity index 95% rename from persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/dao/StudentDao.java rename to persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/dao/StudentDao.java index 4ca2046a0e..ba5bfcee11 100644 --- a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/dao/StudentDao.java +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/dao/StudentDao.java @@ -1,8 +1,8 @@ -package com.baeldung.jdbcClient.dao; +package com.baeldung.jdbcclient.dao; -import com.baeldung.jdbcClient.model.Student; -import com.baeldung.jdbcClient.model.StudentResultExtractor; -import com.baeldung.jdbcClient.model.StudentRowMapper; +import com.baeldung.jdbcclient.model.Student; +import com.baeldung.jdbcclient.model.StudentResultExtractor; +import com.baeldung.jdbcclient.model.StudentRowMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/Student.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/Student.java similarity index 96% rename from persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/Student.java rename to persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/Student.java index 2e4ff69464..3de8a6e1f9 100644 --- a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/Student.java +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/Student.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbcClient.model; +package com.baeldung.jdbcclient.model; public class Student { private Integer studentId; diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentResultExtractor.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/StudentResultExtractor.java similarity index 95% rename from persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentResultExtractor.java rename to persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/StudentResultExtractor.java index 2bc8a249c5..29cb60cee9 100644 --- a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentResultExtractor.java +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/StudentResultExtractor.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbcClient.model; +package com.baeldung.jdbcclient.model; import org.springframework.jdbc.core.ResultSetExtractor; diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentRowMapper.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/StudentRowMapper.java similarity index 94% rename from persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentRowMapper.java rename to persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/StudentRowMapper.java index 22a98e0efa..c387a6c485 100644 --- a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcClient/model/StudentRowMapper.java +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/model/StudentRowMapper.java @@ -1,4 +1,4 @@ -package com.baeldung.jdbcClient.model; +package com.baeldung.jdbcclient.model; import org.springframework.jdbc.core.RowMapper; diff --git a/persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/application.properties b/persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/application.properties similarity index 100% rename from persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/application.properties rename to persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/application.properties diff --git a/persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/drop_student.sql b/persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/drop_student.sql similarity index 100% rename from persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/drop_student.sql rename to persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/drop_student.sql diff --git a/persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/student.sql b/persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/student.sql similarity index 100% rename from persistence-modules/spring-jdbc-2/src/main/resources/com.baeldung.jdbcClient/student.sql rename to persistence-modules/spring-jdbc-2/src/main/resources/jdbcclient/student.sql diff --git a/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcClient/JdbcClientUnitTest.java b/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcclient/JdbcClientUnitTest.java similarity index 89% rename from persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcClient/JdbcClientUnitTest.java rename to persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcclient/JdbcClientUnitTest.java index b07a3c16f0..42ac1eb4d0 100644 --- a/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcClient/JdbcClientUnitTest.java +++ b/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcclient/JdbcClientUnitTest.java @@ -1,7 +1,7 @@ -package com.baeldung.jdbcClient; +package com.baeldung.jdbcclient; -import com.baeldung.jdbcClient.dao.StudentDao; -import com.baeldung.jdbcClient.model.Student; +import com.baeldung.jdbcclient.dao.StudentDao; +import com.baeldung.jdbcclient.model.Student; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; @@ -20,10 +20,10 @@ import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; @RunWith(SpringRunner.class) -@Sql(value = "/com.baeldung.jdbcClient/student.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) -@Sql(value = "/com.baeldung.jdbcClient/drop_student.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) +@Sql(value = "/jdbcclient/student.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) +@Sql(value = "/jdbcclient/drop_student.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) @SpringBootTest(classes = JdbcClientDemoApplication.class) -@TestPropertySource(locations = {"classpath:com.baeldung.jdbcClient/application.properties"}) +@TestPropertySource(locations = {"classpath:jdbcclient/application.properties"}) public class JdbcClientUnitTest { private static final Logger logger = LoggerFactory.getLogger(JdbcClientUnitTest.class); From 78f5072f7c93b46ccb6acc62fa0210be2e8d7ccd Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Wed, 25 Oct 2023 15:10:31 +0530 Subject: [PATCH 30/91] BAEL-7135 updated component scan --- .../java/com/baeldung/jdbcclient/JdbcClientDemoApplication.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/JdbcClientDemoApplication.java b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/JdbcClientDemoApplication.java index 3453671cca..d10124fdef 100644 --- a/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/JdbcClientDemoApplication.java +++ b/persistence-modules/spring-jdbc-2/src/main/java/com/baeldung/jdbcclient/JdbcClientDemoApplication.java @@ -5,7 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication -@ComponentScan(basePackages = "jdbcclient") +@ComponentScan(basePackages = "com.baledung.jdbcclient") public class JdbcClientDemoApplication { public static void main(String[] args) { From 3c8e7eb634053b7031d277ab7789b7ccbfd2b75a Mon Sep 17 00:00:00 2001 From: parthiv39731 <70740707+parthiv39731@users.noreply.github.com> Date: Wed, 25 Oct 2023 15:48:55 +0530 Subject: [PATCH 31/91] BAEL-7135 migrated to junit 5 --- persistence-modules/spring-jdbc-2/pom.xml | 1 + .../jdbcclient/JdbcClientUnitTest.java | 20 +++++++++---------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/persistence-modules/spring-jdbc-2/pom.xml b/persistence-modules/spring-jdbc-2/pom.xml index 24744b28dc..ce79c1c615 100644 --- a/persistence-modules/spring-jdbc-2/pom.xml +++ b/persistence-modules/spring-jdbc-2/pom.xml @@ -86,6 +86,7 @@ 3.2.0-SNAPSHOT + 5.10.0 UTF-8 diff --git a/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcclient/JdbcClientUnitTest.java b/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcclient/JdbcClientUnitTest.java index 42ac1eb4d0..be30efcb9c 100644 --- a/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcclient/JdbcClientUnitTest.java +++ b/persistence-modules/spring-jdbc-2/src/test/java/com/baeldung/jdbcclient/JdbcClientUnitTest.java @@ -2,15 +2,13 @@ package com.baeldung.jdbcclient; import com.baeldung.jdbcclient.dao.StudentDao; import com.baeldung.jdbcclient.model.Student; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import java.util.Map; @@ -19,11 +17,11 @@ import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; -@RunWith(SpringRunner.class) @Sql(value = "/jdbcclient/student.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) @Sql(value = "/jdbcclient/drop_student.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD) @SpringBootTest(classes = JdbcClientDemoApplication.class) @TestPropertySource(locations = {"classpath:jdbcclient/application.properties"}) + public class JdbcClientUnitTest { private static final Logger logger = LoggerFactory.getLogger(JdbcClientUnitTest.class); @@ -31,14 +29,14 @@ public class JdbcClientUnitTest { private StudentDao studentDao; @Test - public void givenJdbcClient_whenInsertWithNamedParamAndSqlType_thenSuccess() { + void givenJdbcClient_whenInsertWithNamedParamAndSqlType_thenSuccess() { logger.info("testing invoked successfully"); Student student = getSampleStudent("Johny Dep", 8, 4, "Male", "New York"); assertEquals(1, studentDao.insertWithSetParamWithNamedParamAndSqlType(student)); } @Test - public void givenJdbcClient_whenQueryWithPositionalParams_thenSuccess() { + void givenJdbcClient_whenQueryWithPositionalParams_thenSuccess() { logger.info("testing invoked successfully"); List students = studentDao.getStudentsOfGradeStateAndGenderWithPositionalParams( 1, "New York", "Male"); @@ -47,7 +45,7 @@ public class JdbcClientUnitTest { } @Test - public void givenJdbcClient_whenQueryWithParamsInVarargs_thenSuccess() { + void givenJdbcClient_whenQueryWithParamsInVarargs_thenSuccess() { logger.info("testing invoked successfully"); Student student = studentDao.getStudentsOfGradeStateAndGenderWithParamsInVarargs( 1, "New York", "Male"); @@ -55,7 +53,7 @@ public class JdbcClientUnitTest { } @Test - public void givenJdbcClient_whenQueryWithParamsInList_thenSuccess() { + void givenJdbcClient_whenQueryWithParamsInList_thenSuccess() { logger.info("testing invoked successfully"); List params = List.of(1, "New York", "Male"); Optional optional = studentDao.getStudentsOfGradeStateAndGenderWithParamsInList(params); @@ -67,14 +65,14 @@ public class JdbcClientUnitTest { } @Test - public void givenJdbcClient_whenQueryWithParamsIndex_thenSuccess() { + void givenJdbcClient_whenQueryWithParamsIndex_thenSuccess() { logger.info("testing invoked successfully"); List students = studentDao.getStudentsOfGradeStateAndGenderWithParamIndex( 1, "New York", "Male"); assertEquals(6, students.size()); } @Test - public void givenJdbcClient_whenQueryWithNamedParam_thenSuccess() { + void givenJdbcClient_whenQueryWithNamedParam_thenSuccess() { logger.info("testing invoked successfully"); Integer count = studentDao.getCountOfStudentsOfGradeStateAndGenderWithNamedParam( 1, "New York", "Male"); @@ -82,7 +80,7 @@ public class JdbcClientUnitTest { assertEquals(6, count); } @Test - public void givenJdbcClient_whenQueryWithParamMap_thenSuccess() { + void givenJdbcClient_whenQueryWithParamMap_thenSuccess() { logger.info("testing invoked successfully"); Map paramMap = Map.of( "grade", 1, From ed75b80958f0ce23157017a2dde51baa2d7471f9 Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Thu, 26 Oct 2023 23:15:14 +0530 Subject: [PATCH 32/91] Added few more changes to accommodate review comments. --- .../langchain/ChainWithDocumentLiveTest.java | 32 ++++--------------- .../langchain/ChatWithDocumentLiveTest.java | 29 ++++------------- .../langchain/ChatWithMemoryLiveTest.java | 27 ++++++++-------- .../com/baeldung/langchain/Constants.java | 2 +- .../langchain/PromptTemplatesLiveTest.java | 7 ++-- .../langchain/ServiceWithToolsLiveTest.java | 3 +- 6 files changed, 32 insertions(+), 68 deletions(-) diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java index 556f394866..804a052990 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java @@ -2,15 +2,10 @@ package com.baeldung.langchain; import static dev.langchain4j.data.document.FileSystemDocumentLoader.loadDocument; import static java.time.Duration.ofSeconds; +import static org.junit.Assert.assertNotNull; -import java.io.File; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.file.Path; import java.nio.file.Paths; -import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,11 +26,11 @@ import dev.langchain4j.store.embedding.EmbeddingStoreIngestor; import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore; public class ChainWithDocumentLiveTest { - - Logger logger = LoggerFactory.getLogger(ChainWithDocumentLiveTest.class); + + private static final Logger logger = LoggerFactory.getLogger(ChainWithDocumentLiveTest.class); @Test - public void givenDocument_whenPrompted_thenValidResponse() { + public void givenChainWithDocument_whenPrompted_thenValidResponse() { EmbeddingModel embeddingModel = new AllMiniLmL6V2EmbeddingModel(); @@ -47,7 +42,7 @@ public class ChainWithDocumentLiveTest { .embeddingStore(embeddingStore) .build(); - Document document = loadDocument(toPath("src/test/resources/example-files/simpson's_adventures.txt")); + Document document = loadDocument(Paths.get("src/test/resources/example-files/simpson's_adventures.txt")); ingestor.ingest(document); ChatLanguageModel chatModel = OpenAiChatModel.builder() @@ -59,27 +54,14 @@ public class ChainWithDocumentLiveTest { .chatLanguageModel(chatModel) .retriever(EmbeddingStoreRetriever.from(embeddingStore, embeddingModel)) .chatMemory(MessageWindowChatMemory.withMaxMessages(10)) - .promptTemplate(PromptTemplate - .from("Answer the following question to the best of your ability: {{question}}\n\nBase your answer on the following information:\n{{information}}")) + .promptTemplate(PromptTemplate.from("Answer the following question to the best of your ability: {{question}}\n\nBase your answer on the following information:\n{{information}}")) .build(); String answer = chain.execute("Who is Simpson?"); logger.info(answer); - Assert.assertNotNull(answer); + assertNotNull(answer); } - private static Path toPath(String fileName) { - try { - URL fileUrl = new File(fileName).toURI() - .toURL(); - System.out.println(new File(fileName).toURI() - .toURL()); - return Paths.get(fileUrl.toURI()); - } catch (URISyntaxException | MalformedURLException e) { - throw new RuntimeException(e); - } - } - } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java index a7dc89afde..7ae50c6bc4 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java @@ -4,18 +4,13 @@ import static dev.langchain4j.data.document.FileSystemDocumentLoader.loadDocumen import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; import static java.time.Duration.ofSeconds; import static java.util.stream.Collectors.joining; +import static org.junit.Assert.assertNotNull; -import java.io.File; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,13 +33,13 @@ import dev.langchain4j.store.embedding.EmbeddingStore; import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore; public class ChatWithDocumentLiveTest { - - Logger logger = LoggerFactory.getLogger(ChatWithDocumentLiveTest.class); + + private static final Logger logger = LoggerFactory.getLogger(ChatWithDocumentLiveTest.class); @Test - public void givenChainWithDocument_whenPrompted_thenValidResponse() { + public void givenDocument_whenPrompted_thenValidResponse() { - Document document = loadDocument(toPath("src/test/resources/example-files/simpson's_adventures.txt")); + Document document = loadDocument(Paths.get("src/test/resources/example-files/simpson's_adventures.txt")); DocumentSplitter splitter = DocumentSplitters.recursive(100, 0, new OpenAiTokenizer(GPT_3_5_TURBO)); List segments = splitter.split(document); @@ -81,20 +76,8 @@ public class ChatWithDocumentLiveTest { .content(); logger.info(aiMessage.text()); - Assert.assertNotNull(aiMessage.text()); + assertNotNull(aiMessage.text()); } - private static Path toPath(String fileName) { - try { - URL fileUrl = new File(fileName).toURI() - .toURL(); - System.out.println(new File(fileName).toURI() - .toURL()); - return Paths.get(fileUrl.toURI()); - } catch (URISyntaxException | MalformedURLException e) { - throw new RuntimeException(e); - } - } - } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java index 8f7dcca1cb..cae6a7930a 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java @@ -1,5 +1,14 @@ package com.baeldung.langchain; +import static dev.langchain4j.data.message.UserMessage.userMessage; +import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import dev.langchain4j.data.message.AiMessage; import dev.langchain4j.memory.ChatMemory; import dev.langchain4j.memory.chat.TokenWindowChatMemory; @@ -7,18 +16,9 @@ import dev.langchain4j.model.chat.ChatLanguageModel; import dev.langchain4j.model.openai.OpenAiChatModel; import dev.langchain4j.model.openai.OpenAiTokenizer; -import static dev.langchain4j.data.message.UserMessage.userMessage; -import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Assert; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class ChatWithMemoryLiveTest { - - Logger logger = LoggerFactory.getLogger(ChatWithMemoryLiveTest.class); + + private static final Logger logger = LoggerFactory.getLogger(ChatWithMemoryLiveTest.class); @Test public void givenMemory_whenPrompted_thenValidResponse() { @@ -30,15 +30,16 @@ public class ChatWithMemoryLiveTest { AiMessage answer = model.generate(chatMemory.messages()) .content(); logger.info(answer.text()); - Assert.assertNotNull(answer.text()); chatMemory.add(answer); + assertNotNull(answer.text()); chatMemory.add(userMessage("What is my name?")); AiMessage answerWithName = model.generate(chatMemory.messages()) .content(); logger.info(answerWithName.text()); - assertThat(answerWithName.text().contains("Kumar")); chatMemory.add(answerWithName); + assertThat(answerWithName.text() + .contains("Kumar")); } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java b/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java index 149858f351..b468b3a065 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java @@ -7,6 +7,6 @@ public class Constants { * registering for free at (https://platform.openai.com/signup) and then by navigating * to "Create new secret key" page at (https://platform.openai.com/account/api-keys). */ - public static String OPEN_AI_KEY = ""; + public static String OPEN_AI_KEY = "demo"; //""; } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java index 31698ee0c7..1350872eb1 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java @@ -1,6 +1,7 @@ package com.baeldung.langchain; import static dev.langchain4j.model.openai.OpenAiModelName.GPT_3_5_TURBO; +import static org.junit.Assert.assertNotNull; import java.util.HashMap; import java.util.Map; @@ -14,11 +15,9 @@ import dev.langchain4j.model.input.Prompt; import dev.langchain4j.model.input.PromptTemplate; import dev.langchain4j.model.openai.OpenAiChatModel; -import org.junit.Assert; - public class PromptTemplatesLiveTest { - Logger logger = LoggerFactory.getLogger(PromptTemplatesLiveTest.class); + private static final Logger logger = LoggerFactory.getLogger(PromptTemplatesLiveTest.class); @Test public void givenPromptTemplate_whenSuppliedInput_thenValidResponse() { @@ -37,7 +36,7 @@ public class PromptTemplatesLiveTest { String response = model.generate(prompt.text()); logger.info(response); - Assert.assertNotNull(response); + assertNotNull(response); } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java index 6a6144aa21..9d64d1fc97 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java @@ -2,7 +2,6 @@ package com.baeldung.langchain; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,7 +13,7 @@ import dev.langchain4j.service.AiServices; public class ServiceWithToolsLiveTest { - Logger logger = LoggerFactory.getLogger(ServiceWithToolsLiveTest.class); + private static final Logger logger = LoggerFactory.getLogger(ServiceWithToolsLiveTest.class); static class Calculator { From 450b6d8025dd076cfb069e60969fe84f646a8cc9 Mon Sep 17 00:00:00 2001 From: Neetika23 <42495275+Neetika23@users.noreply.github.com> Date: Thu, 26 Oct 2023 23:25:17 +0530 Subject: [PATCH 33/91] Create StringIterator.java --- .../baeldung/stringIterator/StringIterator.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java diff --git a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java new file mode 100644 index 0000000000..2ffabc48d4 --- /dev/null +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java @@ -0,0 +1,14 @@ +package com.baeldung.stringIterator; + +public class StringIterator { + public static void main(String[] args) { + String str = "Hello, Baeldung!"; + java8forEach(str); + } + + public static void java8forEach(String str){ + str.chars().forEach(name -> { + System.out.print((char) name); + }); + } +} From d3d60f392b77c69677e02dfc8407df7e5b1aea72 Mon Sep 17 00:00:00 2001 From: Neetika23 <42495275+Neetika23@users.noreply.github.com> Date: Thu, 26 Oct 2023 23:41:32 +0530 Subject: [PATCH 34/91] Update StringIterator.java --- .../stringIterator/StringIterator.java | 41 ++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java index 2ffabc48d4..cbd69a151a 100644 --- a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java @@ -1,14 +1,53 @@ package com.baeldung.stringIterator; +import java.text.*; +import java.util.*; + public class StringIterator { public static void main(String[] args) { String str = "Hello, Baeldung!"; + javaforLoop(str); + System.out.println(); java8forEach(str); + System.out.println(); + javaCharArray(str); + System.out.println(); + javaRegexExp(str); + System.out.println(); + javaCharacterIterator(str); } - + + public static void javaCharArray(String str){ + for (char c : str.toCharArray()) { + System.out.print(c); + } + } + + public static void javaforLoop(String str) { + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + System.out.print(c); + } + } + public static void java8forEach(String str){ str.chars().forEach(name -> { System.out.print((char) name); }); } + + public static void javaRegexExp(String str){ + String[] characters = str.split(""); + for (String c : characters) { + System.out.print(c); + } + } + + public static void javaCharacterIterator(String str){ + CharacterIterator it = new StringCharacterIterator(str); + while (it.current() != CharacterIterator.DONE) { + System.out.print(it.current()); + it.next(); + } + } } From 0fa77ed809e43b24e7dc474308eb461e5a7c708e Mon Sep 17 00:00:00 2001 From: Neetika23 <42495275+Neetika23@users.noreply.github.com> Date: Thu, 26 Oct 2023 23:45:34 +0530 Subject: [PATCH 35/91] Create StringIteratorTest.java --- .../java/com/baeldung/stringIterator/StringIteratorTest.java | 1 + 1 file changed, 1 insertion(+) create mode 100644 core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java new file mode 100644 index 0000000000..9daeafb986 --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java @@ -0,0 +1 @@ +test From 7aeb97fcdfe49b2518512339356462ced27a5966 Mon Sep 17 00:00:00 2001 From: Neetika23 <42495275+Neetika23@users.noreply.github.com> Date: Thu, 26 Oct 2023 23:57:27 +0530 Subject: [PATCH 36/91] Update StringIterator.java --- .../stringIterator/StringIterator.java | 44 +++++++++++-------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java index cbd69a151a..0f7cd2a7f7 100644 --- a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java @@ -6,48 +6,54 @@ import java.util.*; public class StringIterator { public static void main(String[] args) { String str = "Hello, Baeldung!"; - javaforLoop(str); - System.out.println(); - java8forEach(str); - System.out.println(); - javaCharArray(str); - System.out.println(); - javaRegexExp(str); - System.out.println(); - javaCharacterIterator(str); + System.out.println(javaforLoop(str)); + System.out.println(java8forEach(str)); + System.out.println(javaCharArray(str)); + System.out.println(javaRegexExp(str)); + System.out.println(javaCharacterIterator(str)); } - public static void javaCharArray(String str){ + public static String javaCharArray(String str){ + StringBuilder result = new StringBuilder(); for (char c : str.toCharArray()) { - System.out.print(c); + result.append(c); } + return result.toString(); } - public static void javaforLoop(String str) { + public static String javaforLoop(String str) { + StringBuilder result = new StringBuilder(); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); - System.out.print(c); + result.append(c); } + return result.toString(); } - public static void java8forEach(String str){ + public static String java8forEach(String str){ + StringBuilder result = new StringBuilder(); str.chars().forEach(name -> { - System.out.print((char) name); + result.append((char) name); }); + return result.toString(); } - public static void javaRegexExp(String str){ + public static String javaRegexExp(String str){ + StringBuilder result = new StringBuilder(); String[] characters = str.split(""); for (String c : characters) { - System.out.print(c); + result.append(c); } + return result.toString(); } - public static void javaCharacterIterator(String str){ + public static String javaCharacterIterator(String str){ + StringBuilder result = new StringBuilder(); CharacterIterator it = new StringCharacterIterator(str); while (it.current() != CharacterIterator.DONE) { - System.out.print(it.current()); + result.append(it.current()); it.next(); } + return result.toString(); } } From aa7ad247e1c7d8e53c0fcb3554d60ff8807fa82b Mon Sep 17 00:00:00 2001 From: Neetika23 <42495275+Neetika23@users.noreply.github.com> Date: Fri, 27 Oct 2023 00:02:38 +0530 Subject: [PATCH 37/91] Update StringIteratorTest.java --- .../stringIterator/StringIteratorTest.java | 48 ++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java index 9daeafb986..8f7b853bc2 100644 --- a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java @@ -1 +1,47 @@ -test +package com.baeldung.stringIterator; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +public class StringIteratorTest { + + @Test + public void testJavaCharArray() { + String input = "Hello, Baeldung!"; + String expectedOutput = "Hello, Baeldung!"; + String result = StringIterator.javaCharArray(input); + assertEquals(expectedOutput, result); + } + + @Test + public void testJavaForLoop() { + String input = "Hello, Baeldung!"; + String expectedOutput = "Hello, Baeldung!"; + String result = StringIterator.javaForLoop(input); + assertEquals(expectedOutput, result); + } + + @Test + public void testJava8ForEach() { + String input = "Hello, Baeldung!"; + String expectedOutput = "Hello, Baeldung!"; + String result = StringIterator.java8ForEach(input); + assertEquals(expectedOutput, result); + } + + @Test + public void testJavaRegExp() { + String input = "Hello, Baeldung!"; + String expectedOutput = "Hello, Baeldung!"; + String result = StringIterator.javaRegExp(input); + assertEquals(expectedOutput, result); + } + + @Test + public void testJavaCharacterIterator() { + String input = "Hello, Baeldung!"; + String expectedOutput = "Hello, Baeldung!"; + String result = StringIterator.javaCharacterIterator(input); + assertEquals(expectedOutput, result); + } +} From 9f1ce56f8260557130b8695d4785fe7077ac32a7 Mon Sep 17 00:00:00 2001 From: Neetika23 <42495275+Neetika23@users.noreply.github.com> Date: Fri, 27 Oct 2023 00:09:53 +0530 Subject: [PATCH 38/91] Update StringIteratorTest.java --- .../baeldung/stringIterator/StringIteratorTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java index 8f7b853bc2..2caec944f5 100644 --- a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java @@ -6,7 +6,7 @@ import static org.junit.jupiter.api.Assertions.*; public class StringIteratorTest { @Test - public void testJavaCharArray() { + public void whenUseCharArrayMethod_thenIterate() { String input = "Hello, Baeldung!"; String expectedOutput = "Hello, Baeldung!"; String result = StringIterator.javaCharArray(input); @@ -14,7 +14,7 @@ public class StringIteratorTest { } @Test - public void testJavaForLoop() { + public void whenUseJavaForLoop_thenIterate() { String input = "Hello, Baeldung!"; String expectedOutput = "Hello, Baeldung!"; String result = StringIterator.javaForLoop(input); @@ -22,7 +22,7 @@ public class StringIteratorTest { } @Test - public void testJava8ForEach() { + public void whenUseForEachMethod_thenIterate() { String input = "Hello, Baeldung!"; String expectedOutput = "Hello, Baeldung!"; String result = StringIterator.java8ForEach(input); @@ -30,7 +30,7 @@ public class StringIteratorTest { } @Test - public void testJavaRegExp() { + public void whenUseRegexSplit_thenIterate() { String input = "Hello, Baeldung!"; String expectedOutput = "Hello, Baeldung!"; String result = StringIterator.javaRegExp(input); @@ -38,7 +38,7 @@ public class StringIteratorTest { } @Test - public void testJavaCharacterIterator() { + public void whenUseCharacterIterator_thenIterate() { String input = "Hello, Baeldung!"; String expectedOutput = "Hello, Baeldung!"; String result = StringIterator.javaCharacterIterator(input); From 002def2d241829c9ed3d6e31eb7174cc7e0f767b Mon Sep 17 00:00:00 2001 From: Neetika23 <42495275+Neetika23@users.noreply.github.com> Date: Fri, 27 Oct 2023 14:49:09 +0530 Subject: [PATCH 39/91] Delete core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/School.java --- .../com/baeldung/shallowdeepcopy/School.java | 22 ------------------- 1 file changed, 22 deletions(-) delete mode 100644 core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/School.java diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/School.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/School.java deleted file mode 100644 index 28a751741e..0000000000 --- a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/School.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.shallowdeepcopy; - -class School { - private String schoolName; - public School(School sc) { - this(sc.getSchoolName()); - } - public School(String schoolName) { - this.schoolName = schoolName; - } - // standard getters and setters -} - -@Override -public Object clone() { - try { - return (School) super.clone(); - } catch (CloneNotSupportedException e) { - return new School(this.getSchoolName()); - } -} - From f20dbd4ed9d5ed917b1436fd1c2e600e5ddfe66c Mon Sep 17 00:00:00 2001 From: Neetika23 <42495275+Neetika23@users.noreply.github.com> Date: Fri, 27 Oct 2023 14:49:29 +0530 Subject: [PATCH 40/91] Delete core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java --- .../com/baeldung/shallowdeepcopy/Student.java | 27 ------------------- 1 file changed, 27 deletions(-) delete mode 100644 core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java diff --git a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java b/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java deleted file mode 100644 index 2fc34ba709..0000000000 --- a/core-java-modules/core-java-lang-oop-patterns/src/main/java/com/baeldung/shallowdeepcopy/Student.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.shallowdeepcopy; - -class Student { - private String name; - private int age; - private School school; - public Student(String name, int age, School school) { - this.name = name; - this.rollno = rollno; - this.school = school; - } - public Student(Student st) { - this(st.getName(), st.getAge(), st.getSchool()); - } // standard getters and setters -} - -@Override -public Object clone() { - Student student = null; - try { - student = (Student) super.clone(); - } catch (CloneNotSupportedException e) { - student = new Student(this.getName(), this.getAge(), this.getSchool()); - } - student.school= (School) this.school.clone(); - return student; -} \ No newline at end of file From 98c8e96fcae4562c2ce85fd4869fa172a65d97e3 Mon Sep 17 00:00:00 2001 From: Neetika23 <42495275+Neetika23@users.noreply.github.com> Date: Fri, 27 Oct 2023 14:49:52 +0530 Subject: [PATCH 41/91] Delete core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java --- .../ShallowDeepCopyExampleTest.java | 41 ------------------- 1 file changed, 41 deletions(-) delete mode 100644 core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java diff --git a/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java b/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java deleted file mode 100644 index a14a621dcc..0000000000 --- a/core-java-modules/core-java-lang-oop-patterns/src/test/java/com/baeldung/shallowdeepcopy/ShallowDeepCopyExampleTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.baeldung.shallowdeepcopy; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.jupiter.api.Test; - -public class ShallowDeepCopyExampleTest { - - @Test - public void whenPerformShallowCopy_thenObjectsNotSame() { - School school = new School("Baeldung School"); - Student originalStudent = new Student("John", 20, school); - Student shallowCopy = new Student(originalStudent.getName(), originalStudent.getAge(), originalStudent.getSchool()); - assertNotSame(shallowCopy, originalStudent); - } - - @Test public void whenModifyingActualObject_thenCopyAlsoChange() { - School school = new School("Baeldung School"); - Student originalStudent = new Student("John", 20, school); - Student shallowCopy = new Student(originalStudent.getName(), originalStudent.getAge(), originalStudent.getSchool()); - school.setSchoolName("New Baeldung School"); - assertEquals(shallowCopy.getSchool().getSchoolName(), originalStudent.getSchool().getSchoolName()); - } - - @Test - public void whenModifyingActualObject_thenCloneCopyNotChange() { - School school = new School("New School"); - Student originalStudent = new Student("Alice", 10, school); - Student deepCopy = (Student) originalStudent.clone(); - school.setSchoolName("New Baeldung School"); - assertNotEquals(deepCopy.getSchool().getSchoolName(), originalStudent.getSchool().getSchoolName()); - } - - @Test - public void whenModifyingActualObject_thenCopyNotChange() { - School school = new School("Baeldung School"); - Student originalStudent = new Student("Alice", 30, school); - Student deepCopy = new Student(originalStudent); - school.setSchoolName("New Baeldung School"); - assertNotEquals( originalStudent.getSchool().getSchoolName(), deepCopy.getSchool().getSchoolName()); - } -} From 66604b8e2750cd260a3839a614237f316b0a7727 Mon Sep 17 00:00:00 2001 From: Neetika23 <42495275+Neetika23@users.noreply.github.com> Date: Fri, 27 Oct 2023 14:51:01 +0530 Subject: [PATCH 42/91] Update StringIterator.java --- .../baeldung/stringIterator/StringIterator.java | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java index 0f7cd2a7f7..0e46c7eedd 100644 --- a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java +++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringIterator/StringIterator.java @@ -4,14 +4,6 @@ import java.text.*; import java.util.*; public class StringIterator { - public static void main(String[] args) { - String str = "Hello, Baeldung!"; - System.out.println(javaforLoop(str)); - System.out.println(java8forEach(str)); - System.out.println(javaCharArray(str)); - System.out.println(javaRegexExp(str)); - System.out.println(javaCharacterIterator(str)); - } public static String javaCharArray(String str){ StringBuilder result = new StringBuilder(); @@ -38,15 +30,6 @@ public class StringIterator { return result.toString(); } - public static String javaRegexExp(String str){ - StringBuilder result = new StringBuilder(); - String[] characters = str.split(""); - for (String c : characters) { - result.append(c); - } - return result.toString(); - } - public static String javaCharacterIterator(String str){ StringBuilder result = new StringBuilder(); CharacterIterator it = new StringCharacterIterator(str); From befba49dece94e215f4aab950d0be591305a9d98 Mon Sep 17 00:00:00 2001 From: Neetika23 <42495275+Neetika23@users.noreply.github.com> Date: Fri, 27 Oct 2023 14:52:14 +0530 Subject: [PATCH 43/91] Update StringIteratorTest.java --- .../com/baeldung/stringIterator/StringIteratorTest.java | 8 -------- 1 file changed, 8 deletions(-) diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java index 2caec944f5..585d65d4be 100644 --- a/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/stringIterator/StringIteratorTest.java @@ -29,14 +29,6 @@ public class StringIteratorTest { assertEquals(expectedOutput, result); } - @Test - public void whenUseRegexSplit_thenIterate() { - String input = "Hello, Baeldung!"; - String expectedOutput = "Hello, Baeldung!"; - String result = StringIterator.javaRegExp(input); - assertEquals(expectedOutput, result); - } - @Test public void whenUseCharacterIterator_thenIterate() { String input = "Hello, Baeldung!"; From ce6640a476d145fe54b2ebb39c01e184e8544e8e Mon Sep 17 00:00:00 2001 From: Ehsan Sasanianno Date: Fri, 27 Oct 2023 18:42:59 +0200 Subject: [PATCH 44/91] Java-24346: Fix integration test for spring-cloud-contract-consumer module --- .../BasicMathControllerIntegrationTest.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathControllerIntegrationTest.java b/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathControllerIntegrationTest.java index e21223e6ea..c19b3f3694 100644 --- a/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathControllerIntegrationTest.java +++ b/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathControllerIntegrationTest.java @@ -1,5 +1,10 @@ package com.baeldung.spring.cloud.springcloudcontractconsumer.controller; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -13,6 +18,7 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -26,6 +32,36 @@ public class BasicMathControllerIntegrationTest { @Autowired private MockMvc mockMvc; + private static WireMockServer wireMockServer; + + + @BeforeClass + public static void setupClass() { + WireMockConfiguration wireMockConfiguration = WireMockConfiguration.options().port(8090); // Use the same port as in your code + + wireMockServer = new WireMockServer(wireMockConfiguration); + wireMockServer.start(); + } + + @AfterClass + public static void teardownClass() { + wireMockServer.stop(); + } + + @Before + public void setup() { + wireMockServer.stubFor(get(urlEqualTo("/validate/prime-number?number=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("Odd"))); + + wireMockServer.stubFor(get(urlEqualTo("/validate/prime-number?number=2")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "application/json") + .withBody("Even"))); + } @Test public void given_WhenPassEvenNumberInQueryParam_ThenReturnEven() throws Exception { From 0abadb03a59827d3382e521832e75ab3a0f8d8a3 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Fri, 27 Oct 2023 22:42:27 +0530 Subject: [PATCH 45/91] JAVA-26281 Improve spring-activi module build time --- ...tiWithSpringApplicationIntegrationTest.java | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java diff --git a/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java b/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java deleted file mode 100644 index d289693a73..0000000000 --- a/spring-activiti/src/test/java/com/baeldung/activitiwithspring/ActivitiWithSpringApplicationIntegrationTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.activitiwithspring; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ActivitiWithSpringApplication.class) -@AutoConfigureTestDatabase -public class ActivitiWithSpringApplicationIntegrationTest { - - @Test - public void contextLoads() { - } - -} From 080dded9a425f505119d9b711af4f9b2e92bf7c0 Mon Sep 17 00:00:00 2001 From: timis1 Date: Sat, 28 Oct 2023 23:45:22 +0300 Subject: [PATCH 46/91] JAVA-25525 Adding other service dependencies to run the project --- reactive-systems/docker-compose.yml | 41 ++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/reactive-systems/docker-compose.yml b/reactive-systems/docker-compose.yml index 2e40d1999a..51e15f6a19 100644 --- a/reactive-systems/docker-compose.yml +++ b/reactive-systems/docker-compose.yml @@ -4,15 +4,54 @@ services: build: ./frontend ports: - "80:80" + zookeeper: + image: confluentinc/cp-zookeeper:latest + environment: + ZOOKEEPER_CLIENT_PORT: 2181 + ZOOKEEPER_TICK_TIME: 2000 + ports: + - 22181:2181 + kafka: + image: confluentinc/cp-kafka:latest + container_name: kafka-broker + depends_on: + - zookeeper + ports: + - 29092:29092 + environment: + KAFKA_BROKER_ID: 1 + KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181 + KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka-broker:9092,PLAINTEXT_HOST://localhost:29092 + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT + KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 + mongodb: + container_name: mongo-db + image: mongo:6.0 + volumes: + - ~/mongo:/data/db + ports: + - "27017:27017" + healthcheck: + test: exit 0 order-service: build: ./order-service ports: - "8080:8080" + depends_on: + mongodb: + condition: service_healthy inventory-service: build: ./inventory-service ports: - "8081:8081" + depends_on: + mongodb: + condition: service_healthy shipping-service: build: ./shipping-service ports: - - "8082:8082" \ No newline at end of file + - "8082:8082" + depends_on: + mongodb: + condition: service_healthy \ No newline at end of file From c65981938f9be61a5182259c911462a21671a940 Mon Sep 17 00:00:00 2001 From: lucaCambi77 Date: Sat, 28 Oct 2023 23:56:11 +0200 Subject: [PATCH 47/91] [BAEL-7048] - Passing Strings By Reference in Java (#15047) * feat: pass by reference java string * fix: review --- .../baeldung/passstringbyreference/Dummy.java | 14 +++ .../PassStringUnitTest.java | 85 +++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/Dummy.java create mode 100644 core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/PassStringUnitTest.java diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/Dummy.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/Dummy.java new file mode 100644 index 0000000000..27ebf8331f --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/Dummy.java @@ -0,0 +1,14 @@ +package com.baeldung.passstringbyreference; + +public class Dummy { + + String dummyString; + + public String getDummyString() { + return dummyString; + } + + public void setDummyString(String dummyString) { + this.dummyString = dummyString; + } +} diff --git a/core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/PassStringUnitTest.java b/core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/PassStringUnitTest.java new file mode 100644 index 0000000000..e1b284a94e --- /dev/null +++ b/core-java-modules/core-java-strings/src/test/java/com/baeldung/passstringbyreference/PassStringUnitTest.java @@ -0,0 +1,85 @@ +package com.baeldung.passstringbyreference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.junit.jupiter.api.Test; + +class PassStringUnitTest { + + @Test + void givenAString_whenPassedToVoidMethod_thenStringIsNotModified() { + String s = "hello"; + concatStringWithNoReturn(s); + assertEquals("hello", s); + } + + void concatStringWithNoReturn(String input) { + input += " world"; + assertEquals("hello world", input); + } + + @Test + void givenAString_whenPassedToMethodAndReturnNewString_thenStringIsModified() { + String s = "hello"; + assertEquals("hello world", concatStringWithReturn(s)); + } + + String concatStringWithReturn(String input) { + return input + " world"; + } + + @Test + void givenAString_whenPassStringBuilderToVoidMethod_thenConcatNewStringOk() { + StringBuilder builder = new StringBuilder("hello"); + concatWithStringBuilder(builder); + + assertEquals("hello world", builder.toString()); + } + + void concatWithStringBuilder(StringBuilder input) { + input.append(" world"); + } + + @Test + void givenAString_whenPassStringBufferToVoidMethod_thenConcatNewStringOk() { + StringBuffer builder = new StringBuffer("hello"); + concatWithStringBuffer(builder); + + assertEquals("hello world", builder.toString()); + } + + void concatWithStringBuffer(StringBuffer input) { + input.append(" world"); + } + + @Test + void givenObjectWithStringField_whenSetDifferentValue_thenObjectIsModified() { + Dummy dummy = new Dummy(); + assertNull(dummy.getDummyString()); + modifyStringValueInInputObject(dummy, "hello world"); + assertEquals("hello world", dummy.getDummyString()); + } + + void modifyStringValueInInputObject(Dummy dummy, String dummyString) { + dummy.setDummyString(dummyString); + } + + @Test + void givenObjectWithStringField_whenSetDifferentValueWithStringBuilder_thenSetStringInNewObject() { + assertEquals("hello world", getDummy("hello", "world").getDummyString()); + } + + Dummy getDummy(String hello, String world) { + StringBuilder builder = new StringBuilder(); + + builder.append(hello) + .append(" ") + .append(world); + + Dummy dummy = new Dummy(); + dummy.setDummyString(builder.toString()); + + return dummy; + } +} From 3df29751a7c5b614719103f8a05fc97392246083 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 06:29:25 +0800 Subject: [PATCH 48/91] Update README.md [skip ci] --- core-java-modules/core-java-collections-maps-7/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-maps-7/README.md b/core-java-modules/core-java-collections-maps-7/README.md index 2724df5695..5599187cd8 100644 --- a/core-java-modules/core-java-collections-maps-7/README.md +++ b/core-java-modules/core-java-collections-maps-7/README.md @@ -1,2 +1,3 @@ ## Relevant Articles - [Difference Between putIfAbsent() and computeIfAbsent() in Java’s Map](https://www.baeldung.com/java-map-putifabsent-computeifabsent) +- [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv) From 467b9a2fedde46fb7633f99c83a91553f4a1bcfa Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 06:31:46 +0800 Subject: [PATCH 49/91] Update README.md [skip ci] --- core-java-modules/core-java-string-algorithms-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-string-algorithms-3/README.md b/core-java-modules/core-java-string-algorithms-3/README.md index 3ef07129ed..abcac63ea4 100644 --- a/core-java-modules/core-java-string-algorithms-3/README.md +++ b/core-java-modules/core-java-string-algorithms-3/README.md @@ -13,3 +13,4 @@ This module contains articles about string-related algorithms. - [Find the Most Frequent Characters in a String](https://www.baeldung.com/java-string-find-most-frequent-characters) - [Checking If a String Is a Repeated Substring](https://www.baeldung.com/java-repeated-substring) - [Check if Letter Is Emoji With Java](https://www.baeldung.com/java-check-letter-emoji) +- [Wrapping a String After a Number of Characters Word-Wise](https://www.baeldung.com/java-wrap-string-number-characters-word-wise) From 353b0974ddce8727cf76526c4b3ccfcc943cf346 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 06:35:10 +0800 Subject: [PATCH 50/91] Update README.md [skip ci] --- testing-modules/testing-libraries-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/testing-libraries-2/README.md b/testing-modules/testing-libraries-2/README.md index 9e17da96a7..a37612e207 100644 --- a/testing-modules/testing-libraries-2/README.md +++ b/testing-modules/testing-libraries-2/README.md @@ -7,3 +7,4 @@ - [Gray Box Testing Using the OAT Technique](https://www.baeldung.com/java-gray-box-orthogonal-array-testing) - [Unit Testing of System.in With JUnit](https://www.baeldung.com/java-junit-testing-system-in) - [Fail Maven Build if JUnit Coverage Falls Below Certain Threshold](https://www.baeldung.com/maven-junit-fail-build-coverage-threshold) +- [How to Mock Environment Variables in Unit Tests](https://www.baeldung.com/java-unit-testing-environment-variables) From f6deb1c0ef3ed7361a397704006fa92993485ffc Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 06:40:01 +0800 Subject: [PATCH 51/91] Update README.md [skip ci] --- core-java-modules/core-java-string-conversions-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-string-conversions-3/README.md b/core-java-modules/core-java-string-conversions-3/README.md index 4ec4771eea..732c864a42 100644 --- a/core-java-modules/core-java-string-conversions-3/README.md +++ b/core-java-modules/core-java-string-conversions-3/README.md @@ -3,3 +3,4 @@ - [Convert String to Int Using Encapsulation](https://www.baeldung.com/java-encapsulation-convert-string-to-int) - [HashMap with Multiple Values for the Same Key](https://www.baeldung.com/java-hashmap-multiple-values-per-key) - [Split Java String Into Key-Value Pairs](https://www.baeldung.com/java-split-string-map) +- [How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output) From 499705b6d1c3466d991f0aaff3416f60c1d8f6a5 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 06:42:50 +0800 Subject: [PATCH 52/91] Update README.md [skip ci] --- core-java-modules/core-java-string-conversions-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-string-conversions-3/README.md b/core-java-modules/core-java-string-conversions-3/README.md index 732c864a42..ec169f71d2 100644 --- a/core-java-modules/core-java-string-conversions-3/README.md +++ b/core-java-modules/core-java-string-conversions-3/README.md @@ -4,3 +4,4 @@ - [HashMap with Multiple Values for the Same Key](https://www.baeldung.com/java-hashmap-multiple-values-per-key) - [Split Java String Into Key-Value Pairs](https://www.baeldung.com/java-split-string-map) - [How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output) +- [How to Convert an Object to String](https://www.baeldung.com/java-object-string-representation) From 8518e65d78c8015e903242c39e5c8bc21b6b493f Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 06:51:40 +0800 Subject: [PATCH 53/91] Update README.md [skip ci] --- core-java-modules/core-java-streams-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-streams-5/README.md b/core-java-modules/core-java-streams-5/README.md index e7c58a0eb2..629d52f0a9 100644 --- a/core-java-modules/core-java-streams-5/README.md +++ b/core-java-modules/core-java-streams-5/README.md @@ -4,3 +4,4 @@ - [Aggregate Runtime Exceptions in Java Streams](https://www.baeldung.com/java-streams-aggregate-exceptions) - [Streams vs. Loops in Java](https://www.baeldung.com/java-streams-vs-loops) - [Partition a Stream in Java](https://www.baeldung.com/java-partition-stream) +- [Taking Every N-th Element from Finite and Infinite Streams in Java](https://www.baeldung.com/java-nth-element-finite-infinite-streams) From 5677bcfc8143e5f221a4ea6a940770a64cca49ca Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 06:57:33 +0800 Subject: [PATCH 54/91] Create README.md [skip ci] --- spring-boot-modules/spring-boot-3-2/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 spring-boot-modules/spring-boot-3-2/README.md diff --git a/spring-boot-modules/spring-boot-3-2/README.md b/spring-boot-modules/spring-boot-3-2/README.md new file mode 100644 index 0000000000..c176de2310 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-2/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Spring Boot 3.1’s ConnectionDetails Abstraction](https://www.baeldung.com/spring-boot-3-1-connectiondetails-abstraction) From a068b3886fdd2a87d4c8a85df8776300a589ba4a Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 07:00:26 +0800 Subject: [PATCH 55/91] Update README.md [skip ci] --- spring-security-modules/spring-security-core-2/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-security-modules/spring-security-core-2/README.md b/spring-security-modules/spring-security-core-2/README.md index 80027ea42f..5f54dc1a50 100644 --- a/spring-security-modules/spring-security-core-2/README.md +++ b/spring-security-modules/spring-security-core-2/README.md @@ -8,7 +8,8 @@ This module contains articles about core Spring Security - [Prevent Cross-Site Scripting (XSS) in a Spring Application](https://www.baeldung.com/spring-prevent-xss) - [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver) - [A Custom Spring SecurityConfigurer](https://www.baeldung.com/spring-security-custom-configurer) - +- [HttpSecurity vs. WebSecurity in Spring Security](https://www.baeldung.com/spring-security-httpsecurity-vs-websecurity) + ### Build the Project `mvn clean install` From fcff2408650431cc9c8a53d982e40e192e073398 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 07:02:12 +0800 Subject: [PATCH 56/91] Update README.md [skip ci] --- core-java-modules/core-java-collections-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-5/README.md b/core-java-modules/core-java-collections-5/README.md index e478d87ad0..1939e5ca3f 100644 --- a/core-java-modules/core-java-collections-5/README.md +++ b/core-java-modules/core-java-collections-5/README.md @@ -7,4 +7,5 @@ - [Creating Custom Iterator in Java](https://www.baeldung.com/java-creating-custom-iterator) - [Difference Between Arrays.sort() and Collections.sort()](https://www.baeldung.com/java-arrays-collections-sort-methods) - [Skipping the First Iteration in Java](https://www.baeldung.com/java-skip-first-iteration) +- [Remove Elements From a Queue Using Loop](https://www.baeldung.com/java-remove-elements-queue) - More articles: [[<-- prev]](/core-java-modules/core-java-collections-4) From fde7fabe427559129ea8cfd7d34dbbf85c4e85e5 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 07:04:20 +0800 Subject: [PATCH 57/91] Update README.md [skip ci] --- core-java-modules/core-java-arrays-operations-basic-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-arrays-operations-basic-2/README.md b/core-java-modules/core-java-arrays-operations-basic-2/README.md index da2f17111f..07eb82ec68 100644 --- a/core-java-modules/core-java-arrays-operations-basic-2/README.md +++ b/core-java-modules/core-java-arrays-operations-basic-2/README.md @@ -3,3 +3,4 @@ This module contains articles about Java array fundamentals. They assume no previous background knowledge on working with arrays. ### Relevant Articles: +- [Arrays mismatch() Method in Java](https://www.baeldung.com/java-arrays-mismatch) From b4fd454c652db63fbc8476cf1f3fdc8cb850469d Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 07:07:22 +0800 Subject: [PATCH 58/91] Update README.md [skip ci] --- core-java-modules/core-java-concurrency-basic-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-concurrency-basic-3/README.md b/core-java-modules/core-java-concurrency-basic-3/README.md index b9c66b279c..179a69495c 100644 --- a/core-java-modules/core-java-concurrency-basic-3/README.md +++ b/core-java-modules/core-java-concurrency-basic-3/README.md @@ -10,4 +10,5 @@ This module contains articles about basic Java concurrency. - [Returning a Value After Finishing Thread’s Job in Java](https://www.baeldung.com/java-return-value-after-thread-finish) - [CompletableFuture and ThreadPool in Java](https://www.baeldung.com/java-completablefuture-threadpool) - [CompletableFuture allOf().join() vs. CompletableFuture.join()](https://www.baeldung.com/java-completablefuture-allof-join) +- [Retry Logic with CompletableFuture](https://www.baeldung.com/java-completablefuture-retry-logic) - [[<-- Prev]](../core-java-concurrency-basic-2) From 1425f647f6465b93deb5863ff0036710eba19e62 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 07:09:45 +0800 Subject: [PATCH 59/91] Update README.md [skip ci] --- core-java-modules/core-java-concurrency-simple/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-concurrency-simple/README.md b/core-java-modules/core-java-concurrency-simple/README.md index 5cbfc67862..422d33e2c3 100644 --- a/core-java-modules/core-java-concurrency-simple/README.md +++ b/core-java-modules/core-java-concurrency-simple/README.md @@ -12,6 +12,7 @@ This module contains articles about Java Concurrency that are also part of an Eb - [Guide to the Volatile Keyword in Java](https://www.baeldung.com/java-volatile) - [A Guide to the Java ExecutorService](https://www.baeldung.com/java-executor-service-tutorial) - [Guide To CompletableFuture](https://www.baeldung.com/java-completablefuture) +- [How To Manage Timeout for CompletableFuture](https://www.baeldung.com/java-completablefuture-timeout) ### NOTE: From 19df93af17f1145e0ee2f746bd005f64f0e8912c Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 07:12:24 +0800 Subject: [PATCH 60/91] Update README.md [skip ci] --- libraries-io/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries-io/README.md b/libraries-io/README.md index 6cfe978d91..a9ca5df3d6 100644 --- a/libraries-io/README.md +++ b/libraries-io/README.md @@ -3,4 +3,4 @@ - [Transferring a File Through SFTP in Java](https://www.baeldung.com/java-file-sftp) - [How to Create Password-Protected Zip Files and Unzip Them in Java](https://www.baeldung.com/java-password-protected-zip-unzip) - +- [How to Create CSV File from POJO with Custom Column Headers and Positions](https://www.baeldung.com/java-create-csv-pojo-customize-columns) From 78dc038e8bcc7d1aedeee356f2647d6cc6b80e31 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 07:14:25 +0800 Subject: [PATCH 61/91] Update README.md [skip ci] --- core-java-modules/core-java-string-operations-7/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-operations-7/README.md b/core-java-modules/core-java-string-operations-7/README.md index 7020369f02..6c4fab384b 100644 --- a/core-java-modules/core-java-string-operations-7/README.md +++ b/core-java-modules/core-java-string-operations-7/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: -[How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output) +- [How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output) +- [Capitalize the First Letter of Each Word in a String](https://www.baeldung.com/java-string-initial-capital-letter-every-word) From fc2cf6cfacce5d594bb25fe308ecfe8cc2b8418b Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 07:18:49 +0800 Subject: [PATCH 62/91] Update README.md [skip ci] --- spring-boot-modules/spring-boot-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-3/README.md b/spring-boot-modules/spring-boot-3/README.md index 8791aaae1f..ded5db30e4 100644 --- a/spring-boot-modules/spring-boot-3/README.md +++ b/spring-boot-modules/spring-boot-3/README.md @@ -8,3 +8,4 @@ - [HTTP Interface in Spring 6](https://www.baeldung.com/spring-6-http-interface) - [Working with Virtual Threads in Spring 6](https://www.baeldung.com/spring-6-virtual-threads) - [Docker Compose Support in Spring Boot 3](https://www.baeldung.com/ops/docker-compose-support-spring-boot) +- [A Guide to RestClient in Spring Boot](https://www.baeldung.com/spring-boot-restclient) From ff76b6c94970d70b3d27730e4a608a8c20800bed Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 29 Oct 2023 07:25:11 +0800 Subject: [PATCH 63/91] Update README.md [skip ci] --- core-java-modules/core-java-string-operations-6/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-operations-6/README.md b/core-java-modules/core-java-string-operations-6/README.md index b4b78d1ad7..9d92552dd1 100644 --- a/core-java-modules/core-java-string-operations-6/README.md +++ b/core-java-modules/core-java-string-operations-6/README.md @@ -11,4 +11,4 @@ - [Check if a String Has All Unique Characters in Java](https://www.baeldung.com/java-check-string-all-unique-chars) - [Performance Comparison Between Different Java String Concatenation Methods](https://www.baeldung.com/java-string-concatenation-methods) - [Replacing Single Quote with \’ in Java String](https://www.baeldung.com/java-replacing-single-quote-string) - +- [Check if a String Contains a Number Value in Java](https://www.baeldung.com/java-string-number-presence) From c115e99dccf7dc1470a5856535fb9fced45d7991 Mon Sep 17 00:00:00 2001 From: pentakon Date: Sun, 29 Oct 2023 06:27:34 +0200 Subject: [PATCH 64/91] BAEL-6814 Convert List to CompletableFuture (#15028) * Code for BAEL-6814 Convert List to CompletableFuture * Refactor some comments --- .../completablefuturelist/Application.java | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuturelist/Application.java diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuturelist/Application.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuturelist/Application.java new file mode 100644 index 0000000000..be5d9e8479 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuturelist/Application.java @@ -0,0 +1,100 @@ +package com.baeldung.concurrent.completablefuturelist; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.stream.Collectors; + +public class Application { + + ScheduledExecutorService asyncOperationEmulation; + + Application initialize() { + asyncOperationEmulation = Executors.newScheduledThreadPool(10); + return this; + } + + CompletableFuture asyncOperation(String operationId) { + CompletableFuture cf = new CompletableFuture<>(); + asyncOperationEmulation.submit(() -> { + // The following lines simulate an exception happening on the 567th operation + // if (operationId.endsWith("567")) { + // cf.completeExceptionally(new Exception("Error on operation " + operationId)); + // return; + // } + try { + Thread.sleep(100); + cf.complete(operationId); + } catch (InterruptedException e) { + System.err.println("Thread interrupted error"); + cf.completeExceptionally(e); + } + }); + return cf; + } + + void startNaive() { + List> futures = new ArrayList<>(); + for (int i = 1; i <= 1000; i++) { + String operationId = "Naive-Operation-" + i; + futures.add(asyncOperation(operationId)); + } + + CompletableFuture> aggregate = CompletableFuture.completedFuture(new ArrayList<>()); + for (CompletableFuture future : futures) { + aggregate = aggregate.thenCompose(list -> { + try { + list.add(future.get()); + return CompletableFuture.completedFuture(list); + } catch (Exception e) { + final CompletableFuture> excFuture = new CompletableFuture<>(); + excFuture.completeExceptionally(e); + return excFuture; + } + }); + } + + try { + final List results = aggregate.join(); + System.out.println("Printing first 10 results"); + for (int i = 0; i < 10; i++) { + System.out.println("Finished " + results.get(i)); + } + } finally { + close(); + } + } + + void start() { + List> futures = new ArrayList<>(); + for (int i = 1; i <= 1000; i++) { + String operationId = "Operation-" + i; + futures.add(asyncOperation(operationId)); + } + CompletableFuture[] futuresArray = futures.toArray(new CompletableFuture[0]); + CompletableFuture> listFuture = CompletableFuture.allOf(futuresArray).thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList())); + try { + final List results = listFuture.join(); + System.out.println("Printing first 10 results"); + for (int i = 0; i < 10; i++) { + System.out.println("Finished " + results.get(i)); + } + } finally { + close(); + } + } + + void close() { + asyncOperationEmulation.shutdownNow(); + } + + public static void main(String[] args) { + new Application().initialize() + // Switch between .startNaive() and .start() to test both implementations + // .startNaive(); + .start(); + } + +} From f5ce4e6d86e5a1e8998d8ce675838f713af02871 Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Sun, 29 Oct 2023 05:28:39 +0100 Subject: [PATCH 65/91] PrintWriter vs FileWriter in Java (#15034) * https://jira.baeldung.com/browse/BAEL-7117 * PrintWriter vs FileWriter in Java * PrintWriter vs FileWriter in Java * https://jira.baeldung.com/browse/BAEL-7117 * PrintWriter vs FileWriter in Java --- .../core-java-io-apis-2/alabama.txt | 2 + .../core-java-io-apis-2/dream.txt | 1 + .../core-java-io-apis-2/potter.txt | 1 + .../PrintWriterVsFilePrinterUnitTest.java | 64 +++++++++++++++++++ 4 files changed, 68 insertions(+) create mode 100644 core-java-modules/core-java-io-apis-2/alabama.txt create mode 100644 core-java-modules/core-java-io-apis-2/dream.txt create mode 100644 core-java-modules/core-java-io-apis-2/potter.txt create mode 100644 core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/printwritervsfilewriter/PrintWriterVsFilePrinterUnitTest.java diff --git a/core-java-modules/core-java-io-apis-2/alabama.txt b/core-java-modules/core-java-io-apis-2/alabama.txt new file mode 100644 index 0000000000..d421fa5c33 --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/alabama.txt @@ -0,0 +1,2 @@ +I'm going to Alabama +Alabama is a state in the US diff --git a/core-java-modules/core-java-io-apis-2/dream.txt b/core-java-modules/core-java-io-apis-2/dream.txt new file mode 100644 index 0000000000..a4821c7dd4 --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/dream.txt @@ -0,0 +1 @@ +Dreams from My Father by Barack Obama \ No newline at end of file diff --git a/core-java-modules/core-java-io-apis-2/potter.txt b/core-java-modules/core-java-io-apis-2/potter.txt new file mode 100644 index 0000000000..78974da192 --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/potter.txt @@ -0,0 +1 @@ +Harry Potter and the Chamber of Secrets \ No newline at end of file diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/printwritervsfilewriter/PrintWriterVsFilePrinterUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/printwritervsfilewriter/PrintWriterVsFilePrinterUnitTest.java new file mode 100644 index 0000000000..6e44ad8318 --- /dev/null +++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/printwritervsfilewriter/PrintWriterVsFilePrinterUnitTest.java @@ -0,0 +1,64 @@ +package com.baeldung.printwritervsfilewriter; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +import org.junit.jupiter.api.Test; + +public class PrintWriterVsFilePrinterUnitTest { + + @Test + public void whenWritingToTextFileUsingFileWriter_thenTextMatches() throws IOException { + String result = "Harry Potter and the Chamber of Secrets"; + + File file = new File("potter.txt"); + try (FileWriter fw = new FileWriter(file);) { + fw.write("Harry Potter and the Chamber of Secrets"); + } + + try (BufferedReader reader = new BufferedReader(new FileReader(file));) { + String actualData = reader.readLine(); + assertEquals(result, actualData); + } + } + + @Test + public void whenWritingToTextFileUsingPrintWriterPrintf_thenTextMatches() throws IOException { + String result = "Dreams from My Father by Barack Obama"; + File file = new File("dream.txt"); + try (PrintWriter pw = new PrintWriter(file);) { + String author = "Barack Obama"; + pw.printf("Dreams from My Father by %s", author); + assertTrue(!pw.checkError()); + } + + try (BufferedReader reader = new BufferedReader(new FileReader(file));) { + String actualData = reader.readLine(); + assertEquals(result, actualData); + } + } + + @Test + public void whenWritingToTextFileUsingPrintWriterPrintln_thenTextMatches() throws IOException { + String result = "I'm going to Alabama\nAlabama is a state in the US\n"; + try (PrintWriter pw = new PrintWriter("alabama.txt");) { + pw.println("I'm going to Alabama"); + pw.println("Alabama is a state in the US"); + } + Path path = Paths.get("alabama.txt"); + String actualData = new String(Files.readAllBytes(path)); + assertEquals(result, actualData); + } + +} From 05230cf79d975489269717e0dcd821847fbfbfc9 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Sun, 29 Oct 2023 18:54:02 +0200 Subject: [PATCH 66/91] [JAVA-26374-boot-data] Moved "Spring Boot: Customize the Jackson ObjectMapper" article to spring-boot-data (#15095) --- spring-boot-modules/spring-boot-data-2/README.md | 1 - spring-boot-modules/spring-boot-data/README.md | 1 + .../com/baeldung/boot/jackson/app/Application.java | 0 .../baeldung/boot/jackson/config/CoffeeConstants.java | 4 ++-- .../boot/jackson/config/CoffeeCustomizerConfig.java | 5 +++-- .../config/CoffeeHttpConverterConfiguration.java | 5 +++-- .../jackson/config/CoffeeJacksonBuilderConfig.java | 5 +++-- .../boot/jackson/config/CoffeeObjectMapperConfig.java | 9 +++++---- .../jackson/config/CoffeeRegisterModuleConfig.java | 8 ++++---- .../boot/jackson/controller/CoffeeController.java | 5 +++-- .../java/com/baeldung/boot/jackson/model/Coffee.java | 0 .../src/main/resources/coffee.properties | 0 .../jackson/app/AbstractCoffeeIntegrationTest.java | 11 ++++++----- .../jackson/app/CoffeeCustomizerIntegrationTest.java | 3 ++- .../app/CoffeeHttpConverterIntegrationTest.java | 3 ++- .../app/CoffeeJacksonBuilderIntegrationTest.java | 3 ++- .../app/CoffeeObjectMapperIntegrationTest.java | 3 ++- .../app/CoffeeRegisterModuleIntegrationTest.java | 3 ++- 18 files changed, 40 insertions(+), 29 deletions(-) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/main/java/com/baeldung/boot/jackson/app/Application.java (100%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java (100%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java (99%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java (99%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java (99%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java (99%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java (88%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java (99%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/main/java/com/baeldung/boot/jackson/model/Coffee.java (100%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/main/resources/coffee.properties (100%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java (99%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java (99%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java (99%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java (99%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java (99%) rename spring-boot-modules/{spring-boot-data-2 => spring-boot-data}/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java (99%) diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md index 9ff2b2caf8..8e6619dce4 100644 --- a/spring-boot-modules/spring-boot-data-2/README.md +++ b/spring-boot-modules/spring-boot-data-2/README.md @@ -1,7 +1,6 @@ ### Relevant Articles: - [HttpMessageNotWritableException: No Converter for [class …] With Preset Content-Type](https://www.baeldung.com/spring-no-converter-with-preset) -- [Spring Boot: Customize the Jackson ObjectMapper](https://www.baeldung.com/spring-boot-customize-jackson-objectmapper) - [“HttpMessageNotWritableException: No converter found for return value of type”](https://www.baeldung.com/spring-no-converter-found) - [Creating a Read-Only Repository with Spring Data](https://www.baeldung.com/spring-data-read-only-repository) - [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) diff --git a/spring-boot-modules/spring-boot-data/README.md b/spring-boot-modules/spring-boot-data/README.md index c56c87014d..aa745b77a2 100644 --- a/spring-boot-modules/spring-boot-data/README.md +++ b/spring-boot-modules/spring-boot-data/README.md @@ -11,4 +11,5 @@ This module contains articles about Spring Boot with Spring Data - [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) - [Using @JsonComponent in Spring Boot](https://www.baeldung.com/spring-boot-jsoncomponent) - [Guide To Running Logic on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) +- [Spring Boot: Customize the Jackson ObjectMapper](https://www.baeldung.com/spring-boot-customize-jackson-objectmapper) diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/app/Application.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/app/Application.java similarity index 100% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/app/Application.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/app/Application.java diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java similarity index 100% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java index d1875d03d9..ecb07e44b1 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeConstants.java @@ -1,10 +1,10 @@ package com.baeldung.boot.jackson.config; -import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; - import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; + public class CoffeeConstants { public static final String DATETIME_FORMAT = "dd-MM-yyyy HH:mm"; diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java index edb2b478fc..0aa2d3eb96 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeCustomizerConfig.java @@ -1,11 +1,12 @@ package com.baeldung.boot.jackson.config; -import com.fasterxml.jackson.annotation.JsonInclude; +import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; + import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; +import com.fasterxml.jackson.annotation.JsonInclude; @Configuration public class CoffeeCustomizerConfig { diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java index eff2b5c252..be8e3bb34d 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeHttpConverterConfiguration.java @@ -1,12 +1,13 @@ package com.baeldung.boot.jackson.config; -import com.fasterxml.jackson.annotation.JsonInclude; +import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; +import com.fasterxml.jackson.annotation.JsonInclude; @Configuration public class CoffeeHttpConverterConfiguration { diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java index 8057fff3db..19501f872c 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeJacksonBuilderConfig.java @@ -1,12 +1,13 @@ package com.baeldung.boot.jackson.config; -import com.fasterxml.jackson.annotation.JsonInclude; +import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; -import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; +import com.fasterxml.jackson.annotation.JsonInclude; @Configuration public class CoffeeJacksonBuilderConfig { diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java index f1ce6458ae..cadf17b6b8 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeObjectMapperConfig.java @@ -1,13 +1,14 @@ package com.baeldung.boot.jackson.config; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; -import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; @Configuration public class CoffeeObjectMapperConfig { diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java similarity index 88% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java index fc157f8156..55a928dabc 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/config/CoffeeRegisterModuleConfig.java @@ -1,19 +1,19 @@ package com.baeldung.boot.jackson.config; -import com.fasterxml.jackson.databind.Module; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; + import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; -import static com.baeldung.boot.jackson.config.CoffeeConstants.LOCAL_DATETIME_SERIALIZER; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; @Configuration @PropertySource("classpath:coffee.properties") public class CoffeeRegisterModuleConfig { @Bean - public Module javaTimeModule() { + public JavaTimeModule javaTimeModule() { JavaTimeModule module = new JavaTimeModule(); module.addSerializer(LOCAL_DATETIME_SERIALIZER); return module; diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java index 23749b18a2..36489a645a 100644 --- a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java +++ b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/controller/CoffeeController.java @@ -1,11 +1,12 @@ package com.baeldung.boot.jackson.controller; -import com.baeldung.boot.jackson.model.Coffee; +import static com.baeldung.boot.jackson.config.CoffeeConstants.FIXED_DATE; + import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import static com.baeldung.boot.jackson.config.CoffeeConstants.FIXED_DATE; +import com.baeldung.boot.jackson.model.Coffee; @RestController public class CoffeeController { diff --git a/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/model/Coffee.java b/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/model/Coffee.java similarity index 100% rename from spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/boot/jackson/model/Coffee.java rename to spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/boot/jackson/model/Coffee.java diff --git a/spring-boot-modules/spring-boot-data-2/src/main/resources/coffee.properties b/spring-boot-modules/spring-boot-data/src/main/resources/coffee.properties similarity index 100% rename from spring-boot-modules/spring-boot-data-2/src/main/resources/coffee.properties rename to spring-boot-modules/spring-boot-data/src/main/resources/coffee.properties diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java index f1bc35a8ce..961ab8979c 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/AbstractCoffeeIntegrationTest.java @@ -1,15 +1,16 @@ package com.baeldung.boot.jackson.app; -import com.baeldung.boot.jackson.config.CoffeeConstants; +import static com.baeldung.boot.jackson.config.CoffeeConstants.FIXED_DATE; +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.format.DateTimeFormatter; + import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; -import java.time.format.DateTimeFormatter; - -import static com.baeldung.boot.jackson.config.CoffeeConstants.FIXED_DATE; -import static org.assertj.core.api.Assertions.assertThat; +import com.baeldung.boot.jackson.config.CoffeeConstants; @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public abstract class AbstractCoffeeIntegrationTest { diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java index d690de1b9c..ed5baf239c 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeCustomizerIntegrationTest.java @@ -1,8 +1,9 @@ package com.baeldung.boot.jackson.app; -import com.baeldung.boot.jackson.config.CoffeeCustomizerConfig; import org.springframework.context.annotation.Import; +import com.baeldung.boot.jackson.config.CoffeeCustomizerConfig; + @Import(CoffeeCustomizerConfig.class) public class CoffeeCustomizerIntegrationTest extends AbstractCoffeeIntegrationTest { } diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java index 62b1d42152..0c77948d8e 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeHttpConverterIntegrationTest.java @@ -1,8 +1,9 @@ package com.baeldung.boot.jackson.app; -import com.baeldung.boot.jackson.config.CoffeeHttpConverterConfiguration; import org.springframework.context.annotation.Import; +import com.baeldung.boot.jackson.config.CoffeeHttpConverterConfiguration; + @Import(CoffeeHttpConverterConfiguration.class) public class CoffeeHttpConverterIntegrationTest extends AbstractCoffeeIntegrationTest { } diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java index 52a55394c0..da9251de99 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeJacksonBuilderIntegrationTest.java @@ -1,8 +1,9 @@ package com.baeldung.boot.jackson.app; -import com.baeldung.boot.jackson.config.CoffeeJacksonBuilderConfig; import org.springframework.context.annotation.Import; +import com.baeldung.boot.jackson.config.CoffeeJacksonBuilderConfig; + @Import(CoffeeJacksonBuilderConfig.class) public class CoffeeJacksonBuilderIntegrationTest extends AbstractCoffeeIntegrationTest { } diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java index 34743ceba5..1226eacbf2 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeObjectMapperIntegrationTest.java @@ -1,8 +1,9 @@ package com.baeldung.boot.jackson.app; -import com.baeldung.boot.jackson.config.CoffeeObjectMapperConfig; import org.springframework.context.annotation.Import; +import com.baeldung.boot.jackson.config.CoffeeObjectMapperConfig; + @Import(CoffeeObjectMapperConfig.class) public class CoffeeObjectMapperIntegrationTest extends AbstractCoffeeIntegrationTest { } diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java rename to spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java index 69bbd5be2a..38dc4a76cd 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java +++ b/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/boot/jackson/app/CoffeeRegisterModuleIntegrationTest.java @@ -1,8 +1,9 @@ package com.baeldung.boot.jackson.app; -import com.baeldung.boot.jackson.config.CoffeeRegisterModuleConfig; import org.springframework.context.annotation.Import; +import com.baeldung.boot.jackson.config.CoffeeRegisterModuleConfig; + @Import(CoffeeRegisterModuleConfig.class) public class CoffeeRegisterModuleIntegrationTest extends AbstractCoffeeIntegrationTest { } From b9fa942d274a490ff79b9e8411c1fd8447190ffc Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sun, 29 Oct 2023 23:22:39 +0530 Subject: [PATCH 67/91] JAVA-26395 Move grails module to web-modules (#15072) --- pom.xml | 2 -- {grails => web-modules/grails}/.gitignore | 0 {grails => web-modules/grails}/README.md | 0 {grails => web-modules/grails}/build.gradle | 0 {grails => web-modules/grails}/gradle.properties | 0 .../gradle/wrapper/gradle-wrapper.properties | 0 {grails => web-modules/grails}/gradlew | 0 {grails => web-modules/grails}/gradlew.bat | 0 .../assets/images/apple-touch-icon-retina.png | Bin .../grails-app/assets/images/apple-touch-icon.png | Bin .../grails}/grails-app/assets/images/favicon.ico | Bin .../assets/images/grails-cupsonly-logo-white.svg | 0 .../grails}/grails-app/assets/images/grails.svg | 0 .../grails-app/assets/images/skin/database_add.png | Bin .../assets/images/skin/database_delete.png | Bin .../grails-app/assets/images/skin/database_edit.png | Bin .../grails-app/assets/images/skin/database_save.png | Bin .../assets/images/skin/database_table.png | Bin .../grails-app/assets/images/skin/exclamation.png | Bin .../grails}/grails-app/assets/images/skin/house.png | Bin .../grails-app/assets/images/skin/information.png | Bin .../grails-app/assets/images/skin/shadow.jpg | Bin .../grails-app/assets/images/skin/sorted_asc.gif | Bin .../grails-app/assets/images/skin/sorted_desc.gif | Bin .../grails}/grails-app/assets/images/spinner.gif | Bin .../grails-app/assets/javascripts/application.js | 0 .../grails-app/assets/javascripts/bootstrap.js | 0 .../assets/javascripts/jquery-2.2.0.min.js | 0 .../grails-app/assets/stylesheets/application.css | 0 .../grails-app/assets/stylesheets/bootstrap.css | 0 .../grails-app/assets/stylesheets/errors.css | 0 .../grails-app/assets/stylesheets/grails.css | 0 .../grails}/grails-app/assets/stylesheets/main.css | 0 .../grails-app/assets/stylesheets/mobile.css | 0 .../grails}/grails-app/conf/application.yml | 0 .../grails}/grails-app/conf/logback.groovy | 0 .../grails}/grails-app/conf/spring/resources.groovy | 0 .../com/baeldung/grails/StudentController.groovy | 0 .../controllers/grails/UrlMappings.groovy | 0 .../domain/com/baeldung/grails/Student.groovy | 0 .../grails}/grails-app/i18n/messages.properties | 0 .../grails}/grails-app/i18n/messages_cs.properties | 0 .../grails}/grails-app/i18n/messages_da.properties | 0 .../grails}/grails-app/i18n/messages_de.properties | 0 .../grails}/grails-app/i18n/messages_es.properties | 0 .../grails}/grails-app/i18n/messages_fr.properties | 0 .../grails}/grails-app/i18n/messages_it.properties | 0 .../grails}/grails-app/i18n/messages_ja.properties | 0 .../grails}/grails-app/i18n/messages_nb.properties | 0 .../grails}/grails-app/i18n/messages_nl.properties | 0 .../grails}/grails-app/i18n/messages_pl.properties | 0 .../grails-app/i18n/messages_pt_BR.properties | 0 .../grails-app/i18n/messages_pt_PT.properties | 0 .../grails}/grails-app/i18n/messages_ru.properties | 0 .../grails}/grails-app/i18n/messages_sk.properties | 0 .../grails}/grails-app/i18n/messages_sv.properties | 0 .../grails}/grails-app/i18n/messages_th.properties | 0 .../grails-app/i18n/messages_zh_CN.properties | 0 .../grails-app/init/grails/Application.groovy | 0 .../grails}/grails-app/init/grails/BootStrap.groovy | 0 .../com/baeldung/grails/StudentService.groovy | 0 .../grails}/grails-app/views/error.gsp | 0 .../grails}/grails-app/views/index.gsp | 0 .../grails}/grails-app/views/layouts/main.gsp | 0 .../grails}/grails-app/views/notFound.gsp | 0 .../grails}/grails-app/views/student/create.gsp | 0 .../grails}/grails-app/views/student/index.gsp | 0 .../grails}/grails-app/views/student/show.gsp | 0 {grails => web-modules/grails}/grailsw | 0 {grails => web-modules/grails}/grailsw.bat | 0 .../baeldung/grails/StudentIntegrationSpec.groovy | 0 .../src/integration-test/resources/GebConfig.groovy | 0 .../baeldung/grails/StudentControllerSpec.groovy | 0 web-modules/pom.xml | 1 + 74 files changed, 1 insertion(+), 2 deletions(-) rename {grails => web-modules/grails}/.gitignore (100%) rename {grails => web-modules/grails}/README.md (100%) rename {grails => web-modules/grails}/build.gradle (100%) rename {grails => web-modules/grails}/gradle.properties (100%) rename {grails => web-modules/grails}/gradle/wrapper/gradle-wrapper.properties (100%) rename {grails => web-modules/grails}/gradlew (100%) rename {grails => web-modules/grails}/gradlew.bat (100%) rename {grails => web-modules/grails}/grails-app/assets/images/apple-touch-icon-retina.png (100%) rename {grails => web-modules/grails}/grails-app/assets/images/apple-touch-icon.png (100%) rename {grails => web-modules/grails}/grails-app/assets/images/favicon.ico (100%) rename {grails => web-modules/grails}/grails-app/assets/images/grails-cupsonly-logo-white.svg (100%) rename {grails => web-modules/grails}/grails-app/assets/images/grails.svg (100%) rename {grails => web-modules/grails}/grails-app/assets/images/skin/database_add.png (100%) rename {grails => web-modules/grails}/grails-app/assets/images/skin/database_delete.png (100%) rename {grails => web-modules/grails}/grails-app/assets/images/skin/database_edit.png (100%) rename {grails => web-modules/grails}/grails-app/assets/images/skin/database_save.png (100%) rename {grails => web-modules/grails}/grails-app/assets/images/skin/database_table.png (100%) rename {grails => web-modules/grails}/grails-app/assets/images/skin/exclamation.png (100%) rename {grails => web-modules/grails}/grails-app/assets/images/skin/house.png (100%) rename {grails => web-modules/grails}/grails-app/assets/images/skin/information.png (100%) rename {grails => web-modules/grails}/grails-app/assets/images/skin/shadow.jpg (100%) rename {grails => web-modules/grails}/grails-app/assets/images/skin/sorted_asc.gif (100%) rename {grails => web-modules/grails}/grails-app/assets/images/skin/sorted_desc.gif (100%) rename {grails => web-modules/grails}/grails-app/assets/images/spinner.gif (100%) rename {grails => web-modules/grails}/grails-app/assets/javascripts/application.js (100%) rename {grails => web-modules/grails}/grails-app/assets/javascripts/bootstrap.js (100%) rename {grails => web-modules/grails}/grails-app/assets/javascripts/jquery-2.2.0.min.js (100%) rename {grails => web-modules/grails}/grails-app/assets/stylesheets/application.css (100%) rename {grails => web-modules/grails}/grails-app/assets/stylesheets/bootstrap.css (100%) rename {grails => web-modules/grails}/grails-app/assets/stylesheets/errors.css (100%) rename {grails => web-modules/grails}/grails-app/assets/stylesheets/grails.css (100%) rename {grails => web-modules/grails}/grails-app/assets/stylesheets/main.css (100%) rename {grails => web-modules/grails}/grails-app/assets/stylesheets/mobile.css (100%) rename {grails => web-modules/grails}/grails-app/conf/application.yml (100%) rename {grails => web-modules/grails}/grails-app/conf/logback.groovy (100%) rename {grails => web-modules/grails}/grails-app/conf/spring/resources.groovy (100%) rename {grails => web-modules/grails}/grails-app/controllers/com/baeldung/grails/StudentController.groovy (100%) rename {grails => web-modules/grails}/grails-app/controllers/grails/UrlMappings.groovy (100%) rename {grails => web-modules/grails}/grails-app/domain/com/baeldung/grails/Student.groovy (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_cs.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_da.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_de.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_es.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_fr.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_it.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_ja.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_nb.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_nl.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_pl.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_pt_BR.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_pt_PT.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_ru.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_sk.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_sv.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_th.properties (100%) rename {grails => web-modules/grails}/grails-app/i18n/messages_zh_CN.properties (100%) rename {grails => web-modules/grails}/grails-app/init/grails/Application.groovy (100%) rename {grails => web-modules/grails}/grails-app/init/grails/BootStrap.groovy (100%) rename {grails => web-modules/grails}/grails-app/services/com/baeldung/grails/StudentService.groovy (100%) rename {grails => web-modules/grails}/grails-app/views/error.gsp (100%) rename {grails => web-modules/grails}/grails-app/views/index.gsp (100%) rename {grails => web-modules/grails}/grails-app/views/layouts/main.gsp (100%) rename {grails => web-modules/grails}/grails-app/views/notFound.gsp (100%) rename {grails => web-modules/grails}/grails-app/views/student/create.gsp (100%) rename {grails => web-modules/grails}/grails-app/views/student/index.gsp (100%) rename {grails => web-modules/grails}/grails-app/views/student/show.gsp (100%) rename {grails => web-modules/grails}/grailsw (100%) rename {grails => web-modules/grails}/grailsw.bat (100%) rename {grails => web-modules/grails}/src/integration-test/groovy/com/baeldung/grails/StudentIntegrationSpec.groovy (100%) rename {grails => web-modules/grails}/src/integration-test/resources/GebConfig.groovy (100%) rename {grails => web-modules/grails}/src/test/groovy/com/baeldung/grails/StudentControllerSpec.groovy (100%) diff --git a/pom.xml b/pom.xml index 07b9d6d842..64ef6697a0 100644 --- a/pom.xml +++ b/pom.xml @@ -349,7 +349,6 @@ - @@ -523,7 +522,6 @@ - diff --git a/grails/.gitignore b/web-modules/grails/.gitignore similarity index 100% rename from grails/.gitignore rename to web-modules/grails/.gitignore diff --git a/grails/README.md b/web-modules/grails/README.md similarity index 100% rename from grails/README.md rename to web-modules/grails/README.md diff --git a/grails/build.gradle b/web-modules/grails/build.gradle similarity index 100% rename from grails/build.gradle rename to web-modules/grails/build.gradle diff --git a/grails/gradle.properties b/web-modules/grails/gradle.properties similarity index 100% rename from grails/gradle.properties rename to web-modules/grails/gradle.properties diff --git a/grails/gradle/wrapper/gradle-wrapper.properties b/web-modules/grails/gradle/wrapper/gradle-wrapper.properties similarity index 100% rename from grails/gradle/wrapper/gradle-wrapper.properties rename to web-modules/grails/gradle/wrapper/gradle-wrapper.properties diff --git a/grails/gradlew b/web-modules/grails/gradlew similarity index 100% rename from grails/gradlew rename to web-modules/grails/gradlew diff --git a/grails/gradlew.bat b/web-modules/grails/gradlew.bat similarity index 100% rename from grails/gradlew.bat rename to web-modules/grails/gradlew.bat diff --git a/grails/grails-app/assets/images/apple-touch-icon-retina.png b/web-modules/grails/grails-app/assets/images/apple-touch-icon-retina.png similarity index 100% rename from grails/grails-app/assets/images/apple-touch-icon-retina.png rename to web-modules/grails/grails-app/assets/images/apple-touch-icon-retina.png diff --git a/grails/grails-app/assets/images/apple-touch-icon.png b/web-modules/grails/grails-app/assets/images/apple-touch-icon.png similarity index 100% rename from grails/grails-app/assets/images/apple-touch-icon.png rename to web-modules/grails/grails-app/assets/images/apple-touch-icon.png diff --git a/grails/grails-app/assets/images/favicon.ico b/web-modules/grails/grails-app/assets/images/favicon.ico similarity index 100% rename from grails/grails-app/assets/images/favicon.ico rename to web-modules/grails/grails-app/assets/images/favicon.ico diff --git a/grails/grails-app/assets/images/grails-cupsonly-logo-white.svg b/web-modules/grails/grails-app/assets/images/grails-cupsonly-logo-white.svg similarity index 100% rename from grails/grails-app/assets/images/grails-cupsonly-logo-white.svg rename to web-modules/grails/grails-app/assets/images/grails-cupsonly-logo-white.svg diff --git a/grails/grails-app/assets/images/grails.svg b/web-modules/grails/grails-app/assets/images/grails.svg similarity index 100% rename from grails/grails-app/assets/images/grails.svg rename to web-modules/grails/grails-app/assets/images/grails.svg diff --git a/grails/grails-app/assets/images/skin/database_add.png b/web-modules/grails/grails-app/assets/images/skin/database_add.png similarity index 100% rename from grails/grails-app/assets/images/skin/database_add.png rename to web-modules/grails/grails-app/assets/images/skin/database_add.png diff --git a/grails/grails-app/assets/images/skin/database_delete.png b/web-modules/grails/grails-app/assets/images/skin/database_delete.png similarity index 100% rename from grails/grails-app/assets/images/skin/database_delete.png rename to web-modules/grails/grails-app/assets/images/skin/database_delete.png diff --git a/grails/grails-app/assets/images/skin/database_edit.png b/web-modules/grails/grails-app/assets/images/skin/database_edit.png similarity index 100% rename from grails/grails-app/assets/images/skin/database_edit.png rename to web-modules/grails/grails-app/assets/images/skin/database_edit.png diff --git a/grails/grails-app/assets/images/skin/database_save.png b/web-modules/grails/grails-app/assets/images/skin/database_save.png similarity index 100% rename from grails/grails-app/assets/images/skin/database_save.png rename to web-modules/grails/grails-app/assets/images/skin/database_save.png diff --git a/grails/grails-app/assets/images/skin/database_table.png b/web-modules/grails/grails-app/assets/images/skin/database_table.png similarity index 100% rename from grails/grails-app/assets/images/skin/database_table.png rename to web-modules/grails/grails-app/assets/images/skin/database_table.png diff --git a/grails/grails-app/assets/images/skin/exclamation.png b/web-modules/grails/grails-app/assets/images/skin/exclamation.png similarity index 100% rename from grails/grails-app/assets/images/skin/exclamation.png rename to web-modules/grails/grails-app/assets/images/skin/exclamation.png diff --git a/grails/grails-app/assets/images/skin/house.png b/web-modules/grails/grails-app/assets/images/skin/house.png similarity index 100% rename from grails/grails-app/assets/images/skin/house.png rename to web-modules/grails/grails-app/assets/images/skin/house.png diff --git a/grails/grails-app/assets/images/skin/information.png b/web-modules/grails/grails-app/assets/images/skin/information.png similarity index 100% rename from grails/grails-app/assets/images/skin/information.png rename to web-modules/grails/grails-app/assets/images/skin/information.png diff --git a/grails/grails-app/assets/images/skin/shadow.jpg b/web-modules/grails/grails-app/assets/images/skin/shadow.jpg similarity index 100% rename from grails/grails-app/assets/images/skin/shadow.jpg rename to web-modules/grails/grails-app/assets/images/skin/shadow.jpg diff --git a/grails/grails-app/assets/images/skin/sorted_asc.gif b/web-modules/grails/grails-app/assets/images/skin/sorted_asc.gif similarity index 100% rename from grails/grails-app/assets/images/skin/sorted_asc.gif rename to web-modules/grails/grails-app/assets/images/skin/sorted_asc.gif diff --git a/grails/grails-app/assets/images/skin/sorted_desc.gif b/web-modules/grails/grails-app/assets/images/skin/sorted_desc.gif similarity index 100% rename from grails/grails-app/assets/images/skin/sorted_desc.gif rename to web-modules/grails/grails-app/assets/images/skin/sorted_desc.gif diff --git a/grails/grails-app/assets/images/spinner.gif b/web-modules/grails/grails-app/assets/images/spinner.gif similarity index 100% rename from grails/grails-app/assets/images/spinner.gif rename to web-modules/grails/grails-app/assets/images/spinner.gif diff --git a/grails/grails-app/assets/javascripts/application.js b/web-modules/grails/grails-app/assets/javascripts/application.js similarity index 100% rename from grails/grails-app/assets/javascripts/application.js rename to web-modules/grails/grails-app/assets/javascripts/application.js diff --git a/grails/grails-app/assets/javascripts/bootstrap.js b/web-modules/grails/grails-app/assets/javascripts/bootstrap.js similarity index 100% rename from grails/grails-app/assets/javascripts/bootstrap.js rename to web-modules/grails/grails-app/assets/javascripts/bootstrap.js diff --git a/grails/grails-app/assets/javascripts/jquery-2.2.0.min.js b/web-modules/grails/grails-app/assets/javascripts/jquery-2.2.0.min.js similarity index 100% rename from grails/grails-app/assets/javascripts/jquery-2.2.0.min.js rename to web-modules/grails/grails-app/assets/javascripts/jquery-2.2.0.min.js diff --git a/grails/grails-app/assets/stylesheets/application.css b/web-modules/grails/grails-app/assets/stylesheets/application.css similarity index 100% rename from grails/grails-app/assets/stylesheets/application.css rename to web-modules/grails/grails-app/assets/stylesheets/application.css diff --git a/grails/grails-app/assets/stylesheets/bootstrap.css b/web-modules/grails/grails-app/assets/stylesheets/bootstrap.css similarity index 100% rename from grails/grails-app/assets/stylesheets/bootstrap.css rename to web-modules/grails/grails-app/assets/stylesheets/bootstrap.css diff --git a/grails/grails-app/assets/stylesheets/errors.css b/web-modules/grails/grails-app/assets/stylesheets/errors.css similarity index 100% rename from grails/grails-app/assets/stylesheets/errors.css rename to web-modules/grails/grails-app/assets/stylesheets/errors.css diff --git a/grails/grails-app/assets/stylesheets/grails.css b/web-modules/grails/grails-app/assets/stylesheets/grails.css similarity index 100% rename from grails/grails-app/assets/stylesheets/grails.css rename to web-modules/grails/grails-app/assets/stylesheets/grails.css diff --git a/grails/grails-app/assets/stylesheets/main.css b/web-modules/grails/grails-app/assets/stylesheets/main.css similarity index 100% rename from grails/grails-app/assets/stylesheets/main.css rename to web-modules/grails/grails-app/assets/stylesheets/main.css diff --git a/grails/grails-app/assets/stylesheets/mobile.css b/web-modules/grails/grails-app/assets/stylesheets/mobile.css similarity index 100% rename from grails/grails-app/assets/stylesheets/mobile.css rename to web-modules/grails/grails-app/assets/stylesheets/mobile.css diff --git a/grails/grails-app/conf/application.yml b/web-modules/grails/grails-app/conf/application.yml similarity index 100% rename from grails/grails-app/conf/application.yml rename to web-modules/grails/grails-app/conf/application.yml diff --git a/grails/grails-app/conf/logback.groovy b/web-modules/grails/grails-app/conf/logback.groovy similarity index 100% rename from grails/grails-app/conf/logback.groovy rename to web-modules/grails/grails-app/conf/logback.groovy diff --git a/grails/grails-app/conf/spring/resources.groovy b/web-modules/grails/grails-app/conf/spring/resources.groovy similarity index 100% rename from grails/grails-app/conf/spring/resources.groovy rename to web-modules/grails/grails-app/conf/spring/resources.groovy diff --git a/grails/grails-app/controllers/com/baeldung/grails/StudentController.groovy b/web-modules/grails/grails-app/controllers/com/baeldung/grails/StudentController.groovy similarity index 100% rename from grails/grails-app/controllers/com/baeldung/grails/StudentController.groovy rename to web-modules/grails/grails-app/controllers/com/baeldung/grails/StudentController.groovy diff --git a/grails/grails-app/controllers/grails/UrlMappings.groovy b/web-modules/grails/grails-app/controllers/grails/UrlMappings.groovy similarity index 100% rename from grails/grails-app/controllers/grails/UrlMappings.groovy rename to web-modules/grails/grails-app/controllers/grails/UrlMappings.groovy diff --git a/grails/grails-app/domain/com/baeldung/grails/Student.groovy b/web-modules/grails/grails-app/domain/com/baeldung/grails/Student.groovy similarity index 100% rename from grails/grails-app/domain/com/baeldung/grails/Student.groovy rename to web-modules/grails/grails-app/domain/com/baeldung/grails/Student.groovy diff --git a/grails/grails-app/i18n/messages.properties b/web-modules/grails/grails-app/i18n/messages.properties similarity index 100% rename from grails/grails-app/i18n/messages.properties rename to web-modules/grails/grails-app/i18n/messages.properties diff --git a/grails/grails-app/i18n/messages_cs.properties b/web-modules/grails/grails-app/i18n/messages_cs.properties similarity index 100% rename from grails/grails-app/i18n/messages_cs.properties rename to web-modules/grails/grails-app/i18n/messages_cs.properties diff --git a/grails/grails-app/i18n/messages_da.properties b/web-modules/grails/grails-app/i18n/messages_da.properties similarity index 100% rename from grails/grails-app/i18n/messages_da.properties rename to web-modules/grails/grails-app/i18n/messages_da.properties diff --git a/grails/grails-app/i18n/messages_de.properties b/web-modules/grails/grails-app/i18n/messages_de.properties similarity index 100% rename from grails/grails-app/i18n/messages_de.properties rename to web-modules/grails/grails-app/i18n/messages_de.properties diff --git a/grails/grails-app/i18n/messages_es.properties b/web-modules/grails/grails-app/i18n/messages_es.properties similarity index 100% rename from grails/grails-app/i18n/messages_es.properties rename to web-modules/grails/grails-app/i18n/messages_es.properties diff --git a/grails/grails-app/i18n/messages_fr.properties b/web-modules/grails/grails-app/i18n/messages_fr.properties similarity index 100% rename from grails/grails-app/i18n/messages_fr.properties rename to web-modules/grails/grails-app/i18n/messages_fr.properties diff --git a/grails/grails-app/i18n/messages_it.properties b/web-modules/grails/grails-app/i18n/messages_it.properties similarity index 100% rename from grails/grails-app/i18n/messages_it.properties rename to web-modules/grails/grails-app/i18n/messages_it.properties diff --git a/grails/grails-app/i18n/messages_ja.properties b/web-modules/grails/grails-app/i18n/messages_ja.properties similarity index 100% rename from grails/grails-app/i18n/messages_ja.properties rename to web-modules/grails/grails-app/i18n/messages_ja.properties diff --git a/grails/grails-app/i18n/messages_nb.properties b/web-modules/grails/grails-app/i18n/messages_nb.properties similarity index 100% rename from grails/grails-app/i18n/messages_nb.properties rename to web-modules/grails/grails-app/i18n/messages_nb.properties diff --git a/grails/grails-app/i18n/messages_nl.properties b/web-modules/grails/grails-app/i18n/messages_nl.properties similarity index 100% rename from grails/grails-app/i18n/messages_nl.properties rename to web-modules/grails/grails-app/i18n/messages_nl.properties diff --git a/grails/grails-app/i18n/messages_pl.properties b/web-modules/grails/grails-app/i18n/messages_pl.properties similarity index 100% rename from grails/grails-app/i18n/messages_pl.properties rename to web-modules/grails/grails-app/i18n/messages_pl.properties diff --git a/grails/grails-app/i18n/messages_pt_BR.properties b/web-modules/grails/grails-app/i18n/messages_pt_BR.properties similarity index 100% rename from grails/grails-app/i18n/messages_pt_BR.properties rename to web-modules/grails/grails-app/i18n/messages_pt_BR.properties diff --git a/grails/grails-app/i18n/messages_pt_PT.properties b/web-modules/grails/grails-app/i18n/messages_pt_PT.properties similarity index 100% rename from grails/grails-app/i18n/messages_pt_PT.properties rename to web-modules/grails/grails-app/i18n/messages_pt_PT.properties diff --git a/grails/grails-app/i18n/messages_ru.properties b/web-modules/grails/grails-app/i18n/messages_ru.properties similarity index 100% rename from grails/grails-app/i18n/messages_ru.properties rename to web-modules/grails/grails-app/i18n/messages_ru.properties diff --git a/grails/grails-app/i18n/messages_sk.properties b/web-modules/grails/grails-app/i18n/messages_sk.properties similarity index 100% rename from grails/grails-app/i18n/messages_sk.properties rename to web-modules/grails/grails-app/i18n/messages_sk.properties diff --git a/grails/grails-app/i18n/messages_sv.properties b/web-modules/grails/grails-app/i18n/messages_sv.properties similarity index 100% rename from grails/grails-app/i18n/messages_sv.properties rename to web-modules/grails/grails-app/i18n/messages_sv.properties diff --git a/grails/grails-app/i18n/messages_th.properties b/web-modules/grails/grails-app/i18n/messages_th.properties similarity index 100% rename from grails/grails-app/i18n/messages_th.properties rename to web-modules/grails/grails-app/i18n/messages_th.properties diff --git a/grails/grails-app/i18n/messages_zh_CN.properties b/web-modules/grails/grails-app/i18n/messages_zh_CN.properties similarity index 100% rename from grails/grails-app/i18n/messages_zh_CN.properties rename to web-modules/grails/grails-app/i18n/messages_zh_CN.properties diff --git a/grails/grails-app/init/grails/Application.groovy b/web-modules/grails/grails-app/init/grails/Application.groovy similarity index 100% rename from grails/grails-app/init/grails/Application.groovy rename to web-modules/grails/grails-app/init/grails/Application.groovy diff --git a/grails/grails-app/init/grails/BootStrap.groovy b/web-modules/grails/grails-app/init/grails/BootStrap.groovy similarity index 100% rename from grails/grails-app/init/grails/BootStrap.groovy rename to web-modules/grails/grails-app/init/grails/BootStrap.groovy diff --git a/grails/grails-app/services/com/baeldung/grails/StudentService.groovy b/web-modules/grails/grails-app/services/com/baeldung/grails/StudentService.groovy similarity index 100% rename from grails/grails-app/services/com/baeldung/grails/StudentService.groovy rename to web-modules/grails/grails-app/services/com/baeldung/grails/StudentService.groovy diff --git a/grails/grails-app/views/error.gsp b/web-modules/grails/grails-app/views/error.gsp similarity index 100% rename from grails/grails-app/views/error.gsp rename to web-modules/grails/grails-app/views/error.gsp diff --git a/grails/grails-app/views/index.gsp b/web-modules/grails/grails-app/views/index.gsp similarity index 100% rename from grails/grails-app/views/index.gsp rename to web-modules/grails/grails-app/views/index.gsp diff --git a/grails/grails-app/views/layouts/main.gsp b/web-modules/grails/grails-app/views/layouts/main.gsp similarity index 100% rename from grails/grails-app/views/layouts/main.gsp rename to web-modules/grails/grails-app/views/layouts/main.gsp diff --git a/grails/grails-app/views/notFound.gsp b/web-modules/grails/grails-app/views/notFound.gsp similarity index 100% rename from grails/grails-app/views/notFound.gsp rename to web-modules/grails/grails-app/views/notFound.gsp diff --git a/grails/grails-app/views/student/create.gsp b/web-modules/grails/grails-app/views/student/create.gsp similarity index 100% rename from grails/grails-app/views/student/create.gsp rename to web-modules/grails/grails-app/views/student/create.gsp diff --git a/grails/grails-app/views/student/index.gsp b/web-modules/grails/grails-app/views/student/index.gsp similarity index 100% rename from grails/grails-app/views/student/index.gsp rename to web-modules/grails/grails-app/views/student/index.gsp diff --git a/grails/grails-app/views/student/show.gsp b/web-modules/grails/grails-app/views/student/show.gsp similarity index 100% rename from grails/grails-app/views/student/show.gsp rename to web-modules/grails/grails-app/views/student/show.gsp diff --git a/grails/grailsw b/web-modules/grails/grailsw similarity index 100% rename from grails/grailsw rename to web-modules/grails/grailsw diff --git a/grails/grailsw.bat b/web-modules/grails/grailsw.bat similarity index 100% rename from grails/grailsw.bat rename to web-modules/grails/grailsw.bat diff --git a/grails/src/integration-test/groovy/com/baeldung/grails/StudentIntegrationSpec.groovy b/web-modules/grails/src/integration-test/groovy/com/baeldung/grails/StudentIntegrationSpec.groovy similarity index 100% rename from grails/src/integration-test/groovy/com/baeldung/grails/StudentIntegrationSpec.groovy rename to web-modules/grails/src/integration-test/groovy/com/baeldung/grails/StudentIntegrationSpec.groovy diff --git a/grails/src/integration-test/resources/GebConfig.groovy b/web-modules/grails/src/integration-test/resources/GebConfig.groovy similarity index 100% rename from grails/src/integration-test/resources/GebConfig.groovy rename to web-modules/grails/src/integration-test/resources/GebConfig.groovy diff --git a/grails/src/test/groovy/com/baeldung/grails/StudentControllerSpec.groovy b/web-modules/grails/src/test/groovy/com/baeldung/grails/StudentControllerSpec.groovy similarity index 100% rename from grails/src/test/groovy/com/baeldung/grails/StudentControllerSpec.groovy rename to web-modules/grails/src/test/groovy/com/baeldung/grails/StudentControllerSpec.groovy diff --git a/web-modules/pom.xml b/web-modules/pom.xml index 684283b546..57810f90de 100644 --- a/web-modules/pom.xml +++ b/web-modules/pom.xml @@ -19,6 +19,7 @@ bootique dropwizard google-web-toolkit + jakarta-ee javax-servlets From 2b22ffc5eae54acbae886ff4849c95953e8c556d Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Sun, 29 Oct 2023 23:23:54 +0530 Subject: [PATCH 68/91] Fixed as par some more review comments. --- libraries-llms/README.md | 6 ------ .../com/baeldung/langchain/ChainWithDocumentLiveTest.java | 2 -- .../com/baeldung/langchain/ChatWithDocumentLiveTest.java | 2 -- .../java/com/baeldung/langchain/ChatWithMemoryLiveTest.java | 5 +---- .../com/baeldung/langchain/PromptTemplatesLiveTest.java | 2 -- .../com/baeldung/langchain/ServiceWithToolsLiveTest.java | 5 ----- 6 files changed, 1 insertion(+), 21 deletions(-) delete mode 100644 libraries-llms/README.md diff --git a/libraries-llms/README.md b/libraries-llms/README.md deleted file mode 100644 index 2e250d42d6..0000000000 --- a/libraries-llms/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Language Model Integration Libraries - -This module contains articles about libraries for language model integration in Java. - -### Relevant articles -- [Introduction to LangChain](https://www.baeldung.com/langchain) \ No newline at end of file diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java index 804a052990..eec7da99fd 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java @@ -31,7 +31,6 @@ public class ChainWithDocumentLiveTest { @Test public void givenChainWithDocument_whenPrompted_thenValidResponse() { - EmbeddingModel embeddingModel = new AllMiniLmL6V2EmbeddingModel(); EmbeddingStore embeddingStore = new InMemoryEmbeddingStore<>(); @@ -61,7 +60,6 @@ public class ChainWithDocumentLiveTest { logger.info(answer); assertNotNull(answer); - } } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java index 7ae50c6bc4..cbbcc7dd23 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java @@ -38,7 +38,6 @@ public class ChatWithDocumentLiveTest { @Test public void givenDocument_whenPrompted_thenValidResponse() { - Document document = loadDocument(Paths.get("src/test/resources/example-files/simpson's_adventures.txt")); DocumentSplitter splitter = DocumentSplitters.recursive(100, 0, new OpenAiTokenizer(GPT_3_5_TURBO)); List segments = splitter.split(document); @@ -77,7 +76,6 @@ public class ChatWithDocumentLiveTest { logger.info(aiMessage.text()); assertNotNull(aiMessage.text()); - } } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java index cae6a7930a..7a67c0be0e 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java @@ -22,7 +22,6 @@ public class ChatWithMemoryLiveTest { @Test public void givenMemory_whenPrompted_thenValidResponse() { - ChatLanguageModel model = OpenAiChatModel.withApiKey(Constants.OPEN_AI_KEY); ChatMemory chatMemory = TokenWindowChatMemory.withMaxTokens(300, new OpenAiTokenizer(GPT_3_5_TURBO)); @@ -38,9 +37,7 @@ public class ChatWithMemoryLiveTest { .content(); logger.info(answerWithName.text()); chatMemory.add(answerWithName); - assertThat(answerWithName.text() - .contains("Kumar")); - + assertThat(answerWithName.text()).contains("Kumar"); } } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java index 1350872eb1..b05727f15f 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java @@ -21,7 +21,6 @@ public class PromptTemplatesLiveTest { @Test public void givenPromptTemplate_whenSuppliedInput_thenValidResponse() { - PromptTemplate promptTemplate = PromptTemplate.from("Tell me a {{adjective}} joke about {{content}}.."); Map variables = new HashMap<>(); variables.put("adjective", "funny"); @@ -37,7 +36,6 @@ public class PromptTemplatesLiveTest { String response = model.generate(prompt.text()); logger.info(response); assertNotNull(response); - } } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java index 9d64d1fc97..1df08e6d35 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java @@ -16,7 +16,6 @@ public class ServiceWithToolsLiveTest { private static final Logger logger = LoggerFactory.getLogger(ServiceWithToolsLiveTest.class); static class Calculator { - @Tool("Calculates the length of a string") int stringLength(String s) { return s.length(); @@ -26,17 +25,14 @@ public class ServiceWithToolsLiveTest { int add(int a, int b) { return a + b; } - } interface Assistant { - String chat(String userMessage); } @Test public void givenServiceWithTools_whenPrompted_thenValidResponse() { - Assistant assistant = AiServices.builder(Assistant.class) .chatLanguageModel(OpenAiChatModel.withApiKey(Constants.OPEN_AI_KEY)) .tools(new Calculator()) @@ -48,7 +44,6 @@ public class ServiceWithToolsLiveTest { logger.info(answer); assertThat(answer).contains("13"); - } } From b7edd335a9d45e6fb2fee37e50ffcd9a95ef032d Mon Sep 17 00:00:00 2001 From: Alvin Austria Date: Sun, 29 Oct 2023 19:14:06 +0100 Subject: [PATCH 69/91] Java 20557: Upgrade hibernate-ogm to JDK 11 (#15064) --- .../test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java | 1 + pom.xml | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java index d7fd49d917..3903e272de 100644 --- a/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java +++ b/persistence-modules/hibernate-ogm/src/test/java/com/baeldung/hibernate/ogm/EditorUnitTest.java @@ -22,6 +22,7 @@ public class EditorUnitTest { loadAndVerifyTestData(entityManagerFactory, editor); } */ + @Test public void givenNeo4j_WhenEntitiesCreated_thenCanBeRetrieved() throws Exception { EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ogm-neo4j"); diff --git a/pom.xml b/pom.xml index 64ef6697a0..7bde142fbc 100644 --- a/pom.xml +++ b/pom.xml @@ -361,7 +361,7 @@ muleesb web-modules/java-lite persistence-modules/deltaspike - persistence-modules/hibernate-ogm + persistence-modules/hibernate-ogm persistence-modules/spring-data-cassandra-reactive java-nashorn jeromq @@ -532,7 +532,7 @@ muleesb web-modules/java-lite persistence-modules/deltaspike - persistence-modules/hibernate-ogm + persistence-modules/hibernate-ogm persistence-modules/spring-data-cassandra-reactive java-nashorn jeromq From a127e7644e9166d2eba73aca0e4fef901d4dcf02 Mon Sep 17 00:00:00 2001 From: Manfred <77407079+manfred106@users.noreply.github.com> Date: Mon, 30 Oct 2023 00:56:52 +0000 Subject: [PATCH 70/91] BAEL-6804: Difference Between ZipFile and ZipInputStream in Java (#15039) * BAEL-6804: Difference Between ZipFile and ZipInputStream in Java * BAEL-6804: Difference Between ZipFile and ZipInputStream in Java - use 2-space indents for line continuations --- core-java-modules/core-java-io-5/pom.xml | 16 +++ .../java/com/baeldung/zip/ZipBenchmark.java | 112 ++++++++++++++++++ .../com/baeldung/zip/ZipSampleFileStore.java | 70 +++++++++++ .../java/com/baeldung/zip/ZipUnitTest.java | 83 +++++++++++++ 4 files changed, 281 insertions(+) create mode 100644 core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipBenchmark.java create mode 100644 core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipSampleFileStore.java create mode 100644 core-java-modules/core-java-io-5/src/test/java/com/baeldung/zip/ZipUnitTest.java diff --git a/core-java-modules/core-java-io-5/pom.xml b/core-java-modules/core-java-io-5/pom.xml index 11116b071c..5c987a82e1 100644 --- a/core-java-modules/core-java-io-5/pom.xml +++ b/core-java-modules/core-java-io-5/pom.xml @@ -35,6 +35,21 @@ simplemagic ${simplemagic.version} + + commons-io + commons-io + ${commons-io.version} + + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + @@ -62,5 +77,6 @@ 0.1.5 6.2.1 1.17 + 1.37 \ No newline at end of file diff --git a/core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipBenchmark.java b/core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipBenchmark.java new file mode 100644 index 0000000000..30ec1522a2 --- /dev/null +++ b/core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipBenchmark.java @@ -0,0 +1,112 @@ +package com.baeldung.zip; + +import java.io.*; +import java.util.concurrent.TimeUnit; +import java.util.*; +import java.util.zip.*; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.infra.Blackhole; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@Warmup(iterations = 1, time = 2, timeUnit = TimeUnit.SECONDS) +@Measurement(iterations = 3, time = 1, timeUnit = TimeUnit.SECONDS) +@OutputTimeUnit(TimeUnit.MILLISECONDS) +@Fork(value = 1) +public class ZipBenchmark { + + public static final int NUM_OF_FILES = 10; + public static final int DATA_SIZE = 204800; + + @State(Scope.Thread) + public static class SourceState { + + public File compressedFile; + + @Setup(Level.Trial) + public void setup() throws IOException { + ZipSampleFileStore sampleFileStore = new ZipSampleFileStore(NUM_OF_FILES, DATA_SIZE); + compressedFile = sampleFileStore.getFile(); + } + + @TearDown(Level.Trial) + public void cleanup() { + if (compressedFile.exists()) { + compressedFile.delete(); + } + } + } + + @Benchmark + public static void readAllEntriesByZipFile(SourceState sourceState, Blackhole blackhole) throws IOException { + + try (ZipFile zipFile = new ZipFile(sourceState.compressedFile)) { + Enumeration zipEntries = zipFile.entries(); + while (zipEntries.hasMoreElements()) { + ZipEntry zipEntry = zipEntries.nextElement(); + try (InputStream inputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry))) { + blackhole.consume(ZipSampleFileStore.getString(inputStream)); + } + } + } + } + + @Benchmark + public static void readAllEntriesByZipInputStream(SourceState sourceState, Blackhole blackhole) throws IOException { + + try ( + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceState.compressedFile)); + ZipInputStream zipInputStream = new ZipInputStream(bis) + ) { + ZipEntry entry; + while ((entry = zipInputStream.getNextEntry()) != null) { + blackhole.consume(ZipSampleFileStore.getString(zipInputStream)); + } + } + } + + @Benchmark + public static void readLastEntryByZipFile(SourceState sourceState, Blackhole blackhole) throws IOException { + + try (ZipFile zipFile = new ZipFile(sourceState.compressedFile)) { + ZipEntry zipEntry = zipFile.getEntry(getLastEntryName()); + try (InputStream inputStream = new BufferedInputStream(zipFile.getInputStream(zipEntry))) { + blackhole.consume(ZipSampleFileStore.getString(inputStream)); + } + } + } + + @Benchmark + public static void readLastEntryByZipInputStream(SourceState sourceState, Blackhole blackhole) throws IOException { + + try ( + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceState.compressedFile)); + ZipInputStream zipInputStream = new ZipInputStream(bis) + ) { + ZipEntry entry; + while ((entry = zipInputStream.getNextEntry()) != null) { + if (Objects.equals(entry.getName(), getLastEntryName())){ + blackhole.consume(ZipSampleFileStore.getString(zipInputStream)); + } + } + } + } + + private static String getLastEntryName() { + return String.format(ZipSampleFileStore.ENTRY_NAME_PATTERN, NUM_OF_FILES); + } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder() + .include(ZipBenchmark.class.getSimpleName()).threads(1) + .shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server").build(); + new Runner(options).run(); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipSampleFileStore.java b/core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipSampleFileStore.java new file mode 100644 index 0000000000..389f082ff1 --- /dev/null +++ b/core-java-modules/core-java-io-5/src/main/java/com/baeldung/zip/ZipSampleFileStore.java @@ -0,0 +1,70 @@ +package com.baeldung.zip; + +import java.io.*; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.apache.commons.io.IOUtils; + +public class ZipSampleFileStore { + + public static final String ENTRY_NAME_PATTERN = "str-data-%s.txt"; + private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; + + private final File file; + private final List dataList; + + public ZipSampleFileStore(int numOfFiles, int fileSize) throws IOException { + + dataList = new ArrayList<>(numOfFiles); + file = File.createTempFile("zip-sample", ""); + + try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file))) { + + for (int idx=0; idx<=numOfFiles; idx++) { + + byte[] data = createRandomStringInByte(fileSize); + dataList.add(new String(data, DEFAULT_ENCODING)); + + ZipEntry entry = new ZipEntry(String.format(ENTRY_NAME_PATTERN, idx)); + zos.putNextEntry(entry); + zos.write(data); + zos.closeEntry(); + } + } + } + + public static byte[] createRandomStringInByte(int size) { + Random random = new Random(); + byte[] data = new byte[size]; + for (int n = 0; n < data.length; n++) { + char randomChar; + int choice = random.nextInt(2); // 0 for uppercase, 1 for lowercase + if (choice == 0) { + randomChar = (char) ('A' + random.nextInt(26)); // 'A' to 'Z' + } else { + randomChar = (char) ('a' + random.nextInt(26)); // 'a' to 'z' + } + data[n] = (byte) randomChar; + } + return data; + } + + public File getFile() { + return file; + } + + public List getDataList() { + return dataList; + } + + public static String getString(InputStream inputStream) throws IOException { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + IOUtils.copy(inputStream, byteArrayOutputStream); + return byteArrayOutputStream.toString(DEFAULT_ENCODING); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-io-5/src/test/java/com/baeldung/zip/ZipUnitTest.java b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/zip/ZipUnitTest.java new file mode 100644 index 0000000000..1d4d76dc41 --- /dev/null +++ b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/zip/ZipUnitTest.java @@ -0,0 +1,83 @@ +package com.baeldung.zip; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.*; +import java.util.*; +import java.util.zip.*; + +import org.junit.*; + +public class ZipUnitTest { + + private static File compressedFile; + private static List dataList = new ArrayList<>(); + + @BeforeClass + public static void prepareData() throws IOException { + ZipSampleFileStore sampleFileStore = new ZipSampleFileStore(ZipBenchmark.NUM_OF_FILES, ZipBenchmark.DATA_SIZE); + compressedFile = sampleFileStore.getFile(); + dataList = sampleFileStore.getDataList(); + } + + @Test + public void whenCreateZipFile_thenCompressedSizeShouldBeLessThanOriginal() throws IOException { + byte[] data = ZipSampleFileStore.createRandomStringInByte(10240); + File file = File.createTempFile("zip-temp", ""); + + try ( + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); + ZipOutputStream zos = new ZipOutputStream(bos) + ) { + ZipEntry zipEntry = new ZipEntry("zip-entry.txt"); + zos.putNextEntry(zipEntry); + zos.write(data); + zos.closeEntry(); + + assertThat(file.length()).isLessThan(data.length); + } + finally { + file.delete(); + } + } + + @Test + public void whenReadAllEntriesViaZipFile_thenDataIsEqualtoTheSource() throws IOException { + + try (ZipFile zipFile = new ZipFile(compressedFile)) { + Enumeration entries = zipFile.entries(); + List entryList = Collections.list(entries); + + for (int idx=0; idx Date: Mon, 30 Oct 2023 11:05:16 +0530 Subject: [PATCH 71/91] Corrected the name of a constant. --- .../java/com/baeldung/langchain/ChainWithDocumentLiveTest.java | 2 +- .../java/com/baeldung/langchain/ChatWithDocumentLiveTest.java | 2 +- .../java/com/baeldung/langchain/ChatWithMemoryLiveTest.java | 2 +- .../src/test/java/com/baeldung/langchain/Constants.java | 2 +- .../java/com/baeldung/langchain/PromptTemplatesLiveTest.java | 2 +- .../java/com/baeldung/langchain/ServiceWithToolsLiveTest.java | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java index eec7da99fd..39746ce810 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChainWithDocumentLiveTest.java @@ -45,7 +45,7 @@ public class ChainWithDocumentLiveTest { ingestor.ingest(document); ChatLanguageModel chatModel = OpenAiChatModel.builder() - .apiKey(Constants.OPEN_AI_KEY) + .apiKey(Constants.OPENAI_API_KEY) .timeout(ofSeconds(60)) .build(); diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java index cbbcc7dd23..41540f4888 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithDocumentLiveTest.java @@ -68,7 +68,7 @@ public class ChatWithDocumentLiveTest { Prompt prompt = promptTemplate.apply(variables); ChatLanguageModel chatModel = OpenAiChatModel.builder() - .apiKey(Constants.OPEN_AI_KEY) + .apiKey(Constants.OPENAI_API_KEY) .timeout(ofSeconds(60)) .build(); AiMessage aiMessage = chatModel.generate(prompt.toUserMessage()) diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java index 7a67c0be0e..3d265d3f3f 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ChatWithMemoryLiveTest.java @@ -22,7 +22,7 @@ public class ChatWithMemoryLiveTest { @Test public void givenMemory_whenPrompted_thenValidResponse() { - ChatLanguageModel model = OpenAiChatModel.withApiKey(Constants.OPEN_AI_KEY); + ChatLanguageModel model = OpenAiChatModel.withApiKey(Constants.OPENAI_API_KEY); ChatMemory chatMemory = TokenWindowChatMemory.withMaxTokens(300, new OpenAiTokenizer(GPT_3_5_TURBO)); chatMemory.add(userMessage("Hello, my name is Kumar")); diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java b/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java index b468b3a065..380415bf9c 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/Constants.java @@ -7,6 +7,6 @@ public class Constants { * registering for free at (https://platform.openai.com/signup) and then by navigating * to "Create new secret key" page at (https://platform.openai.com/account/api-keys). */ - public static String OPEN_AI_KEY = "demo"; //""; + public static String OPENAI_API_KEY = ""; } diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java index b05727f15f..cd2ea642ed 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/PromptTemplatesLiveTest.java @@ -28,7 +28,7 @@ public class PromptTemplatesLiveTest { Prompt prompt = promptTemplate.apply(variables); ChatLanguageModel model = OpenAiChatModel.builder() - .apiKey(Constants.OPEN_AI_KEY) + .apiKey(Constants.OPENAI_API_KEY) .modelName(GPT_3_5_TURBO) .temperature(0.3) .build(); diff --git a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java index 1df08e6d35..7ebfcba4df 100644 --- a/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java +++ b/libraries-llms/src/test/java/com/baeldung/langchain/ServiceWithToolsLiveTest.java @@ -34,7 +34,7 @@ public class ServiceWithToolsLiveTest { @Test public void givenServiceWithTools_whenPrompted_thenValidResponse() { Assistant assistant = AiServices.builder(Assistant.class) - .chatLanguageModel(OpenAiChatModel.withApiKey(Constants.OPEN_AI_KEY)) + .chatLanguageModel(OpenAiChatModel.withApiKey(Constants.OPENAI_API_KEY)) .tools(new Calculator()) .chatMemory(MessageWindowChatMemory.withMaxMessages(10)) .build(); From dfd9baf8e0baced4172d6f55a27bb16ceb7ac57a Mon Sep 17 00:00:00 2001 From: anujgaud <146576725+anujgaud@users.noreply.github.com> Date: Mon, 30 Oct 2023 13:50:16 +0530 Subject: [PATCH 72/91] Formatted UnicodeLetterChecker.java --- .../main/java/com/baeldung/unicode/UnicodeLetterChecker.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/unicode/UnicodeLetterChecker.java b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/unicode/UnicodeLetterChecker.java index df561c88ea..8ac8671586 100644 --- a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/unicode/UnicodeLetterChecker.java +++ b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/unicode/UnicodeLetterChecker.java @@ -13,15 +13,18 @@ public class UnicodeLetterChecker { } return true; } + public boolean regexCheck(String input) { Pattern pattern = Pattern.compile("^\\p{L}+$"); Matcher matcher = pattern.matcher(input); return matcher.matches(); } + public boolean isAlphaCheck(String input) { return StringUtils.isAlpha(input); } - public boolean StreamsCheck(String input){ + + public boolean StreamsCheck(String input) { return input.codePoints().allMatch(Character::isLetter); } } From de7dadabef623904f0a8687aaab75d2cfc94d6cc Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Mon, 30 Oct 2023 17:23:12 +0100 Subject: [PATCH 73/91] BAEL-7108: Comparing Arrays Using compare() Method in Java (#14975) --- .../pom.xml | 4 +++ .../arraycompare/ArraysCompareUnitTest.java | 29 +++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ArraysCompareUnitTest.java diff --git a/core-java-modules/core-java-arrays-operations-advanced/pom.xml b/core-java-modules/core-java-arrays-operations-advanced/pom.xml index cbcd6ae440..52787cc0c9 100644 --- a/core-java-modules/core-java-arrays-operations-advanced/pom.xml +++ b/core-java-modules/core-java-arrays-operations-advanced/pom.xml @@ -57,5 +57,9 @@ + + + 11 + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ArraysCompareUnitTest.java b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ArraysCompareUnitTest.java new file mode 100644 index 0000000000..828560d71c --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-advanced/src/test/java/com/baeldung/arraycompare/ArraysCompareUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.arraycompare; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; + +import org.junit.jupiter.api.Test; + +class ArraysCompareUnitTest { + + @Test + void givenSameContents_whenCompare_thenCorrect() { + String[] array1 = new String[] { "A", "B", "C" }; + String[] array2 = new String[] { "A", "B", "C" }; + + assertThat(Arrays.compare(array1, array2)).isEqualTo(0); + } + + @Test + void givenDifferentContents_whenCompare_thenDifferent() { + String[] array1 = new String[] { "A", "B", "C" }; + String[] array2 = new String[] { "A", "C", "B", "D" }; + + assertThat(Arrays.compare(array1, array2)).isLessThan(0); + assertThat(Arrays.compare(array2, array1)).isGreaterThan(0); + assertThat(Arrays.compare(array1, null)).isGreaterThan(0); + } + +} From 49929794b8db2ca20239b2dea47b07a3573a468f Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Mon, 30 Oct 2023 17:42:44 +0100 Subject: [PATCH 74/91] BAEL-7111: Get First Date of Current Month in Java (#15023) --- .../FirstDayOfMonthUnitTest.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/firstdaymonth/FirstDayOfMonthUnitTest.java diff --git a/core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/firstdaymonth/FirstDayOfMonthUnitTest.java b/core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/firstdaymonth/FirstDayOfMonthUnitTest.java new file mode 100644 index 0000000000..9edc3e4a8d --- /dev/null +++ b/core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/firstdaymonth/FirstDayOfMonthUnitTest.java @@ -0,0 +1,61 @@ +package com.baeldung.firstdaymonth; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.LocalDate; +import java.time.YearMonth; +import java.time.temporal.TemporalAdjusters; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import org.junit.jupiter.api.Test; + +public class FirstDayOfMonthUnitTest { + + @Test + void givenMonth_whenUsingCalendar_thenReturnFirstDay() { + Date currentDate = new GregorianCalendar(2023, Calendar.NOVEMBER, 23).getTime(); + Date expectedDate = new GregorianCalendar(2023, Calendar.NOVEMBER, 1).getTime(); + + Calendar cal = Calendar.getInstance(); + cal.setTime(currentDate); + cal.set(Calendar.DAY_OF_MONTH, 1); + + assertEquals(expectedDate, cal.getTime()); + } + + @Test + void givenMonth_whenUsingLocalDate_thenReturnFirstDay() { + LocalDate currentDate = LocalDate.of(2023, 9, 6); + LocalDate expectedDate = LocalDate.of(2023, 9, 1); + + assertEquals(expectedDate, currentDate.withDayOfMonth(1)); + } + + @Test + void givenMonth_whenUsingTemporalAdjusters_thenReturnFirstDay() { + LocalDate currentDate = LocalDate.of(2023, 7, 19); + LocalDate expectedDate = LocalDate.of(2023, 7, 1); + + assertEquals(expectedDate, currentDate.with(TemporalAdjusters.firstDayOfMonth())); + } + + @Test + void givenMonth_whenUsingYearMonth_thenReturnFirstDay() { + YearMonth currentDate = YearMonth.of(2023, 4); + LocalDate expectedDate = LocalDate.of(2023, 4, 1); + + assertEquals(expectedDate, currentDate.atDay(1)); + } + + @Test + void givenMonth_whenUsingJodaTime_thenReturnFirstDay() { + org.joda.time.LocalDate currentDate = org.joda.time.LocalDate.parse("2023-5-10"); + org.joda.time.LocalDate expectedDate = org.joda.time.LocalDate.parse("2023-5-1"); + + assertEquals(expectedDate, currentDate.dayOfMonth() + .withMinimumValue()); + } + +} From 7343754f159864c44ab65c9f187d876d4758a1cd Mon Sep 17 00:00:00 2001 From: Mikhail Polivakha <68962645+Mikhail2048@users.noreply.github.com> Date: Mon, 30 Oct 2023 20:20:48 +0300 Subject: [PATCH 75/91] BAEL-7139 implemented (#15082) --- spring-boot-modules/spring-boot-3-2/pom.xml | 34 ++++++++- .../ConditionalOnThreadingUnitTest.java | 70 +++++++++++++++++++ 2 files changed, 101 insertions(+), 3 deletions(-) create mode 100644 spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/conditionalonthreading/ConditionalOnThreadingUnitTest.java diff --git a/spring-boot-modules/spring-boot-3-2/pom.xml b/spring-boot-modules/spring-boot-3-2/pom.xml index 9e73d8ea32..276659c609 100644 --- a/spring-boot-modules/spring-boot-3-2/pom.xml +++ b/spring-boot-modules/spring-boot-3-2/pom.xml @@ -15,6 +15,14 @@ ../../parent-boot-3 + + + repository.spring.release + Spring GA Repository + https://repo.spring.io/milestone + + + org.springframework.boot @@ -94,6 +102,17 @@ org.springframework.boot spring-boot-starter-test + 3.2.0-M2 + + + org.junit.jupiter + junit-jupiter + 5.10.0 + + + org.junit.jupiter + junit-jupiter-api + 5.10.0 org.postgresql @@ -175,6 +194,18 @@ + + + + org.springframework.boot + spring-boot-dependencies + 3.2.0-M2 + import + pom + + + + @@ -244,9 +275,6 @@ org.apache.maven.plugins maven-compiler-plugin - - --enable-preview - diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/conditionalonthreading/ConditionalOnThreadingUnitTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/conditionalonthreading/ConditionalOnThreadingUnitTest.java new file mode 100644 index 0000000000..ed65769954 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/conditionalonthreading/ConditionalOnThreadingUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.conditionalonthreading; + +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.condition.JRE; +import org.springframework.boot.autoconfigure.condition.ConditionalOnThreading; +import org.springframework.boot.autoconfigure.thread.Threading; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +public class ConditionalOnThreadingUnitTest { + + ApplicationContextRunner applicationContextRunner = new ApplicationContextRunner() + .withUserConfiguration(CurrentConfig.class); + + @Configuration + static class CurrentConfig { + + @Bean + @ConditionalOnThreading(Threading.PLATFORM) + ThreadingType platformBean() { + return ThreadingType.PLATFORM; + } + + @Bean + @ConditionalOnThreading(Threading.VIRTUAL) + ThreadingType virtualBean() { + return ThreadingType.VIRTUAL; + } + } + + enum ThreadingType { + PLATFORM, VIRTUAL + } + + @Test + @EnabledForJreRange(max = JRE.JAVA_20) + public void whenJava20AndVirtualThreadsEnabled_thenThreadingIsPlatform() { + applicationContextRunner.withPropertyValues("spring.threads.virtual.enabled=true").run(context -> { + Assertions.assertThat(context.getBean(ThreadingType.class)).isEqualTo(ThreadingType.PLATFORM); + }); + } + + @Test + @EnabledForJreRange(max = JRE.JAVA_20) + public void whenJava20AndVirtualThreadsDisabled_thenThreadingIsPlatform() { + applicationContextRunner.withPropertyValues("spring.threads.virtual.enabled=false").run(context -> { + Assertions.assertThat(context.getBean(ThreadingType.class)).isEqualTo(ThreadingType.PLATFORM); + }); + } + + @Test + @EnabledForJreRange(min = JRE.JAVA_21) + public void whenJava21AndVirtualThreadsEnabled_thenThreadingIsVirtual() { + applicationContextRunner.withPropertyValues("spring.threads.virtual.enabled=true").run(context -> { + Assertions.assertThat(context.getBean(ThreadingType.class)).isEqualTo(ThreadingType.VIRTUAL); + }); + } + + @Test + @EnabledForJreRange(min = JRE.JAVA_21) + public void whenJava21AndVirtualThreadsDisabled_thenThreadingIsPlatform() { + applicationContextRunner.withPropertyValues("spring.threads.virtual.enabled=false").run(context -> { + Assertions.assertThat(context.getBean(ThreadingType.class)).isEqualTo(ThreadingType.PLATFORM); + }); + } + +} \ No newline at end of file From d5c1b161bb5331472cf67c33cf46c0b7aeec8d45 Mon Sep 17 00:00:00 2001 From: kasramp Date: Mon, 30 Oct 2023 21:42:36 +0100 Subject: [PATCH 76/91] JAVA-25491 better variable naming AVL Tree insert method --- .../main/java/com/baeldung/avltree/AVLTree.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/data-structures/src/main/java/com/baeldung/avltree/AVLTree.java b/data-structures/src/main/java/com/baeldung/avltree/AVLTree.java index ca0cfce7b4..117a35e028 100644 --- a/data-structures/src/main/java/com/baeldung/avltree/AVLTree.java +++ b/data-structures/src/main/java/com/baeldung/avltree/AVLTree.java @@ -42,17 +42,17 @@ public class AVLTree { return root == null ? -1 : root.height; } - private Node insert(Node node, int key) { - if (node == null) { + private Node insert(Node root, int key) { + if (root == null) { return new Node(key); - } else if (node.key > key) { - node.left = insert(node.left, key); - } else if (node.key < key) { - node.right = insert(node.right, key); + } else if (root.key > key) { + root.left = insert(root.left, key); + } else if (root.key < key) { + root.right = insert(root.right, key); } else { throw new RuntimeException("duplicate Key!"); } - return rebalance(node); + return rebalance(root); } private Node delete(Node node, int key) { From 6e25eb35cc11740b71c1d72419de85fa5420fb5a Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Tue, 31 Oct 2023 05:06:00 +0100 Subject: [PATCH 77/91] Add Spring StringUtils class (#15090) * Add Spring StringUtils class * Add Spring StringUtils class --- .../core-java-string-operations-2/pom.xml | 6 ++++++ .../emptystrings/EmptyStringsUnitTest.java | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml index c6debc4f71..902e8f09b4 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/pom.xml @@ -54,6 +54,11 @@ commons-codec ${commons-codec.version} + + org.springframework + spring-core + ${spring-core.version} + @@ -95,6 +100,7 @@ 3.0.0 2.2.6 1.14 + 5.3.0 \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java index d772c38341..9652e0e770 100644 --- a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java +++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/emptystrings/EmptyStringsUnitTest.java @@ -3,6 +3,7 @@ package com.baeldung.emptystrings; import com.google.common.base.Strings; import org.apache.commons.lang3.StringUtils; import org.junit.Test; +import org.springframework.util.ObjectUtils; import javax.validation.ConstraintViolation; import javax.validation.Validation; @@ -109,6 +110,24 @@ public class EmptyStringsUnitTest { assertFalse(Strings.isNullOrEmpty(blankString)); } + /* + * Spring Core ObjectUtils + */ + @Test + public void givenSomeEmptyString_thenObjectUtilsIsEmptyReturnsTrue() { + assertTrue(ObjectUtils.isEmpty(emptyString)); + } + + @Test + public void givenSomeNonEmptyString_thenObjectUtilsIsEmptyReturnsFalse() { + assertFalse(ObjectUtils.isEmpty(nonEmptyString)); + } + + @Test + public void givenSomeBlankString_thenObjectUtilsIsEmptyReturnsFalse() { + assertFalse(ObjectUtils.isEmpty(blankString)); + } + /* * Bean Validation */ From 036369c792924306bb7f08caa812863cad14920c Mon Sep 17 00:00:00 2001 From: Eugene Kovko <37694937+eukovko@users.noreply.github.com> Date: Tue, 31 Oct 2023 16:21:05 +0100 Subject: [PATCH 78/91] BAEL-6705: Fixed typo (#15015) --- .../baeldung/alphanumeric/AlphanumericPerformanceBenchmark.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-regex-2/src/main/java/com/baeldung/alphanumeric/AlphanumericPerformanceBenchmark.java b/core-java-modules/core-java-regex-2/src/main/java/com/baeldung/alphanumeric/AlphanumericPerformanceBenchmark.java index 4b2ecc4c4d..0525153ed9 100644 --- a/core-java-modules/core-java-regex-2/src/main/java/com/baeldung/alphanumeric/AlphanumericPerformanceBenchmark.java +++ b/core-java-modules/core-java-regex-2/src/main/java/com/baeldung/alphanumeric/AlphanumericPerformanceBenchmark.java @@ -85,7 +85,7 @@ public class AlphanumericPerformanceBenchmark { public boolean isAlphanumeric(final int codePoint) { return (codePoint >= 65 && codePoint <= 90) || - (codePoint >= 97 && codePoint <= 172) || + (codePoint >= 97 && codePoint <= 122) || (codePoint >= 48 && codePoint <= 57); } } From 0422349dabb4fd6c1e4b53c4c5d60834fbf827f2 Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Tue, 31 Oct 2023 18:07:06 +0000 Subject: [PATCH 79/91] BAEL-7088: Code for Connect 4 Article (#15099) * BAEL-7088: Code for Connect 4 Article * Renamed test --- .../algorithms/connect4/GameBoard.java | 129 ++++++++++++++++++ .../algorithms/connect4/GameUnitTest.java | 40 ++++++ .../baeldung/algorithms/connect4/Piece.java | 6 + 3 files changed, 175 insertions(+) create mode 100644 algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameBoard.java create mode 100644 algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameUnitTest.java create mode 100644 algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/Piece.java diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameBoard.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameBoard.java new file mode 100644 index 0000000000..b10bd95a19 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameBoard.java @@ -0,0 +1,129 @@ +package com.baeldung.algorithms.connect4; + +import java.util.ArrayList; +import java.util.List; + +public class GameBoard { + private final List> columns; + + private final int rows; + + public GameBoard(int columns, int rows) { + this.rows = rows; + this.columns = new ArrayList<>(); + + for (int i = 0; i < columns; ++i) { + this.columns.add(new ArrayList<>()); + } + } + + public int getRows() { + return rows; + } + + public int getColumns() { + return columns.size(); + } + + public Piece getCell(int x, int y) { + assert(x >= 0 && x < getColumns()); + assert(y >= 0 && y < getRows()); + + List column = columns.get(x); + + if (column.size() > y) { + return column.get(y); + } else { + return null; + } + } + + public boolean move(int x, Piece player) { + assert(x >= 0 && x < getColumns()); + + List column = columns.get(x); + + if (column.size() >= this.rows) { + throw new IllegalArgumentException("That column is full"); + } + + column.add(player); + + return checkWin(x, column.size() - 1, player); + } + + private boolean checkWin(int x, int y, Piece player) { + // Vertical line + if (checkLine(x, y, 0, -1, player)) { + return true; + } + + for (int offset = 0; offset < 4; ++offset) { + // Horizontal line + if (checkLine(x - 3 + offset, y, 1, 0, player)) { + return true; + } + + // Leading diagonal + if (checkLine(x - 3 + offset, y + 3 - offset, 1, -1, player)) { + return true; + } + + // Trailing diagonal + if (checkLine(x - 3 + offset, y - 3 + offset, 1, 1, player)) { + return true; + } + } + + return false; + } + + private boolean checkLine(int x1, int y1, int xDiff, int yDiff, Piece player) { + for (int i = 0; i < 4; ++i) { + int x = x1 + (xDiff * i); + int y = y1 + (yDiff * i); + + if (x < 0 || x > columns.size() - 1) { + return false; + } + + if (y < 0 || y > rows - 1) { + return false; + } + + if (player != getCell(x, y)) { + return false; + } + } + + return true; + } + + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + + for (int y = getRows() - 1; y >= 0; --y) { + for (int x = 0; x < getColumns(); ++x) { + Piece piece = getCell(x, y); + + result.append("|"); + if (piece == null) { + result.append(" "); + } else if (piece == Piece.PLAYER_1) { + result.append("X"); + } else if (piece == Piece.PLAYER_2) { + result.append("O"); + } + } + + result.append("|\n"); + for (int i = 0; i < getColumns(); ++i) { + result.append("+-"); + } + result.append("+\n"); + } + + return result.toString(); + } +} diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameUnitTest.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameUnitTest.java new file mode 100644 index 0000000000..f340644950 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/GameUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.algorithms.connect4; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class GameUnitTest { + @Test + public void blankGame() { + GameBoard gameBoard = new GameBoard(8, 6); + + System.out.println(gameBoard); + } + + @Test + public void playedGame() { + GameBoard gameBoard = new GameBoard(8, 6); + + assertFalse(gameBoard.move(3, Piece.PLAYER_1)); + assertFalse(gameBoard.move(2, Piece.PLAYER_2)); + + assertFalse(gameBoard.move(4, Piece.PLAYER_1)); + assertFalse(gameBoard.move(3, Piece.PLAYER_2)); + + assertFalse(gameBoard.move(5, Piece.PLAYER_1)); + assertFalse(gameBoard.move(6, Piece.PLAYER_2)); + + assertFalse(gameBoard.move(5, Piece.PLAYER_1)); + assertFalse(gameBoard.move(4, Piece.PLAYER_2)); + + assertFalse(gameBoard.move(5, Piece.PLAYER_1)); + assertFalse(gameBoard.move(5, Piece.PLAYER_2)); + + assertFalse(gameBoard.move(6, Piece.PLAYER_1)); + assertTrue(gameBoard.move(4, Piece.PLAYER_2)); + + System.out.println(gameBoard); + } +} diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/Piece.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/Piece.java new file mode 100644 index 0000000000..5a8724c09b --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/connect4/Piece.java @@ -0,0 +1,6 @@ +package com.baeldung.algorithms.connect4; + +public enum Piece { + PLAYER_1, + PLAYER_2 +} From 2f9acfe1d1a3e7eb69b628e6888095328de916fc Mon Sep 17 00:00:00 2001 From: Manfred <77407079+manfred106@users.noreply.github.com> Date: Tue, 31 Oct 2023 23:41:15 +0000 Subject: [PATCH 80/91] BAEL-7119: Localized Validation Messages in REST (#14996) * BAEL-7119: Localized Validation Messages in REST * BAEL-7119: Localized Validation Messages in REST - Remove unused imports --- spring-boot-modules/spring-boot-mvc/pom.xml | 4 + .../RestValidationApplication.java | 15 ++++ .../restvalidation/config/MessageConfig.java | 38 ++++++++++ ...rsiveLocaleContextMessageInterpolator.java | 36 +++++++++ .../response/InputFieldError.java | 12 +++ .../response/UpdateUserResponse.java | 17 +++++ .../restvalidation/service1/User.java | 15 ++++ .../restvalidation/service1/UserService1.java | 36 +++++++++ .../restvalidation/service2/User.java | 15 ++++ .../restvalidation/service2/UserService2.java | 40 ++++++++++ .../service3/FieldNotEmpty.java | 32 ++++++++ .../service3/FieldNotEmptyValidator.java | 16 ++++ .../restvalidation/service3/User.java | 13 ++++ .../restvalidation/service3/UserService3.java | 40 ++++++++++ .../CustomValidationMessages.properties | 3 + .../CustomValidationMessages_zh.properties | 3 + .../resources/ValidationMessages.properties | 1 + .../ValidationMessages_zh.properties | 1 + .../service1/UserService1IntegrationTest.java | 75 +++++++++++++++++++ .../service2/UserService2IntegrationTest.java | 75 +++++++++++++++++++ .../service3/UserService3IntegrationTest.java | 75 +++++++++++++++++++ 21 files changed, 562 insertions(+) create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/RestValidationApplication.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/config/MessageConfig.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/config/RecursiveLocaleContextMessageInterpolator.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/response/InputFieldError.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/response/UpdateUserResponse.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service1/User.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service1/UserService1.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service2/User.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service2/UserService2.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/FieldNotEmpty.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/FieldNotEmptyValidator.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/User.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/UserService3.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/resources/CustomValidationMessages.properties create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/resources/CustomValidationMessages_zh.properties create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/resources/ValidationMessages.properties create mode 100644 spring-boot-modules/spring-boot-mvc/src/main/resources/ValidationMessages_zh.properties create mode 100644 spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/restvalidation/service1/UserService1IntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/restvalidation/service2/UserService2IntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/restvalidation/service3/UserService3IntegrationTest.java diff --git a/spring-boot-modules/spring-boot-mvc/pom.xml b/spring-boot-modules/spring-boot-mvc/pom.xml index 369bcf799b..a251c5049b 100644 --- a/spring-boot-modules/spring-boot-mvc/pom.xml +++ b/spring-boot-modules/spring-boot-mvc/pom.xml @@ -91,6 +91,10 @@ aspectjweaver ${aspectjweaver.version} + + org.projectlombok + lombok + diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/RestValidationApplication.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/RestValidationApplication.java new file mode 100644 index 0000000000..b335aecac2 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/RestValidationApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.restvalidation; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +@SpringBootApplication +@ComponentScan(basePackages = { "com.baeldung.restvalidation" }) +public class RestValidationApplication { + + public static void main(String[] args) { + SpringApplication.run(RestValidationApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/config/MessageConfig.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/config/MessageConfig.java new file mode 100644 index 0000000000..e37e2c9d78 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/config/MessageConfig.java @@ -0,0 +1,38 @@ +package com.baeldung.restvalidation.config; + +import javax.validation.MessageInterpolator; + +import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator; +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ReloadableResourceBundleMessageSource; +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; +import org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator; + +@Configuration +public class MessageConfig { + + @Bean + public MessageSource messageSource() { + ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); + messageSource.setBasename("classpath:CustomValidationMessages"); + messageSource.setDefaultEncoding("UTF-8"); + return messageSource; + } + + @Bean + public MessageInterpolator getMessageInterpolator(MessageSource messageSource) { + MessageSourceResourceBundleLocator resourceBundleLocator = new MessageSourceResourceBundleLocator(messageSource); + ResourceBundleMessageInterpolator messageInterpolator = new ResourceBundleMessageInterpolator(resourceBundleLocator); + return new RecursiveLocaleContextMessageInterpolator(messageInterpolator); + } + + @Bean + public LocalValidatorFactoryBean getValidator(MessageInterpolator messageInterpolator) { + LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean(); + bean.setMessageInterpolator(messageInterpolator); + return bean; + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/config/RecursiveLocaleContextMessageInterpolator.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/config/RecursiveLocaleContextMessageInterpolator.java new file mode 100644 index 0000000000..003a3d79b0 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/config/RecursiveLocaleContextMessageInterpolator.java @@ -0,0 +1,36 @@ +package com.baeldung.restvalidation.config; + +import java.util.Locale; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.validation.MessageInterpolator; + +import org.hibernate.validator.messageinterpolation.AbstractMessageInterpolator; +import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator; + +public class RecursiveLocaleContextMessageInterpolator extends AbstractMessageInterpolator { + + private static final Pattern PATTERN_PLACEHOLDER = Pattern.compile("\\{([^}]+)\\}"); + + private final MessageInterpolator interpolator; + + public RecursiveLocaleContextMessageInterpolator(ResourceBundleMessageInterpolator interpolator) { + this.interpolator = interpolator; + } + + @Override + public String interpolate(MessageInterpolator.Context context, Locale locale, String message) { + int level = 0; + while (containsPlaceholder(message) && (level++ < 2)) { + message = this.interpolator.interpolate(message, context, locale); + } + return message; + } + + private boolean containsPlaceholder(String code) { + Matcher matcher = PATTERN_PLACEHOLDER.matcher(code); + return matcher.find(); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/response/InputFieldError.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/response/InputFieldError.java new file mode 100644 index 0000000000..06bd764d97 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/response/InputFieldError.java @@ -0,0 +1,12 @@ +package com.baeldung.restvalidation.response; + +import lombok.*; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class InputFieldError { + private String field; + private String message; + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/response/UpdateUserResponse.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/response/UpdateUserResponse.java new file mode 100644 index 0000000000..7eb400cd2c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/response/UpdateUserResponse.java @@ -0,0 +1,17 @@ +package com.baeldung.restvalidation.response; + +import com.fasterxml.jackson.annotation.JsonInclude; + +import java.util.List; + +import lombok.*; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UpdateUserResponse { + + private List fieldErrors; + +} diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service1/User.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service1/User.java new file mode 100644 index 0000000000..f9a7d1a9b5 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service1/User.java @@ -0,0 +1,15 @@ +package com.baeldung.restvalidation.service1; + +import javax.validation.constraints.NotEmpty; + +import lombok.*; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class User { + + @NotEmpty + private String email; + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service1/UserService1.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service1/UserService1.java new file mode 100644 index 0000000000..790b5031e6 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service1/UserService1.java @@ -0,0 +1,36 @@ +package com.baeldung.restvalidation.service1; + +import org.springframework.http.*; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.*; + +import java.util.List; +import java.util.stream.Collectors; + +import javax.validation.Valid; + +import com.baeldung.restvalidation.response.InputFieldError; +import com.baeldung.restvalidation.response.UpdateUserResponse; + +@RestController +public class UserService1 { + + @PutMapping(value = "/user1", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity updateUser(@RequestBody @Valid User user, + BindingResult bindingResult) { + if (bindingResult.hasFieldErrors()) { + + List fieldErrorList = bindingResult.getFieldErrors().stream() + .map(error -> new InputFieldError(error.getField(), error.getDefaultMessage())) + .collect(Collectors.toList()); + + UpdateUserResponse updateResponse = new UpdateUserResponse(fieldErrorList); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(updateResponse); + } + else { + // Update logic... + return ResponseEntity.status(HttpStatus.OK).build(); + } + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service2/User.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service2/User.java new file mode 100644 index 0000000000..a2e567766c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service2/User.java @@ -0,0 +1,15 @@ +package com.baeldung.restvalidation.service2; + +import javax.validation.constraints.NotEmpty; + +import lombok.*; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class User { + + @NotEmpty(message = "{validation.email.notEmpty}") + private String email; + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service2/UserService2.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service2/UserService2.java new file mode 100644 index 0000000000..4593a2b1bd --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service2/UserService2.java @@ -0,0 +1,40 @@ +package com.baeldung.restvalidation.service2; + +import java.util.List; +import java.util.stream.Collectors; + +import javax.validation.Valid; + +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.restvalidation.response.InputFieldError; +import com.baeldung.restvalidation.response.UpdateUserResponse; + +@RestController +public class UserService2 { + + @PutMapping(value = "/user2", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity updateUser(@RequestBody @Valid User user, + BindingResult bindingResult) { + if (bindingResult.hasFieldErrors()) { + + List fieldErrorList = bindingResult.getFieldErrors().stream() + .map(error -> new InputFieldError(error.getField(), error.getDefaultMessage())) + .collect(Collectors.toList()); + + UpdateUserResponse updateResponse = new UpdateUserResponse(fieldErrorList); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(updateResponse); + } + else { + // Update logic... + return ResponseEntity.status(HttpStatus.OK).build(); + } + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/FieldNotEmpty.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/FieldNotEmpty.java new file mode 100644 index 0000000000..93c7052d5b --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/FieldNotEmpty.java @@ -0,0 +1,32 @@ +package com.baeldung.restvalidation.service3; + +import static java.lang.annotation.ElementType.ANNOTATION_TYPE; +import static java.lang.annotation.ElementType.CONSTRUCTOR; +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.ElementType.PARAMETER; +import static java.lang.annotation.ElementType.TYPE_USE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import javax.validation.Constraint; +import javax.validation.Payload; + +@Documented +@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) +@Retention(RUNTIME) +@Constraint(validatedBy = { FieldNotEmptyValidator.class }) +public @interface FieldNotEmpty { + + String message() default "{validation.notEmpty}"; + + String field() default "Field"; + + Class[] groups() default {}; + + Class[] payload() default {}; + +} diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/FieldNotEmptyValidator.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/FieldNotEmptyValidator.java new file mode 100644 index 0000000000..356efc590b --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/FieldNotEmptyValidator.java @@ -0,0 +1,16 @@ +package com.baeldung.restvalidation.service3; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; + +public class FieldNotEmptyValidator implements ConstraintValidator { + + private String message; + private String field; + + @Override + public boolean isValid(Object value, ConstraintValidatorContext context) { + return (value != null && !value.toString().trim().isEmpty()); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/User.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/User.java new file mode 100644 index 0000000000..97b38feba4 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/User.java @@ -0,0 +1,13 @@ +package com.baeldung.restvalidation.service3; + +import lombok.*; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class User { + + @FieldNotEmpty(message = "{validation.notEmpty}", field = "{field.personalEmail}") + private String email; + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/UserService3.java b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/UserService3.java new file mode 100644 index 0000000000..e506b63d8e --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/java/com/baeldung/restvalidation/service3/UserService3.java @@ -0,0 +1,40 @@ +package com.baeldung.restvalidation.service3; + +import java.util.List; +import java.util.stream.Collectors; + +import javax.validation.Valid; + +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.BindingResult; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.restvalidation.response.InputFieldError; +import com.baeldung.restvalidation.response.UpdateUserResponse; + +@RestController +public class UserService3 { + + @PutMapping(value = "/user3", produces = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity updateUser(@RequestBody @Valid User user, + BindingResult bindingResult) { + if (bindingResult.hasFieldErrors()) { + + List fieldErrorList = bindingResult.getFieldErrors().stream() + .map(error -> new InputFieldError(error.getField(), error.getDefaultMessage())) + .collect(Collectors.toList()); + + UpdateUserResponse updateResponse = new UpdateUserResponse(fieldErrorList); + return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(updateResponse); + } + else { + // Update logic... + return ResponseEntity.status(HttpStatus.OK).build(); + } + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/CustomValidationMessages.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/CustomValidationMessages.properties new file mode 100644 index 0000000000..58cabc30c9 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/resources/CustomValidationMessages.properties @@ -0,0 +1,3 @@ +field.personalEmail=Personal Email +validation.notEmpty={field} cannot be empty +validation.email.notEmpty=Email cannot be empty \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/CustomValidationMessages_zh.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/CustomValidationMessages_zh.properties new file mode 100644 index 0000000000..b4fbe909bb --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/resources/CustomValidationMessages_zh.properties @@ -0,0 +1,3 @@ +field.personalEmail=個人電郵 +validation.notEmpty={field}不能是空白 +validation.email.notEmpty=電郵不能留空 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/ValidationMessages.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/ValidationMessages.properties new file mode 100644 index 0000000000..90d3c88a8f --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/resources/ValidationMessages.properties @@ -0,0 +1 @@ +javax.validation.constraints.NotEmpty.message=The field cannot be empty \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/main/resources/ValidationMessages_zh.properties b/spring-boot-modules/spring-boot-mvc/src/main/resources/ValidationMessages_zh.properties new file mode 100644 index 0000000000..04f415911c --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/main/resources/ValidationMessages_zh.properties @@ -0,0 +1 @@ +javax.validation.constraints.NotEmpty.message=本欄不能留空 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/restvalidation/service1/UserService1IntegrationTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/restvalidation/service1/UserService1IntegrationTest.java new file mode 100644 index 0000000000..969a6c17a6 --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/restvalidation/service1/UserService1IntegrationTest.java @@ -0,0 +1,75 @@ +package com.baeldung.restvalidation.service1; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Objects; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.*; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.restvalidation.RestValidationApplication; +import com.baeldung.restvalidation.response.InputFieldError; +import com.baeldung.restvalidation.response.UpdateUserResponse; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = RestValidationApplication.class) +class UserService1IntegrationTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + void whenUpdateValidEmail_thenReturnsOK() { + + // When + ResponseEntity responseEntity = updateUser(new User("test@email.com"), null); + + // Then + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + } + + @Test + void whenUpdateEmptyEmail_thenReturnsErrorMessageInEnglish() { + + // When + ResponseEntity responseEntity = updateUser(new User(""), null); + + // Then + InputFieldError error = responseEntity.getBody().getFieldErrors().get(0); + assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + assertEquals("The field cannot be empty", error.getMessage()); + } + + @Test + void whenUpdateEmptyEmailWithLanguageHeaderEqualsToZh_thenReturnsErrorMessageInChinese() { + + // When + ResponseEntity responseEntity = updateUser(new User(""), "zh-tw"); + + // Then + InputFieldError error = responseEntity.getBody().getFieldErrors().get(0); + assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + assertEquals("本欄不能留空", error.getMessage()); + } + + private ResponseEntity updateUser(User user, String language) { + + HttpHeaders headers = new HttpHeaders(); + if (Objects.nonNull(language)) { + headers.set(HttpHeaders.ACCEPT_LANGUAGE, language); + } + + return restTemplate.exchange( + "/user1", + HttpMethod.PUT, + new HttpEntity<>(user, headers), + UpdateUserResponse.class + ); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/restvalidation/service2/UserService2IntegrationTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/restvalidation/service2/UserService2IntegrationTest.java new file mode 100644 index 0000000000..3e92229d7b --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/restvalidation/service2/UserService2IntegrationTest.java @@ -0,0 +1,75 @@ +package com.baeldung.restvalidation.service2; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Objects; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.*; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.restvalidation.RestValidationApplication; +import com.baeldung.restvalidation.response.InputFieldError; +import com.baeldung.restvalidation.response.UpdateUserResponse; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = RestValidationApplication.class) +class UserService2IntegrationTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + void whenUpdateValidEmail_thenReturnsOK() { + + // When + ResponseEntity responseEntity = updateUser(new User("test@email.com"), null); + + // Then + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + } + + @Test + void whenUpdateEmptyEmail_thenReturnsErrorMessageInEnglish() { + + // When + ResponseEntity responseEntity = updateUser(new User(""), null); + + // Then + InputFieldError error = responseEntity.getBody().getFieldErrors().get(0); + assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + assertEquals("Email cannot be empty", error.getMessage()); + } + + @Test + void whenUpdateEmptyEmailWithLanguageHeaderEqualsToZh_thenReturnsErrorMessageInChinese() { + + // When + ResponseEntity responseEntity = updateUser(new User(""), "zh-tw"); + + // Then + InputFieldError error = responseEntity.getBody().getFieldErrors().get(0); + assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + assertEquals("電郵不能留空", error.getMessage()); + } + + private ResponseEntity updateUser(User user, String language) { + + HttpHeaders headers = new HttpHeaders(); + if (Objects.nonNull(language)) { + headers.set(HttpHeaders.ACCEPT_LANGUAGE, language); + } + + return restTemplate.exchange( + "/user2", + HttpMethod.PUT, + new HttpEntity<>(user, headers), + UpdateUserResponse.class + ); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/restvalidation/service3/UserService3IntegrationTest.java b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/restvalidation/service3/UserService3IntegrationTest.java new file mode 100644 index 0000000000..8bc4d460ea --- /dev/null +++ b/spring-boot-modules/spring-boot-mvc/src/test/java/com/baeldung/restvalidation/service3/UserService3IntegrationTest.java @@ -0,0 +1,75 @@ +package com.baeldung.restvalidation.service3; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Objects; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.*; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.restvalidation.RestValidationApplication; +import com.baeldung.restvalidation.response.InputFieldError; +import com.baeldung.restvalidation.response.UpdateUserResponse; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = RestValidationApplication.class) +class UserService3IntegrationTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Test + void whenUpdateValidEmail_thenReturnsOK() { + + // When + ResponseEntity responseEntity = updateUser(new User("test@email.com"), null); + + // Then + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + } + + @Test + void whenUpdateEmptyEmail_thenReturnsErrorMessageInEnglish() { + + // When + ResponseEntity responseEntity = updateUser(new User(""), null); + + // Then + InputFieldError error = responseEntity.getBody().getFieldErrors().get(0); + assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + assertEquals("Personal Email cannot be empty", error.getMessage()); + } + + @Test + void whenUpdateEmptyEmailWithLanguageHeaderEqualsToZh_thenReturnsErrorMessageInChinese() { + + // When + ResponseEntity responseEntity = updateUser(new User(""), "zh-tw"); + + // Then + InputFieldError error = responseEntity.getBody().getFieldErrors().get(0); + assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode()); + assertEquals("個人電郵不能是空白", error.getMessage()); + } + + private ResponseEntity updateUser(User user, String language) { + + HttpHeaders headers = new HttpHeaders(); + if (Objects.nonNull(language)) { + headers.set(HttpHeaders.ACCEPT_LANGUAGE, language); + } + + return restTemplate.exchange( + "/user3", + HttpMethod.PUT, + new HttpEntity<>(user, headers), + UpdateUserResponse.class + ); + } + +} \ No newline at end of file From b696d205f616f3a067baa451ea4dd9e846cd01f9 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Wed, 1 Nov 2023 13:00:50 +0200 Subject: [PATCH 81/91] [JAVA-26243] Upgraded spring-di-3 module to spring-boot 3 (#14997) --- spring-di-2/pom.xml | 12 +++------- .../com/baeldung/di/aspectj/PersonEntity.java | 6 ++--- .../FieldByNameInjectIntegrationTest.java | 4 ++-- .../inject/FieldInjectIntegrationTest.java | 2 +- .../FieldQualifierInjectIntegrationTest.java | 2 +- ...FieldResourceInjectionIntegrationTest.java | 2 +- ...hodByQualifierResourceIntegrationTest.java | 2 +- .../MethodByTypeResourceIntegrationTest.java | 2 +- ...ethodResourceInjectionIntegrationTest.java | 2 +- .../NamedResourceIntegrationTest.java | 2 +- ...ifierResourceInjectionIntegrationTest.java | 2 +- ...etterResourceInjectionIntegrationTest.java | 2 +- spring-di-3/pom.xml | 8 ++++--- .../DynamicAutowireIntegrationTest.java | 2 +- spring-di-4/pom.xml | 4 ++-- .../baeldung/sampleabstract/BallService.java | 2 +- spring-di/pom.xml | 22 ++++--------------- 17 files changed, 30 insertions(+), 48 deletions(-) diff --git a/spring-di-2/pom.xml b/spring-di-2/pom.xml index 69333c74f1..0bd6c41a8c 100644 --- a/spring-di-2/pom.xml +++ b/spring-di-2/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-spring-5 + parent-spring-6 0.0.1-SNAPSHOT - ../parent-spring-5 + ../parent-spring-6 @@ -46,11 +46,6 @@ org.springframework spring-aspects - - javax.inject - javax.inject - ${javax.inject.version} - org.springframework.boot spring-boot-starter-test @@ -84,9 +79,8 @@ - 2.6.1 + 3.1.2 1.14.0 - 1 2.17.1 diff --git a/spring-di-2/src/main/java/com/baeldung/di/aspectj/PersonEntity.java b/spring-di-2/src/main/java/com/baeldung/di/aspectj/PersonEntity.java index f087a97c7e..758a942227 100644 --- a/spring-di-2/src/main/java/com/baeldung/di/aspectj/PersonEntity.java +++ b/spring-di-2/src/main/java/com/baeldung/di/aspectj/PersonEntity.java @@ -3,9 +3,9 @@ package com.baeldung.di.aspectj; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Configurable; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Transient; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Transient; @Entity @Configurable(preConstruction = true) diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldByNameInjectIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldByNameInjectIntegrationTest.java index d1a75d73ea..f7ca089355 100644 --- a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldByNameInjectIntegrationTest.java +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldByNameInjectIntegrationTest.java @@ -3,8 +3,8 @@ package com.baeldung.wiring.configuration.inject; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import javax.inject.Inject; -import javax.inject.Named; +import jakarta.inject.Inject; +import jakarta.inject.Named; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldInjectIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldInjectIntegrationTest.java index 995f560701..c06205aee8 100644 --- a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldInjectIntegrationTest.java +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldInjectIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung.wiring.configuration.inject; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import javax.inject.Inject; +import jakarta.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldQualifierInjectIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldQualifierInjectIntegrationTest.java index 67fa2bf3d4..2a3e41f63f 100644 --- a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldQualifierInjectIntegrationTest.java +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/inject/FieldQualifierInjectIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung.wiring.configuration.inject; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import javax.inject.Inject; +import jakarta.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/FieldResourceInjectionIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/FieldResourceInjectionIntegrationTest.java index 938d557939..16430a0573 100644 --- a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/FieldResourceInjectionIntegrationTest.java +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/FieldResourceInjectionIntegrationTest.java @@ -5,7 +5,7 @@ import static org.junit.Assert.assertNotNull; import java.io.File; -import javax.annotation.Resource; +import jakarta.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByQualifierResourceIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByQualifierResourceIntegrationTest.java index f49bf70aba..1c1e3388b5 100644 --- a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByQualifierResourceIntegrationTest.java +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByQualifierResourceIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.baeldung.wiring.configuration.ApplicationContextTestResourceQualifier; -import javax.annotation.Resource; +import jakarta.annotation.Resource; import java.io.File; import static org.junit.Assert.assertEquals; diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByTypeResourceIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByTypeResourceIntegrationTest.java index aecd02a1d5..660610753f 100644 --- a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByTypeResourceIntegrationTest.java +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodByTypeResourceIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.baeldung.wiring.configuration.ApplicationContextTestResourceNameType; -import javax.annotation.Resource; +import jakarta.annotation.Resource; import java.io.File; import static org.junit.Assert.assertEquals; diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodResourceInjectionIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodResourceInjectionIntegrationTest.java index 4ef9368c28..0fcc2b1c50 100644 --- a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodResourceInjectionIntegrationTest.java +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/MethodResourceInjectionIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.baeldung.wiring.configuration.ApplicationContextTestResourceNameType; -import javax.annotation.Resource; +import jakarta.annotation.Resource; import java.io.File; import static org.junit.Assert.assertEquals; diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/NamedResourceIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/NamedResourceIntegrationTest.java index 4339194f63..5aed1ac7cb 100644 --- a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/NamedResourceIntegrationTest.java +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/NamedResourceIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.baeldung.wiring.configuration.ApplicationContextTestResourceNameType; -import javax.annotation.Resource; +import jakarta.annotation.Resource; import java.io.File; import static org.junit.Assert.assertEquals; diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/QualifierResourceInjectionIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/QualifierResourceInjectionIntegrationTest.java index cc8c669757..03f82adef3 100644 --- a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/QualifierResourceInjectionIntegrationTest.java +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/QualifierResourceInjectionIntegrationTest.java @@ -9,7 +9,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.baeldung.wiring.configuration.ApplicationContextTestResourceQualifier; -import javax.annotation.Resource; +import jakarta.annotation.Resource; import java.io.File; import static org.junit.Assert.assertEquals; diff --git a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/SetterResourceInjectionIntegrationTest.java b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/SetterResourceInjectionIntegrationTest.java index 90c8677bff..605f86172c 100644 --- a/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/SetterResourceInjectionIntegrationTest.java +++ b/spring-di-2/src/test/java/com/baeldung/wiring/configuration/resource/SetterResourceInjectionIntegrationTest.java @@ -8,7 +8,7 @@ import org.springframework.test.context.support.AnnotationConfigContextLoader; import com.baeldung.wiring.configuration.ApplicationContextTestResourceNameType; -import javax.annotation.Resource; +import jakarta.annotation.Resource; import java.io.File; import static org.junit.Assert.assertEquals; diff --git a/spring-di-3/pom.xml b/spring-di-3/pom.xml index 2d635d1f85..ba1a18ae8c 100644 --- a/spring-di-3/pom.xml +++ b/spring-di-3/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-spring-5 + parent-spring-6 0.0.1-SNAPSHOT - ../parent-spring-5 + ../parent-spring-6 @@ -45,8 +45,10 @@ - 2.6.1 + 3.1.2 2.17.1 + 2.0.9 + 1.4.11 \ No newline at end of file diff --git a/spring-di-3/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java b/spring-di-3/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java index 56582ecb66..d93f94b0e3 100644 --- a/spring-di-3/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java +++ b/spring-di-3/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java @@ -7,7 +7,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = DynamicAutowireConfig.class) diff --git a/spring-di-4/pom.xml b/spring-di-4/pom.xml index c6572495cb..1eec8efcf0 100644 --- a/spring-di-4/pom.xml +++ b/spring-di-4/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 diff --git a/spring-di-4/src/main/java/com/baeldung/sampleabstract/BallService.java b/spring-di-4/src/main/java/com/baeldung/sampleabstract/BallService.java index 0d951aac8b..541d8dfb6b 100644 --- a/spring-di-4/src/main/java/com/baeldung/sampleabstract/BallService.java +++ b/spring-di-4/src/main/java/com/baeldung/sampleabstract/BallService.java @@ -2,7 +2,7 @@ package com.baeldung.sampleabstract; import org.springframework.beans.factory.annotation.Autowired; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; public abstract class BallService { diff --git a/spring-di/pom.xml b/spring-di/pom.xml index af0601deb6..bae7263ef9 100644 --- a/spring-di/pom.xml +++ b/spring-di/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring-5 + parent-spring-6 0.0.1-SNAPSHOT - ../parent-spring-5 + ../parent-spring-6 @@ -48,11 +48,6 @@ spring-context ${spring.version} - - javax.inject - javax.inject - ${javax.inject.version} - com.google.guava guava @@ -71,7 +66,7 @@ org.springframework.boot spring-boot-test - ${mockito.spring.boot.version} + ${spring-boot.version} test @@ -89,11 +84,6 @@ - - javax.annotation - javax.annotation-api - ${annotation-api.version} - @@ -143,11 +133,7 @@ org.baeldung.org.baeldung.sample.App - 1.3.2 - 1.4.4.RELEASE - 1 - 1.5.2.RELEASE - 1.10.19 + 3.1.2 1.9.5 From 33f52b2e0bf44f70b1ecb114911a214925e9590a Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Wed, 1 Nov 2023 20:54:40 +0200 Subject: [PATCH 82/91] This PR is related to the article BAEL-7130 (#15109) * This commit related to the article BAEL-7130 This commit aims to add a RoundDate class with several methods to round the date. * This commit related to the article BAEL-7130 This commit aims to add a test class DateRoundingUnitTest. --- .../com/baeldung/rounddate/RoundDate.java | 113 ++++++++++++++++++ .../rounddate/DateRoundingUnitTest.java | 63 ++++++++++ 2 files changed, 176 insertions(+) create mode 100644 core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/rounddate/RoundDate.java create mode 100644 core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/rounddate/DateRoundingUnitTest.java diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/rounddate/RoundDate.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/rounddate/RoundDate.java new file mode 100644 index 0000000000..6fb7cf87b7 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/rounddate/RoundDate.java @@ -0,0 +1,113 @@ +package com.baeldung.rounddate; + +import java.time.DayOfWeek; +import java.time.temporal.ChronoField; +import java.time.temporal.TemporalAdjusters; +import java.util.Calendar; +import java.util.Date; +import java.time.LocalDateTime; +import java.time.ZonedDateTime; + +public class RoundDate { + public static Date getDate(int year, int month, int day, int hour, int minute) { + Calendar calendar = Calendar.getInstance(); + calendar.set(Calendar.YEAR, year); + calendar.set(Calendar.MONTH, month); + calendar.set(Calendar.DAY_OF_MONTH, day); + calendar.set(Calendar.HOUR_OF_DAY, hour); + calendar.set(Calendar.MINUTE, minute); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + + return calendar.getTime(); + } + + public static Date roundToDay(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + return calendar.getTime(); + } + + public static Date roundToNearestUnit(Date date, int unit) { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + + switch (unit) { + case Calendar.HOUR: + int minute = calendar.get(Calendar.MINUTE); + if (minute >= 0 && minute < 15) { + calendar.set(Calendar.MINUTE, 0); + } else if (minute >= 15 && minute < 45) { + calendar.set(Calendar.MINUTE, 30); + } else { + calendar.set(Calendar.MINUTE, 0); + calendar.add(Calendar.HOUR_OF_DAY, 1); + } + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + break; + + case Calendar.DAY_OF_MONTH: + int hour = calendar.get(Calendar.HOUR_OF_DAY); + if (hour >= 12) { + calendar.add(Calendar.DAY_OF_MONTH, 1); + } + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + break; + + case Calendar.MONTH: + int day = calendar.get(Calendar.DAY_OF_MONTH); + if (day >= 15) { + calendar.add(Calendar.MONTH, 1); + } + calendar.set(Calendar.DAY_OF_MONTH, 1); + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + break; + } + + return calendar.getTime(); + } + + public static LocalDateTime roundToStartOfMonthUsingLocalDateTime(LocalDateTime dateTime) { + return dateTime.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0); + } + + public static LocalDateTime roundToEndOfWeekUsingLocalDateTime(LocalDateTime dateTime) { + return dateTime.with(TemporalAdjusters.next(DayOfWeek.SATURDAY)) + .withHour(23) + .withMinute(59) + .withSecond(59) + .withNano(999); + } + + public static ZonedDateTime roundToStartOfMonthUsingZonedDateTime(ZonedDateTime dateTime) { + return dateTime.withDayOfMonth(1) + .withHour(0) + .withMinute(0) + .withSecond(0) + .with(ChronoField.MILLI_OF_SECOND, 0) + .with(ChronoField.MICRO_OF_SECOND, 0) + .with(ChronoField.NANO_OF_SECOND, 0); + } + + public static ZonedDateTime roundToEndOfWeekUsingZonedDateTime(ZonedDateTime dateTime) { + return dateTime.with(TemporalAdjusters.next(DayOfWeek.SATURDAY)) + .withHour(23) + .withMinute(59) + .withSecond(59) + .with(ChronoField.MILLI_OF_SECOND, 999) + .with(ChronoField.MICRO_OF_SECOND, 999) + .with(ChronoField.NANO_OF_SECOND, 999); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/rounddate/DateRoundingUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/rounddate/DateRoundingUnitTest.java new file mode 100644 index 0000000000..bbe49d8340 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/rounddate/DateRoundingUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.rounddate; + +import org.junit.Test; + +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; + +import static org.junit.Assert.assertEquals; + +public class DateRoundingUnitTest { + + @Test + public void givenDate_whenRoundToDay_thenBeginningOfDay() { + Date date = RoundDate.getDate(2023, Calendar.JANUARY, 27, 14, 30); + Date result = RoundDate.roundToDay(date); + assertEquals(RoundDate.getDate(2023, Calendar.JANUARY, 27, 0, 0), result); + } + + @Test + public void givenDate_whenRoundToNearestUnit_thenNearestUnit() { + Date date = RoundDate.getDate(2023, Calendar.JANUARY, 27, 14, 12); + Date result = RoundDate.roundToNearestUnit(date, Calendar.DAY_OF_MONTH); + Date expected = RoundDate.getDate(2023, Calendar.JANUARY, 28, 0, 0); + assertEquals(expected, result); + } + + @Test + public void givenLocalDateTime_whenRoundToStartOfMonth_thenStartOfMonth() { + LocalDateTime dateTime = LocalDateTime.of(2023, 1, 27, 14, 12); + LocalDateTime result = RoundDate.roundToStartOfMonthUsingLocalDateTime(dateTime); + LocalDateTime expected = LocalDateTime.of(2023, 1, 1, 0, 0, 0); + assertEquals(expected, result); + } + + + @Test + public void givenZonedDateTime_whenRoundToStartOfMonth_thenStartOfMonth() { + ZonedDateTime dateTime = ZonedDateTime.of(2023, 1, 27, 14, 12, 0, 0, ZoneId.systemDefault()); + ZonedDateTime result = RoundDate.roundToStartOfMonthUsingZonedDateTime(dateTime); + ZonedDateTime expected = ZonedDateTime.of(2023, 1, 1, 0, 0, 0, 0, ZoneId.systemDefault()); + assertEquals(expected, result); + } + + @Test + public void givenLocalDateTime_whenRoundToEndOfWeek_thenEndOfWeek() { + LocalDateTime dateTime = LocalDateTime.of(2023, 1, 27, 14, 12); + LocalDateTime result = RoundDate.roundToEndOfWeekUsingLocalDateTime(dateTime); + LocalDateTime expected = LocalDateTime.of(2023, 1, 28, 23, 59, 59, 999); + assertEquals(expected, result); + } + + @Test + public void givenZonedDateTime_whenRoundToEndOfWeek_thenEndOfWeek() { + ZonedDateTime dateTime = ZonedDateTime.of(2023, 1, 27, 14, 12, 0, 0, ZoneId.systemDefault()); + ZonedDateTime result = RoundDate.roundToEndOfWeekUsingZonedDateTime(dateTime); + ZonedDateTime expected = ZonedDateTime.of(2023, 1, 28, 23, 59, 59, 999, ZoneId.systemDefault()); + assertEquals(expected, result); + } + +} From aaa4e333a66c8701d53f50331de07625cca074b2 Mon Sep 17 00:00:00 2001 From: Bhaskar Ghosh Dastidar Date: Thu, 2 Nov 2023 00:32:13 +0530 Subject: [PATCH 83/91] [BAEL-7043] mutable strings (#15112) Co-authored-by: Bhaskar --- .../mutablestrings/CharsetUsageExample.java | 34 ++++++++++ .../MutableStringUsingCharset.java | 65 +++++++++++++++++++ .../mutablestrings/MutableStrings.java | 24 +++++++ .../mutablestring/CharsetUsageUnitTest.java | 17 +++++ .../MutableStringUsingCharsetUnitTest.java | 24 +++++++ 5 files changed, 164 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/mutablestrings/CharsetUsageExample.java create mode 100644 core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/mutablestrings/MutableStringUsingCharset.java create mode 100644 core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/mutablestrings/MutableStrings.java create mode 100644 core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/mutablestring/CharsetUsageUnitTest.java create mode 100644 core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/mutablestring/MutableStringUsingCharsetUnitTest.java diff --git a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/mutablestrings/CharsetUsageExample.java b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/mutablestrings/CharsetUsageExample.java new file mode 100644 index 0000000000..5ef8783ac8 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/mutablestrings/CharsetUsageExample.java @@ -0,0 +1,34 @@ +package com.baeldung.mutablestrings; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CoderResult; + +public class CharsetUsageExample { + + public ByteBuffer encodeString(String inputString) { + Charset charset = Charset.forName("UTF-8"); + CharsetEncoder encoder = charset.newEncoder(); + + CharBuffer charBuffer = CharBuffer.wrap(inputString); + ByteBuffer byteBuffer = ByteBuffer.allocate(50); + + encoder.encode(charBuffer, byteBuffer, true); // true indicates the end of input + byteBuffer.flip(); + return byteBuffer; + } + + public String decodeString(ByteBuffer byteBuffer) { + Charset charset = Charset.forName("UTF-8"); + CharsetDecoder decoder = charset.newDecoder(); + CharBuffer decodedCharBuffer = CharBuffer.allocate(50); + decoder.decode(byteBuffer, decodedCharBuffer, true); + decodedCharBuffer.flip(); + + return decodedCharBuffer.toString(); + } +} diff --git a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/mutablestrings/MutableStringUsingCharset.java b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/mutablestrings/MutableStringUsingCharset.java new file mode 100644 index 0000000000..3e4285c9d0 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/mutablestrings/MutableStringUsingCharset.java @@ -0,0 +1,65 @@ +package com.baeldung.mutablestrings; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CoderResult; +import java.util.concurrent.atomic.AtomicReference; + +public class MutableStringUsingCharset { + + private final AtomicReference cbRef = new AtomicReference<>(); + private final Charset myCharset = new Charset("mycharset", null) { + @Override + public boolean contains(Charset cs) { + return false; + } + + @Override + public CharsetDecoder newDecoder() { + return new CharsetDecoder(this, 1.0f, 1.0f) { + @Override + protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) { + cbRef.set(out); + while (in.remaining() > 0) { + out.append((char) in.get()); + } + return CoderResult.UNDERFLOW; + } + }; + } + + @Override + public CharsetEncoder newEncoder() { + CharsetEncoder cd = new CharsetEncoder(this, 1.0f, 1.0f) { + @Override + protected CoderResult encodeLoop(CharBuffer in, ByteBuffer out) { + while (in.hasRemaining()) { + if (!out.hasRemaining()) { + return CoderResult.OVERFLOW; + } + char currentChar = in.get(); + if (currentChar > 127) { + return CoderResult.unmappableForLength(1); + } + out.put((byte) currentChar); + } + return CoderResult.UNDERFLOW; + } + }; + return cd; + } + }; + + public String createModifiableString(String s) { + return new String(s.getBytes(), myCharset); + } + + public void modifyString() { + CharBuffer cb = cbRef.get(); + cb.position(0); + cb.put("xyz"); + } +} diff --git a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/mutablestrings/MutableStrings.java b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/mutablestrings/MutableStrings.java new file mode 100644 index 0000000000..99994498b9 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/mutablestrings/MutableStrings.java @@ -0,0 +1,24 @@ +package com.baeldung.mutablestrings; + +import java.lang.reflect.Field; +import java.nio.charset.Charset; + +import com.google.errorprone.annotations.DoNotCall; + +public class MutableStrings { + + /** + * This involves using Reflection to change String fields and it is not encouraged to use this in programs. + * @throws NoSuchFieldException + * @throws IllegalAccessException + */ + @DoNotCall + public void mutableUsingReflection() throws NoSuchFieldException, IllegalAccessException { + String myString = "Hello World"; + String otherString = new String("Hello World"); + Field f = String.class.getDeclaredField("value"); + f.setAccessible(true); + f.set(myString, "Hi World".toCharArray()); + System.out.println(otherString); + } +} diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/mutablestring/CharsetUsageUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/mutablestring/CharsetUsageUnitTest.java new file mode 100644 index 0000000000..f009b0242f --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/mutablestring/CharsetUsageUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.mutablestring; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import com.baeldung.mutablestrings.CharsetUsageExample; + +public class CharsetUsageUnitTest { + + @Test + public void givenCharset_whenStringIsEncodedAndDecoded_thenGivesCorrectResult() { + CharsetUsageExample ch = new CharsetUsageExample(); + String inputString = "hello दुनिया"; + String result = ch.decodeString(ch.encodeString(inputString)); + Assertions.assertEquals(inputString, result); + } +} diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/mutablestring/MutableStringUsingCharsetUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/mutablestring/MutableStringUsingCharsetUnitTest.java new file mode 100644 index 0000000000..81a92038d5 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/mutablestring/MutableStringUsingCharsetUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.mutablestring; + +import org.junit.Assert; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import com.baeldung.mutablestrings.MutableStringUsingCharset; + +public class MutableStringUsingCharsetUnitTest { + @Test + @Disabled + /** + * This test is disabled as it works well for Java 8 and below + */ + public void givenCustomCharSet_whenStringUpdated_StringGetsMutated() throws Exception { + MutableStringUsingCharset ms = new MutableStringUsingCharset(); + String s = ms.createModifiableString("Hello"); + Assert.assertEquals("Hello", s); + ms.modifyString(); + Assert.assertEquals("something", s); + } + +} + From 7482aa3c25e702410158e6e9ecabc12ec3c49edf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bogdan=20Cardo=C5=9F?= <106325528+sodrac@users.noreply.github.com> Date: Wed, 1 Nov 2023 21:13:08 +0200 Subject: [PATCH 84/91] BAEL-6874 test code for article (#15118) * BAEL-6819 convert from int to Long in Java * BAEL-6819 update package name * BAEL-6874 test code for article * BAEL-6874 rename test class --- .../GenericNumbersComparatorUnitTest.java | 122 ++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/genericnumberscomparator/GenericNumbersComparatorUnitTest.java diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/genericnumberscomparator/GenericNumbersComparatorUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/genericnumberscomparator/GenericNumbersComparatorUnitTest.java new file mode 100644 index 0000000000..37b971b5c5 --- /dev/null +++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/genericnumberscomparator/GenericNumbersComparatorUnitTest.java @@ -0,0 +1,122 @@ +package com.baeldung.genericnumberscomparator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.function.BiFunction; +import java.util.function.BiPredicate; +import java.util.function.Function; + +import org.junit.jupiter.api.Test; + +class GenericNumbersComparatorUnitTest { + + public int compareDouble(Number num1, Number num2) { + return Double.compare(num1.doubleValue(), num2.doubleValue()); + } + + @Test + void givenNumbers_whenUseCompareDouble_thenWillExecuteComparison() { + assertEquals(0, compareDouble(5, 5.0)); + } + + public int compareTo(Integer int1, Integer int2) { + return int1.compareTo(int2); + } + + @Test + void givenNumbers_whenUseCompareTo_thenWillExecuteComparison() { + assertEquals(-1, compareTo(5, 7)); + } + + Map, BiFunction> comparisonMap = new HashMap<>(); + + public int compareUsingMap(Number num1, Number num2) { + comparisonMap.put(Integer.class, (a, b) -> ((Integer) num1).compareTo((Integer) num2)); + + return comparisonMap.get(num1.getClass()) + .apply(num1, num2); + } + + @Test + void givenNumbers_whenUseCompareUsingMap_thenWillExecuteComparison() { + assertEquals(-1, compareUsingMap(5, 7)); + } + + public interface NumberComparator { + int compare(Number num1, Number num2); + } + + @Test + void givenNumbers_whenUseProxy_thenWillExecuteComparison() { + NumberComparator proxy = (NumberComparator) Proxy.newProxyInstance(NumberComparator.class.getClassLoader(), new Class[] { NumberComparator.class }, + (p, method, args) -> Double.compare(((Number) args[0]).doubleValue(), ((Number) args[1]).doubleValue())); + assertEquals(0, proxy.compare(5, 5.0)); + } + + public int compareUsingReflection(Number num1, Number num2) throws Exception { + Method method = num1.getClass() + .getMethod("compareTo", num1.getClass()); + return (int) method.invoke(num1, num2); + } + + @Test + void givenNumbers_whenUseCompareUsingReflection_thenWillExecuteComparison() throws Exception { + assertEquals(-1, compareUsingReflection(5, 7)); + } + + interface NumberComparatorFactory { + Comparator getComparator(); + } + + class IntegerComparatorFactory implements NumberComparatorFactory { + @Override + public Comparator getComparator() { + return (num1, num2) -> ((Integer) num1).compareTo((Integer) num2); + } + } + + @Test + void givenNumbers_whenUseComparatorFactory_thenWillExecuteComparison() { + NumberComparatorFactory factory = new IntegerComparatorFactory(); + Comparator comparator = factory.getComparator(); + assertEquals(-1, comparator.compare(5, 7)); + } + + Function toDouble = Number::doubleValue; + BiPredicate isEqual = (num1, num2) -> toDouble.apply(num1) + .equals(toDouble.apply(num2)); + + @Test + void givenNumbers_whenUseIsEqual_thenWillExecuteComparison() { + assertEquals(true, isEqual.test(5, 5.0)); + } + + private Number someNumber = 5; + private Number anotherNumber = 5.0; + + Optional optNum1 = Optional.ofNullable(someNumber); + Optional optNum2 = Optional.ofNullable(anotherNumber); + int comparisonResult = optNum1.flatMap(n1 -> optNum2.map(n2 -> Double.compare(n1.doubleValue(), n2.doubleValue()))) + .orElse(0); + + @Test + void givenNumbers_whenUseComparisonResult_thenWillExecuteComparison() { + assertEquals(0, comparisonResult); + } + + private boolean someCondition = true; + Function dynamicFunction = someCondition ? Number::doubleValue : Number::intValue; + Comparator dynamicComparator = (num1, num2) -> ((Comparable) dynamicFunction.apply(num1)).compareTo(dynamicFunction.apply(num2)); + + @Test + void givenNumbers_whenUseDynamicComparator_thenWillExecuteComparison() { + assertEquals(0, dynamicComparator.compare(5, 5.0)); + } + +} From dad8a5c02156e46917631135b58565f4e61cd394 Mon Sep 17 00:00:00 2001 From: mikr Date: Wed, 1 Nov 2023 21:14:14 +0100 Subject: [PATCH 85/91] Update readme --- core-java-modules/core-java-strings/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-strings/README.md b/core-java-modules/core-java-strings/README.md index 03e980e5a5..dbbfcc79b6 100644 --- a/core-java-modules/core-java-strings/README.md +++ b/core-java-modules/core-java-strings/README.md @@ -14,3 +14,4 @@ Listed here there are only those articles that does not fit into other core-java - [Java String Interview Questions and Answers](https://www.baeldung.com/java-string-interview-questions) - [Java Multi-line String](https://www.baeldung.com/java-multiline-string) - [Reuse StringBuilder for Efficiency](https://www.baeldung.com/java-reuse-stringbuilder-for-efficiency) +- [How to Iterate Over the String Characters in Java](https://www.baeldung.com/java-iterate-string-characters) From d8fb8b381f99060455efce564d3cc1f796a41577 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Thu, 2 Nov 2023 02:28:53 +0100 Subject: [PATCH 86/91] [linkedhashmap-first-last] get first and last entry from LinkedHashMap (#15066) * [linkedhashmap-first-last] get first and last entry from LinkedHashMap * [linkedhashmap-first-last] add the stream approach --- .../core-java-collections-maps-7/pom.xml | 13 +++ ...AndLastEntryFromLinkedHashMapUnitTest.java | 85 +++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/linkedhashmapfirstandlastentry/GetFirstAndLastEntryFromLinkedHashMapUnitTest.java diff --git a/core-java-modules/core-java-collections-maps-7/pom.xml b/core-java-modules/core-java-collections-maps-7/pom.xml index bcc0915073..cefee201cc 100644 --- a/core-java-modules/core-java-collections-maps-7/pom.xml +++ b/core-java-modules/core-java-collections-maps-7/pom.xml @@ -79,5 +79,18 @@ 1.5 + + + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-opens java.base/java.util=ALL-UNNAMED + + + + + diff --git a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/linkedhashmapfirstandlastentry/GetFirstAndLastEntryFromLinkedHashMapUnitTest.java b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/linkedhashmapfirstandlastentry/GetFirstAndLastEntryFromLinkedHashMapUnitTest.java new file mode 100644 index 0000000000..b872e8bdda --- /dev/null +++ b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/linkedhashmapfirstandlastentry/GetFirstAndLastEntryFromLinkedHashMapUnitTest.java @@ -0,0 +1,85 @@ +package com.baeldung.map.linkedhashmapfirstandlastentry; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map.Entry; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class GetFirstAndLastEntryFromLinkedHashMapUnitTest { + private static final LinkedHashMap THE_MAP = new LinkedHashMap<>(); + + static { + THE_MAP.put("key one", "a1 b1 c1"); + THE_MAP.put("key two", "a2 b2 c2"); + THE_MAP.put("key three", "a3 b3 c3"); + THE_MAP.put("key four", "a4 b4 c4"); + } + + @Test + void whenIteratingEntrySet_thenGetExpectedResult() { + Entry firstEntry = THE_MAP.entrySet().iterator().next(); + assertEquals("key one", firstEntry.getKey()); + assertEquals("a1 b1 c1", firstEntry.getValue()); + + Entry lastEntry = null; + Iterator> it = THE_MAP.entrySet().iterator(); + while (it.hasNext()) { + lastEntry = it.next(); + } + + assertNotNull(lastEntry); + assertEquals("key four", lastEntry.getKey()); + assertEquals("a4 b4 c4", lastEntry.getValue()); + + } + + @Test + void whenConvertingEntriesToArray_thenGetExpectedResult() { + + Entry[] theArray = new Entry[THE_MAP.size()]; + THE_MAP.entrySet().toArray(theArray); + + Entry firstEntry = theArray[0]; + assertEquals("key one", firstEntry.getKey()); + assertEquals("a1 b1 c1", firstEntry.getValue()); + + Entry lastEntry = theArray[THE_MAP.size() - 1]; + assertEquals("key four", lastEntry.getKey()); + assertEquals("a4 b4 c4", lastEntry.getValue()); + } + + @Test + void whenUsingStreamAPI_thenGetExpectedResult() { + Entry firstEntry = THE_MAP.entrySet().stream().findFirst().get(); + assertEquals("key one", firstEntry.getKey()); + assertEquals("a1 b1 c1", firstEntry.getValue()); + + Entry lastEntry = THE_MAP.entrySet().stream().skip(THE_MAP.size() - 1).findFirst().get(); + + assertNotNull(lastEntry); + assertEquals("key four", lastEntry.getKey()); + assertEquals("a4 b4 c4", lastEntry.getValue()); + } + + @Test + void whenUsingReflection_thenGetExpectedResult() throws NoSuchFieldException, IllegalAccessException { + Field head = THE_MAP.getClass().getDeclaredField("head"); + head.setAccessible(true); + Entry firstEntry = (Entry) head.get(THE_MAP); + assertEquals("key one", firstEntry.getKey()); + assertEquals("a1 b1 c1", firstEntry.getValue()); + + Field tail = THE_MAP.getClass().getDeclaredField("tail"); + tail.setAccessible(true); + Entry lastEntry = (Entry) tail.get(THE_MAP); + assertEquals("key four", lastEntry.getKey()); + assertEquals("a4 b4 c4", lastEntry.getValue()); + } + + +} \ No newline at end of file From 57840bb083acfee2834a7fec5fe0da38e19c228a Mon Sep 17 00:00:00 2001 From: Palaniappan Arunachalam Date: Thu, 2 Nov 2023 09:28:54 +0530 Subject: [PATCH 87/91] BAEL-4200: JNDI - What Is java:comp/env? (#15081) --- .../com/baeldung/jndi/JndiNamingUnitTest.java | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/JndiNamingUnitTest.java diff --git a/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/JndiNamingUnitTest.java b/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/JndiNamingUnitTest.java new file mode 100644 index 0000000000..66d8d57d4e --- /dev/null +++ b/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/JndiNamingUnitTest.java @@ -0,0 +1,72 @@ +package com.baeldung.jndi; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jndi.JndiTemplate; +import org.springframework.mock.jndi.SimpleNamingContextBuilder; + +import javax.naming.*; +import javax.sql.DataSource; + +import java.util.Enumeration; + +import static org.junit.jupiter.api.Assertions.*; + +class JndiNamingUnitTest { + + private static InitialContext context; + private static DriverManagerDataSource dataSource; + + @BeforeAll + static void setUp() throws Exception { + SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder(); + dataSource = new DriverManagerDataSource("jdbc:h2:mem:mydb"); + builder.activate(); + + JndiTemplate jndiTemplate = new JndiTemplate(); + context = (InitialContext) jndiTemplate.getContext(); + + dataSource.setDriverClassName("org.h2.Driver"); + context.bind("java:comp/env/jdbc/datasource", dataSource); + } + + @Test + void givenACompositeName_whenAddingAnElement_thenNameIsAdded() throws Exception { + Name objectName = new CompositeName("java:comp/env/jdbc"); + + Enumeration items = objectName.getAll(); + while(items.hasMoreElements()) { + System.out.println(items.nextElement()); + } + + objectName.add("New Name"); + + assertEquals("env", objectName.get(1)); + assertEquals("New Name", objectName.get(objectName.size() - 1)); + } + + @Test + void givenContext_whenLookupByName_thenReturnsValidObject() throws Exception { + DataSource ds = (DataSource) context.lookup("java:comp/env/jdbc/datasource"); + + assertNotNull(ds); + assertNotNull(ds.getConnection()); + } + + @Test + void givenSubContext_whenLookupByName_thenReturnsValidObject() throws Exception { + Context subContext = (Context) context.lookup("java:comp/env"); + DataSource ds = (DataSource) subContext.lookup("jdbc/datasource"); + + assertNotNull(ds); + assertNotNull(ds.getConnection()); + } + + @AfterAll + static void tearDown() throws Exception { + context.close(); + } + +} From 4c06d8e9f9e2a9ad53a1150ee5be4dd074d27fb4 Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Fri, 3 Nov 2023 05:15:06 +0100 Subject: [PATCH 88/91] How to Document Generic Type Parameter (#15108) * How to Documeny Generic Type Parameters * How to Documeny Generic Type Parameters --- .../java/com/baeldung/generictype/Pair.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 core-java-modules/core-java-documentation/src/main/java/com/baeldung/generictype/Pair.java diff --git a/core-java-modules/core-java-documentation/src/main/java/com/baeldung/generictype/Pair.java b/core-java-modules/core-java-documentation/src/main/java/com/baeldung/generictype/Pair.java new file mode 100644 index 0000000000..f85adcfdab --- /dev/null +++ b/core-java-modules/core-java-documentation/src/main/java/com/baeldung/generictype/Pair.java @@ -0,0 +1,23 @@ +package com.baeldung.generictype; + +/** + * @param The type of the first value in the {@code Pair}. + * @param The type of the second value in the {@code Pair}. + */ + +public class Pair { + public T first; + public S second; + + /** + * Constructs a new Pair object with the specified values. + * + * @param a The first value. + * @param b The second value. + */ + + public Pair(T a, S b) { + first = a; + second = b; + } +} From 6f618f5cf9b6a3e97ec7ced4802e9c4a556e9901 Mon Sep 17 00:00:00 2001 From: Pedro Lopes Date: Fri, 3 Nov 2023 01:20:47 -0300 Subject: [PATCH 89/91] BAEL-7128: Optional as a Record Parameter in Java (#15114) * record class and test * renaming test --- .../optionalsasparameterrecords/Product.java | 6 ++++++ .../OptionalAsRecordParameterUnitTest.java | 17 +++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 core-java-modules/core-java-records/src/main/java/com/baeldung/optionalsasparameterrecords/Product.java create mode 100644 core-java-modules/core-java-records/src/test/java/com/baeldung/optionalsasparameterrecords/OptionalAsRecordParameterUnitTest.java diff --git a/core-java-modules/core-java-records/src/main/java/com/baeldung/optionalsasparameterrecords/Product.java b/core-java-modules/core-java-records/src/main/java/com/baeldung/optionalsasparameterrecords/Product.java new file mode 100644 index 0000000000..8ede001ee1 --- /dev/null +++ b/core-java-modules/core-java-records/src/main/java/com/baeldung/optionalsasparameterrecords/Product.java @@ -0,0 +1,6 @@ +package com.baeldung.optionalsasparameterrecords; + +import java.util.Optional; + +public record Product(String name, double price, Optional description) { +} diff --git a/core-java-modules/core-java-records/src/test/java/com/baeldung/optionalsasparameterrecords/OptionalAsRecordParameterUnitTest.java b/core-java-modules/core-java-records/src/test/java/com/baeldung/optionalsasparameterrecords/OptionalAsRecordParameterUnitTest.java new file mode 100644 index 0000000000..554fb2eac3 --- /dev/null +++ b/core-java-modules/core-java-records/src/test/java/com/baeldung/optionalsasparameterrecords/OptionalAsRecordParameterUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.optionalsasparameterrecords; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +public class OptionalAsRecordParameterUnitTest { + + @Test + public void givenRecordCreationWithOptional_thenCreateItProperly() { + var emptyDescriptionProduct = new Product("television", 1699.99, Optional.empty()); + Assertions.assertEquals("television", emptyDescriptionProduct.name()); + Assertions.assertEquals(1699.99, emptyDescriptionProduct.price()); + Assertions.assertNull(emptyDescriptionProduct.description().orElse(null)); + } +} From b11ba779376bfd74ee8fdc73ba756597e5b76b59 Mon Sep 17 00:00:00 2001 From: Reza Ganji Date: Fri, 3 Nov 2023 07:57:27 +0330 Subject: [PATCH 90/91] BAEL-5970 Working with MathFlux (#15116) * Working with MathFlux. * revert change to readme. * merge codes in unit test. * merge codes in unit test. --------- Co-authored-by: rezaganjis --- reactor-core/pom.xml | 7 ++- .../math/MathFluxOperationsUnitTest.java | 48 +++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 reactor-core/src/test/java/com/baeldung/reactor/math/MathFluxOperationsUnitTest.java diff --git a/reactor-core/pom.xml b/reactor-core/pom.xml index e27a1a2845..dd7533fe73 100644 --- a/reactor-core/pom.xml +++ b/reactor-core/pom.xml @@ -26,6 +26,11 @@ ${reactor.version} test + + io.projectreactor.addons + reactor-extra + ${reactor.version} + org.projectlombok lombok @@ -35,7 +40,7 @@ - 3.4.17 + 3.5.1 \ No newline at end of file diff --git a/reactor-core/src/test/java/com/baeldung/reactor/math/MathFluxOperationsUnitTest.java b/reactor-core/src/test/java/com/baeldung/reactor/math/MathFluxOperationsUnitTest.java new file mode 100644 index 0000000000..2ff8005acd --- /dev/null +++ b/reactor-core/src/test/java/com/baeldung/reactor/math/MathFluxOperationsUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.math; + +import org.junit.Test; + +import reactor.math.MathFlux; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +public class MathFluxOperationsUnitTest { + + @Test + public void givenFluxOfNumbers_whenCalculatingSum_thenExpectCorrectResult() { + Flux numbers = Flux.just(1, 2, 3, 4, 5); + Mono sumMono = MathFlux.sumInt(numbers); + StepVerifier.create(sumMono) + .expectNext(15) + .verifyComplete(); + } + + @Test + public void givenFluxOfNumbers_whenCalculatingAverage_thenExpectCorrectResult() { + Flux numbers = Flux.just(1, 2, 3, 4, 5); + Mono averageMono = MathFlux.averageDouble(numbers); + StepVerifier.create(averageMono) + .expectNext(3.0) + .verifyComplete(); + } + + @Test + public void givenFluxOfNumbers_whenFindingMinElement_thenExpectCorrectResult() { + Flux numbers = Flux.just(3, 1, 5, 2, 4); + Mono minMono = MathFlux.min(numbers); + StepVerifier.create(minMono) + .expectNext(1) + .verifyComplete(); + } + + @Test + public void givenFluxOfNumbers_whenFindingMaxElement_thenExpectCorrectResult() { + Flux numbers = Flux.just(3, 1, 5, 2, 4); + Mono maxMono = MathFlux.max(numbers); + StepVerifier.create(maxMono) + .expectNext(5) + .verifyComplete(); + } + +} From 26a57c08ee02d090edb77376d69f7bf0258646f3 Mon Sep 17 00:00:00 2001 From: Gaetano Piazzolla Date: Fri, 3 Nov 2023 13:21:09 +0100 Subject: [PATCH 91/91] JAVA-22296 | Upgrade spring-cloud-modules to JDK 17: Chunk 4 (#15020) --- .../spring-cloud-contract-consumer/pom.xml | 11 +++++ .../BasicMathControllerIntegrationTest.java | 48 ++++--------------- 2 files changed, 19 insertions(+), 40 deletions(-) diff --git a/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/pom.xml b/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/pom.xml index a8c3337de5..234f8b1b60 100644 --- a/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/pom.xml +++ b/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/pom.xml @@ -16,10 +16,12 @@ + org.springframework.boot spring-boot-starter-web + org.springframework.boot spring-boot-starter-data-rest @@ -30,16 +32,25 @@ spring-cloud-contract-wiremock test + org.springframework.cloud spring-cloud-contract-stub-runner test + com.baeldung.spring.cloud spring-cloud-contract-producer ${project.parent.version} + stubs test + + + * + * + + diff --git a/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathControllerIntegrationTest.java b/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathControllerIntegrationTest.java index c19b3f3694..c7d8b695db 100644 --- a/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathControllerIntegrationTest.java +++ b/spring-cloud-modules/spring-cloud-contract/spring-cloud-contract-consumer/src/test/java/com/baeldung/spring/cloud/springcloudcontractconsumer/controller/BasicMathControllerIntegrationTest.java @@ -1,24 +1,18 @@ package com.baeldung.spring.cloud.springcloudcontractconsumer.controller; -import com.github.tomakehurst.wiremock.WireMockServer; -import com.github.tomakehurst.wiremock.core.WireMockConfiguration; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.json.AutoConfigureJsonTesters; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.contract.stubrunner.spring.AutoConfigureStubRunner; -import org.springframework.cloud.contract.stubrunner.spring.StubRunnerProperties; +import org.springframework.cloud.contract.stubrunner.junit.StubRunnerRule; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -26,42 +20,16 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc @AutoConfigureJsonTesters -@AutoConfigureStubRunner(stubsMode = StubRunnerProperties.StubsMode.LOCAL, - ids = "com.baeldung.spring.cloud:spring-cloud-contract-producer:+:stubs:8090") public class BasicMathControllerIntegrationTest { + @Rule + public StubRunnerRule rule = new StubRunnerRule().downloadStub( + "com.baeldung.spring.cloud", + "spring-cloud-contract-producer") + .withPort(8090).failOnNoStubs(true); + @Autowired private MockMvc mockMvc; - private static WireMockServer wireMockServer; - - - @BeforeClass - public static void setupClass() { - WireMockConfiguration wireMockConfiguration = WireMockConfiguration.options().port(8090); // Use the same port as in your code - - wireMockServer = new WireMockServer(wireMockConfiguration); - wireMockServer.start(); - } - - @AfterClass - public static void teardownClass() { - wireMockServer.stop(); - } - - @Before - public void setup() { - wireMockServer.stubFor(get(urlEqualTo("/validate/prime-number?number=1")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "application/json") - .withBody("Odd"))); - - wireMockServer.stubFor(get(urlEqualTo("/validate/prime-number?number=2")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", "application/json") - .withBody("Even"))); - } @Test public void given_WhenPassEvenNumberInQueryParam_ThenReturnEven() throws Exception {