From 78d8f62ef7f5453f02522eba2999b124338bc126 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Tue, 26 Sep 2023 10:05:04 +0700 Subject: [PATCH 001/108] [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 002/108] [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 fe9c78ceb8999b37477da54bf58566e5d4fe328c Mon Sep 17 00:00:00 2001 From: Sam Gardner Date: Thu, 28 Sep 2023 16:29:51 +0100 Subject: [PATCH 003/108] BAEL-6895 Add code for truncating a double to two decimal places --- .../TruncateDoubleUnitTest.java | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/truncatedouble/TruncateDoubleUnitTest.java diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/truncatedouble/TruncateDoubleUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/truncatedouble/TruncateDoubleUnitTest.java new file mode 100644 index 0000000000..d5881c5d66 --- /dev/null +++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/truncatedouble/TruncateDoubleUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.truncatedouble; + +import static org.junit.Assert.assertEquals; + +import java.math.BigDecimal; +import java.math.RoundingMode; +import java.text.DecimalFormat; +import java.text.NumberFormat; + +import org.junit.Test; + +public class TruncateDoubleUnitTest { + + @Test + public void givenADouble_whenUsingDecimalFormat_truncateToTwoDecimalPlaces() { + DecimalFormat df = new DecimalFormat("#.##"); + df.setRoundingMode(RoundingMode.DOWN); + + double value = 1.55555555; + String truncated = df.format(value); + assertEquals("1.55", truncated); + + double negativeValue = -1.55555555; + String negativeTruncated = df.format(negativeValue); + assertEquals("-1.55", negativeTruncated); + } + + @Test + public void givenADouble_whenUsingNumberFormat_truncateToTwoDecimalPlaces() { + NumberFormat nf = NumberFormat.getNumberInstance(); + nf.setMaximumFractionDigits(2); + nf.setRoundingMode(RoundingMode.DOWN); + + double value = 1.55555555; + String truncated = nf.format(value); + assertEquals("1.55", truncated); + + double negativeValue = -1.55555555; + String negativeTruncated = nf.format(negativeValue); + assertEquals("-1.55", negativeTruncated); + } + + @Test + public void givenADouble_whenUsingBigDecimal_truncateToTwoDecimalPlaces() { + BigDecimal positive = new BigDecimal(2.555555).setScale(2, RoundingMode.DOWN); + BigDecimal negative = new BigDecimal(-2.555555).setScale(2, RoundingMode.DOWN); + assertEquals("2.55", positive.toString()); + assertEquals("-2.55", negative.toString()); + } + + @Test + public void givenADouble_whenUsingMath_truncateToTwoDecimalPlaces() { + double positive = 1.55555555; + double truncated = Math.floor(positive * 100) / 100; + assertEquals("1.55", String.valueOf(truncated)); + + double negative = -1.55555555; + double negativeTruncated = Math.ceil(negative * 100) / 100; + assertEquals("-1.55", String.valueOf(negativeTruncated)); + } + + @Test + public void givenADouble_whenUsingStringFormat_truncateToTwoDecimalPlaces() { + double value = 1.55555555; + String truncated = String.format("%.2f", value); + assertEquals("1.56", truncated); + } + +} From 5f016b6220a57fb1c777c0aaf5fe0e4263ff9656 Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Sat, 30 Sep 2023 13:11:57 +0100 Subject: [PATCH 004/108] Create HttpSecurityConfig.java --- .../HttpSecurityConfig.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java new file mode 100644 index 0000000000..19ffa2fdb3 --- /dev/null +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java @@ -0,0 +1,32 @@ +package com.baeldung.httpsecurityvswebsecurity; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class HttpSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + // Given: HttpSecurity configured + + http + .authorizeRequests() + .antMatchers("/public/**").permitAll() + .antMatchers("/admin/**").hasRole("ADMIN") + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login") + .permitAll() + .and() + .logout() + .permitAll(); + + // When: Accessing specific URLs + // Then: Access is granted based on defined rules + } +} From 9058fad8226ae8645b5a35fe950a42773623e8f7 Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Sat, 30 Sep 2023 13:14:08 +0100 Subject: [PATCH 005/108] Create WebSecurityConfig.java --- .../WebSecurityConfig.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java new file mode 100644 index 0000000000..11b740c744 --- /dev/null +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java @@ -0,0 +1,31 @@ +package com.baeldung.httpsecurityvswebsecurity; + +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; + +@Configuration +public class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Autowired + private UserDetailsService userDetailsService; + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/").permitAll() + .anyRequest().authenticated() + .and() + .formLogin(); + } +} From 54469285479cc1cd2da23f345b47a33f415f032d Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Sat, 30 Sep 2023 13:15:37 +0100 Subject: [PATCH 006/108] Update pom.xml add necessary dependencies --- spring-security-modules/spring-security-core/pom.xml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/spring-security-modules/spring-security-core/pom.xml b/spring-security-modules/spring-security-core/pom.xml index 0eb70c0853..d8f2ce7dc9 100644 --- a/spring-security-modules/spring-security-core/pom.xml +++ b/spring-security-modules/spring-security-core/pom.xml @@ -49,6 +49,16 @@ org.springframework.security spring-security-test + + org.springframework.security + spring-security-web + 5.8.4 + + + org.springframework.security + spring-security-core + 5.8.4 + @@ -100,4 +110,4 @@ - \ No newline at end of file + From af8cd8080f8558523b0c1ccda8886840da75d0bc Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sat, 7 Oct 2023 01:28:02 +0300 Subject: [PATCH 007/108] [JAVA-25958] Upgraded jackson-dataformat-xml version to 2.15.2 --- jackson-simple/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml index d01c43dc90..3bf523bbfa 100644 --- a/jackson-simple/pom.xml +++ b/jackson-simple/pom.xml @@ -33,7 +33,7 @@ - 2.14.2 + 2.15.2 17 From 1b1ba05a505ab99243ebf2aebfde9cb2ebc94c95 Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Sat, 7 Oct 2023 12:44:06 +0100 Subject: [PATCH 008/108] Update HttpSecurityConfig.java --- .../httpsecurityvswebsecurity/HttpSecurityConfig.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java index 19ffa2fdb3..bfa8fa8633 100644 --- a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java @@ -14,16 +14,16 @@ public class HttpSecurityConfig extends WebSecurityConfigurerAdapter { // Given: HttpSecurity configured http - .authorizeRequests() + .authorizeRequests() .antMatchers("/public/**").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() - .and() - .formLogin() + .and() + .formLogin() .loginPage("/login") .permitAll() - .and() - .logout() + .and() + .logout() .permitAll(); // When: Accessing specific URLs From 8177e7430718f3350234bff68cabbd738358673b Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Sat, 7 Oct 2023 12:49:07 +0100 Subject: [PATCH 009/108] Update WebSecurityConfig.java --- .../httpsecurityvswebsecurity/WebSecurityConfig.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java index 11b740c744..9d0a3cfb55 100644 --- a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java @@ -17,15 +17,18 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); + auth + .userDetailsService(userDetailsService) + .passwordEncoder(new BCryptPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() + http + .authorizeRequests() .antMatchers("/").permitAll() .anyRequest().authenticated() - .and() - .formLogin(); + .and() + .formLogin(); } } From 05f4487d6357ebfc6eb017b026483876a9e6bd02 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Sun, 8 Oct 2023 05:12:47 +0700 Subject: [PATCH 010/108] [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 011/108] 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 012/108] 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 013/108] [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 0e8c249abdd8e34d0f7d4c77bd9750431bfdaa8a Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Mon, 9 Oct 2023 20:53:04 +0100 Subject: [PATCH 014/108] Update pom.xml --- spring-security-modules/spring-security-core/pom.xml | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/spring-security-modules/spring-security-core/pom.xml b/spring-security-modules/spring-security-core/pom.xml index d8f2ce7dc9..03d7030057 100644 --- a/spring-security-modules/spring-security-core/pom.xml +++ b/spring-security-modules/spring-security-core/pom.xml @@ -49,16 +49,6 @@ org.springframework.security spring-security-test - - org.springframework.security - spring-security-web - 5.8.4 - - - org.springframework.security - spring-security-core - 5.8.4 - From 7fcd8a271b2a7a4beda65d0b0368a5eed6144298 Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Mon, 9 Oct 2023 20:53:46 +0100 Subject: [PATCH 015/108] Update pom.xml --- .../spring-security-core-2/pom.xml | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/spring-security-modules/spring-security-core-2/pom.xml b/spring-security-modules/spring-security-core-2/pom.xml index e540d7bc01..55eaf262df 100644 --- a/spring-security-modules/spring-security-core-2/pom.xml +++ b/spring-security-modules/spring-security-core-2/pom.xml @@ -49,6 +49,16 @@ org.springframework.security spring-security-test + + org.springframework.security + spring-security-web + 5.8.4 + + + org.springframework.security + spring-security-core + 5.8.4 + @@ -100,4 +110,4 @@ - \ No newline at end of file + From ad0932acd1151d3b302f9671e293bc98ee330ee9 Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Mon, 9 Oct 2023 20:57:03 +0100 Subject: [PATCH 016/108] Rename HttpSecurityConfig.java to HttpSecurityConfig.java --- .../baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename spring-security-modules/{spring-security-core => spring-security-core-2}/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java (100%) diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java similarity index 100% rename from spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java rename to spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java From 4eb6c11b4034bbe798adb74d743198e5ea3b5592 Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Mon, 9 Oct 2023 20:59:22 +0100 Subject: [PATCH 017/108] Rename WebSecurityConfig.java to WebSecurityConfig.java --- .../com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename spring-security-modules/{spring-security-core => spring-security-core-2}/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java (100%) diff --git a/spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java similarity index 100% rename from spring-security-modules/spring-security-core/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java rename to spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java From d4d4a0e1a408eb9a2d9924101de37ab7919ec861 Mon Sep 17 00:00:00 2001 From: Sam Gardner Date: Wed, 11 Oct 2023 11:09:45 +0100 Subject: [PATCH 018/108] BAEL-6895 extend String format test to cover negatives --- .../baeldung/truncatedouble/TruncateDoubleUnitTest.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/truncatedouble/TruncateDoubleUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/truncatedouble/TruncateDoubleUnitTest.java index d5881c5d66..1bbca4069f 100644 --- a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/truncatedouble/TruncateDoubleUnitTest.java +++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/truncatedouble/TruncateDoubleUnitTest.java @@ -61,9 +61,13 @@ public class TruncateDoubleUnitTest { @Test public void givenADouble_whenUsingStringFormat_truncateToTwoDecimalPlaces() { - double value = 1.55555555; - String truncated = String.format("%.2f", value); + double positive = 1.55555555; + String truncated = String.format("%.2f", positive); assertEquals("1.56", truncated); + + double negative = -1.55555555; + String negativeTruncated = String.format("%.2f", negative); + assertEquals("-1.56", negativeTruncated); } } From 06943519f841b3cb0fb3ef07348921e7528d0a02 Mon Sep 17 00:00:00 2001 From: "emanuel.trandafir" Date: Sat, 14 Oct 2023 13:06:31 +0200 Subject: [PATCH 019/108] BAEL-7001: retry RetryCompletableFuture --- .../retry/RetryCompletableFuture.java | 63 +++++++++ .../retry/RetryCompletableFutureUnitTest.java | 125 ++++++++++++++++++ 2 files changed, 188 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java new file mode 100644 index 0000000000..41f1309311 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java @@ -0,0 +1,63 @@ +package com.baeldung.concurrent.completablefuture.retry; + +import java.util.concurrent.CompletableFuture; +import java.util.function.Function; +import java.util.function.Supplier; + +public class RetryCompletableFuture { + public static CompletableFuture retryTask(Supplier supplier, int maxRetries) { + Supplier retryableSupplier = retryFunction(supplier, maxRetries); + return CompletableFuture.supplyAsync(retryableSupplier); + } + + static Supplier retryFunction(Supplier supplier, int maxRetries) { + return () -> { + int retries = 0; + while (retries < maxRetries) { + try { + return supplier.get(); + } catch (Exception e) { + retries++; + } + } + throw new IllegalStateException(String.format("Task failed after %s attempts", maxRetries)); + }; + } + + public static CompletableFuture retryUnsafe(Supplier supplier, int maxRetries) { + CompletableFuture cf = CompletableFuture.supplyAsync(supplier); + sleep(100l); + for (int i = 0; i < maxRetries; i++) { + cf = cf.exceptionally(__ -> supplier.get()); + } + return cf; + } + + public static CompletableFuture retryNesting(Supplier supplier, int maxRetries) { + CompletableFuture cf = CompletableFuture.supplyAsync(supplier); + sleep(100); + for (int i = 0; i < maxRetries; i++) { + cf = cf.thenApply(CompletableFuture::completedFuture) + .exceptionally(__ -> CompletableFuture.supplyAsync(supplier)) + .thenCompose(Function.identity()); + } + return cf; + } + + public static CompletableFuture retryExceptionallyAsync(Supplier supplier, int maxRetries) { + CompletableFuture cf = CompletableFuture.supplyAsync(supplier); + sleep(100); + for (int i = 0; i < maxRetries; i++) { + cf = cf.exceptionallyAsync(__ -> supplier.get()); + } + return cf; + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java new file mode 100644 index 0000000000..b48039d4a6 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java @@ -0,0 +1,125 @@ +package com.baeldung.concurrent.completablefuture.retry; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +class RetryCompletableFutureUnitTest { + private AtomicInteger retriesCounter = new AtomicInteger(0); + + @BeforeEach + void beforeEach() { + retriesCounter.set(0); + } + + @Test + void whenRetryingTask_thenReturnsCorrectlyAfterFourInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryTask(codeToRun, 10); + + assertThat(result.join()) + .isEqualTo(100); + assertThat(retriesCounter) + .hasValue(4); + } + + @Test + void whenRetryingTask_thenThrowsExceptionAfterThreeInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryTask(codeToRun, 3); + + assertThatThrownBy(result::join) + .isInstanceOf(CompletionException.class) + .hasMessageContaining("IllegalStateException: Task failed after 3 attempts"); + } + + @Test + void whenRetryingExceptionally_thenReturnsCorrectlyAfterFourInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryUnsafe(codeToRun, 10); + + assertThat(result.join()) + .isEqualTo(100); + assertThat(retriesCounter) + .hasValue(4); + } + + @Test + void whenRetryingExceptionally_thenThrowsExceptionAfterThreeInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryUnsafe(codeToRun, 3); + + assertThatThrownBy(result::join) + .isInstanceOf(CompletionException.class) + .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); + } + + @Test + void whenRetryingExceptionallyAsync_thenReturnsCorrectlyAfterFourInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryExceptionallyAsync(codeToRun, 10); + + assertThat(result.join()) + .isEqualTo(100); + assertThat(retriesCounter) + .hasValue(4); + } + + @Test + void whenRetryingExceptionallyAsync_thenThrowsExceptionAfterThreeInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryExceptionallyAsync(codeToRun, 3); + + assertThatThrownBy(result::join) + .isInstanceOf(CompletionException.class) + .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); + } + + @Test + void whenRetryingNesting_thenReturnsCorrectlyAfterFourInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryNesting(codeToRun, 10); + + assertThat(result.join()) + .isEqualTo(100); + assertThat(retriesCounter) + .hasValue(4); + } + + @Test + void whenRetryingNesting_thenThrowsExceptionAfterThreeInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); + + CompletableFuture result = retryNesting(codeToRun, 3); + + assertThatThrownBy(result::join) + .isInstanceOf(CompletionException.class) + .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); + } + + int failFourTimesThenReturn(int returnValue) { + int retryNr = retriesCounter.get(); + System.out.println(String.format("invocation: %s, thread: %s", retryNr, Thread.currentThread().getName())); + if (retryNr < 4) { + retriesCounter.set(retryNr + 1); + throw new RuntimeException(String.format("task failed for %s time(s)", retryNr)); + } + return returnValue; + } + +} From 9fcdc43c5c6b66b9fe134fafaa30786d0c605faf Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Sat, 14 Oct 2023 21:45:28 +0100 Subject: [PATCH 020/108] Update pom.xml --- spring-security-modules/spring-security-core-2/pom.xml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/spring-security-modules/spring-security-core-2/pom.xml b/spring-security-modules/spring-security-core-2/pom.xml index 55eaf262df..5d77098869 100644 --- a/spring-security-modules/spring-security-core-2/pom.xml +++ b/spring-security-modules/spring-security-core-2/pom.xml @@ -15,6 +15,10 @@ ../../parent-boot-2 + + 5.8.4 + + org.springframework.boot @@ -52,12 +56,12 @@ org.springframework.security spring-security-web - 5.8.4 + ${spring.security.version} org.springframework.security spring-security-core - 5.8.4 + ${spring.security.version} From 4fb3cb257717e61b8c37327fc760dedffea058b3 Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Sat, 14 Oct 2023 21:49:30 +0100 Subject: [PATCH 021/108] Update HttpSecurityConfig.java --- .../HttpSecurityConfig.java | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java index bfa8fa8633..47c4c8de4c 100644 --- a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java @@ -13,18 +13,17 @@ public class HttpSecurityConfig extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { // Given: HttpSecurity configured - http - .authorizeRequests() - .antMatchers("/public/**").permitAll() - .antMatchers("/admin/**").hasRole("ADMIN") - .anyRequest().authenticated() + http.authorizeRequests() + .antMatchers("/public/**").permitAll() + .antMatchers("/admin/**").hasRole("ADMIN") + .anyRequest().authenticated() .and() .formLogin() - .loginPage("/login") - .permitAll() + .loginPage("/login") + .permitAll() .and() .logout() - .permitAll(); + .permitAll(); // When: Accessing specific URLs // Then: Access is granted based on defined rules From 0bbc9163f9f301ba43f99da5d64ce69069d3a467 Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Sat, 14 Oct 2023 21:50:59 +0100 Subject: [PATCH 022/108] Update WebSecurityConfig.java --- .../WebSecurityConfig.java | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java index 9d0a3cfb55..702becbf06 100644 --- a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java @@ -18,16 +18,17 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth - .userDetailsService(userDetailsService) - .passwordEncoder(new BCryptPasswordEncoder()); + .userDetailsService(userDetailsService) + .passwordEncoder(new BCryptPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .antMatchers("/").permitAll() - .anyRequest().authenticated() + http.authorizeRequests() + .antMatchers("/") + .permitAll() + .anyRequest() + .authenticated() .and() .formLogin(); } From fcb0f98b92680f12d24f5c83e3a7dcb6ece26bbf Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Sun, 15 Oct 2023 19:25:42 +0300 Subject: [PATCH 023/108] [JAVA-25997] Clean up --- spring-core-2/pom.xml | 4 +- spring-core-4/pom.xml | 4 +- spring-credhub/pom.xml | 5 +- spring-ejb-modules/ejb-beans/pom.xml | 8 +-- spring-kafka-2/pom.xml | 3 +- spring-kafka/pom.xml | 6 +- spring-katharsis/pom.xml | 4 +- spring-mobile/pom.xml | 8 --- spring-pulsar/pom.xml | 6 +- .../spring-5-reactive/pom.xml | 3 +- .../spring-reactive-data-2/pom.xml | 12 ++-- .../spring-reactive-security/pom.xml | 8 +-- spring-remoting-modules/pom.xml | 6 -- spring-shell/pom.xml | 1 - spring-soap/pom.xml | 9 ++- .../pom.xml | 15 +++-- .../pom.xml | 61 +++++++++++-------- .../spring-swagger-codegen-api-client/pom.xml | 15 ++--- spring-vault/pom.xml | 10 +-- 19 files changed, 102 insertions(+), 86 deletions(-) diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index f6142cffb0..2d11cc2124 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -149,7 +149,7 @@ org.apache.maven.plugins maven-war-plugin - ${maven.version} + ${maven-war-plugin.version} false @@ -166,7 +166,7 @@ 3.6 2.1.0 3.22.0-GA - 3.2.2 + 3.2.2 \ No newline at end of file diff --git a/spring-core-4/pom.xml b/spring-core-4/pom.xml index 2d11cc701b..fb544e29fd 100644 --- a/spring-core-4/pom.xml +++ b/spring-core-4/pom.xml @@ -74,7 +74,7 @@ org.apache.commons commons-text - ${apache-commons-text.version} + ${commons-text.version} @@ -84,7 +84,7 @@ 4.0.2 4.0.0 1.3.2 - 1.10.0 + 1.10.0 \ No newline at end of file diff --git a/spring-credhub/pom.xml b/spring-credhub/pom.xml index 4604833d0b..defe378b6b 100644 --- a/spring-credhub/pom.xml +++ b/spring-credhub/pom.xml @@ -27,7 +27,7 @@ org.springframework.credhub spring-credhub-starter - 2.2.0 + ${spring-credhub-starter.version} com.google.code.gson @@ -36,8 +36,7 @@ - 8 - 8 + 2.2.0 UTF-8 diff --git a/spring-ejb-modules/ejb-beans/pom.xml b/spring-ejb-modules/ejb-beans/pom.xml index 6bfbb42a14..94f7963ad6 100644 --- a/spring-ejb-modules/ejb-beans/pom.xml +++ b/spring-ejb-modules/ejb-beans/pom.xml @@ -66,12 +66,12 @@ org.apache.activemq activemq-broker - ${activemq.broker.version} + ${activemq-broker.version} org.apache.activemq.tooling activemq-junit - ${activemq.junit.version} + ${activemq-junit.version} test @@ -187,8 +187,8 @@ 8.2.1.Final 3.2 5.2.3.RELEASE - 5.16.3 - 5.16.3 + 5.16.3 + 5.16.3 2.21.0 2.8 8.2.1.Final diff --git a/spring-kafka-2/pom.xml b/spring-kafka-2/pom.xml index 76a82f6000..2aa657d3d8 100644 --- a/spring-kafka-2/pom.xml +++ b/spring-kafka-2/pom.xml @@ -53,7 +53,7 @@ org.testcontainers junit-jupiter - ${testcontainers-kafka.version} + ${testcontainers-junit-jupiter.version} test @@ -65,6 +65,7 @@ 1.16.2 + 1.16.2 \ No newline at end of file diff --git a/spring-kafka/pom.xml b/spring-kafka/pom.xml index c013be32e3..7ff7a9710a 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -26,12 +26,12 @@ org.springframework.boot spring-boot-starter-actuator - 3.0.5 + ${spring-boot-starter-actuator.version} io.micrometer micrometer-registry-prometheus - 1.10.5 + ${micrometer-registry-prometheus.version} org.springframework.kafka @@ -90,6 +90,8 @@ + 3.0.5 + 1.10.5 1.16.2 diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index b836a42bca..595cde5109 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -33,7 +33,7 @@ io.katharsis katharsis-spring - ${katharsis.version} + ${katharsis-spring.version} org.apache.commons @@ -132,7 +132,7 @@ - 3.0.2 + 3.0.2 0.9.10 1.6.1 diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index f810159eb7..d96faf3274 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -37,24 +37,16 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - 1.1.5.RELEASE - 11 - 11 \ No newline at end of file diff --git a/spring-pulsar/pom.xml b/spring-pulsar/pom.xml index df1959c84e..05debcab1c 100644 --- a/spring-pulsar/pom.xml +++ b/spring-pulsar/pom.xml @@ -27,7 +27,7 @@ org.springframework.pulsar spring-pulsar-spring-boot-starter - 0.2.0 + ${spring-pulsar-spring-boot-starter.version} @@ -46,4 +46,8 @@ + + 0.2.0 + + diff --git a/spring-reactive-modules/spring-5-reactive/pom.xml b/spring-reactive-modules/spring-5-reactive/pom.xml index fd47c70a07..da04f2c0ca 100644 --- a/spring-reactive-modules/spring-5-reactive/pom.xml +++ b/spring-reactive-modules/spring-5-reactive/pom.xml @@ -124,7 +124,7 @@ maven-resources-plugin - 3.0.1 + ${maven-resources-plugin.version} copy-resources @@ -159,6 +159,7 @@ 1.1.3 1.0 1.0 + 3.0.1 \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-data-2/pom.xml b/spring-reactive-modules/spring-reactive-data-2/pom.xml index 64ce278973..47662a2c2e 100644 --- a/spring-reactive-modules/spring-reactive-data-2/pom.xml +++ b/spring-reactive-modules/spring-reactive-data-2/pom.xml @@ -13,10 +13,6 @@ 1.0.0-SNAPSHOT - - UTF-8 - - org.springframework.boot @@ -62,8 +58,14 @@ javax.validation validation-api - 2.0.1.Final + ${validation-api.version} + + + 2.0.1.Final + UTF-8 + + \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-security/pom.xml b/spring-reactive-modules/spring-reactive-security/pom.xml index 8ed976c572..956153b49a 100644 --- a/spring-reactive-modules/spring-reactive-security/pom.xml +++ b/spring-reactive-modules/spring-reactive-security/pom.xml @@ -80,12 +80,12 @@ io.reactivex.rxjava2 rxjava - ${rxjava-version} + ${rxjava.version} io.projectreactor reactor-test - ${project-reactor-test} + ${project-reactor-test.version} test @@ -114,11 +114,11 @@ 1.0.1.RELEASE - 2.1.12 + 2.1.12 1.1.3 1.0 1.0 - 3.1.6.RELEASE + 3.1.6.RELEASE \ No newline at end of file diff --git a/spring-remoting-modules/pom.xml b/spring-remoting-modules/pom.xml index 41d77c2969..8a5990fd1d 100644 --- a/spring-remoting-modules/pom.xml +++ b/spring-remoting-modules/pom.xml @@ -43,16 +43,10 @@ org.apache.maven.plugins maven-compiler-plugin ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - 11 - 11 \ No newline at end of file diff --git a/spring-shell/pom.xml b/spring-shell/pom.xml index 952920fd1e..24fe5b0fb6 100644 --- a/spring-shell/pom.xml +++ b/spring-shell/pom.xml @@ -28,7 +28,6 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} src/main/webapp false diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index 594eb3dd19..6c49f1f39c 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/pom.xml @@ -34,7 +34,7 @@ jakarta.xml.bind jakarta.xml.bind-api - 4.0.0 + ${jakarta.xml.bind-api.version} @@ -58,7 +58,7 @@ org.codehaus.mojo jaxb2-maven-plugin - 3.1.0 + ${jaxb2-maven-plugin.version} xjc @@ -79,7 +79,7 @@ org.jvnet.jaxb2.maven2 maven-jaxb2-plugin - 0.15.3 + ${maven-jaxb2-plugin.version} @@ -103,5 +103,8 @@ 17 + 4.0.0 + 3.1.0 + 0.15.3 \ No newline at end of file diff --git a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml index c529951b07..b57a014a8f 100644 --- a/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml +++ b/spring-swagger-codegen/custom-validations-opeanpi-codegen/pom.xml @@ -29,22 +29,22 @@ org.hibernate hibernate-validator - 6.0.10.Final + ${hibernate-validator.version} javax.validation validation-api - 2.0.1.Final + ${validation-api.version} org.openapitools openapi-generator - 3.3.4 + ${openapi-generator.version} com.fasterxml.jackson.core jackson-databind - 2.10.0.pr3 + ${jackson-databind.version} org.springdoc @@ -62,7 +62,7 @@ org.openapitools openapi-generator-maven-plugin - 5.1.0 + ${openapi-generator-maven-plugin.version} @@ -97,6 +97,11 @@ 3.0.0 2.17.1 1.7.0 + 6.0.10.Final + 2.0.1.Final + 3.3.4 + 2.10.0.pr3 + 5.1.0 \ No newline at end of file diff --git a/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml index f125018fb0..ee2c86238a 100644 --- a/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml +++ b/spring-swagger-codegen/spring-openapi-generator-api-client/pom.xml @@ -34,55 +34,55 @@ io.swagger swagger-annotations - ${swagger-annotations-version} + ${swagger-annotations.version} com.google.code.findbugs jsr305 - 3.0.2 + ${findbugs-jsr305.version} org.springframework spring-web - ${spring-web-version} + ${spring-web.version} com.fasterxml.jackson.core jackson-core - ${jackson-version} + ${jackson.version} com.fasterxml.jackson.core jackson-annotations - ${jackson-version} + ${jackson.version} com.fasterxml.jackson.core jackson-databind - ${jackson-version} + ${jackson.version} com.fasterxml.jackson.jaxrs jackson-jaxrs-json-provider - ${jackson-version} + ${jackson.version} org.openapitools jackson-databind-nullable - ${jackson-databind-nullable-version} + ${jackson-databind-nullable.version} com.fasterxml.jackson.datatype jackson-datatype-jsr310 - ${jackson-version} + ${jackson.version} com.github.joschi.jackson jackson-datatype-threetenbp - ${jackson-threetenbp-version} + ${jackson-threetenbp.version} @@ -94,7 +94,7 @@ javax.annotation javax.annotation-api - 1.3.2 + ${javax.annotation-api.version} @@ -103,7 +103,7 @@ org.apache.maven.plugins maven-enforcer-plugin - 3.0.0-M1 + ${maven-enforcer-plugin.version} enforce-maven @@ -123,7 +123,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.12 + ${maven-surefire-plugin.version} @@ -154,7 +154,7 @@ org.apache.maven.plugins maven-jar-plugin - 2.2 + ${maven-jar-plugin.version} @@ -169,7 +169,7 @@ org.codehaus.mojo build-helper-maven-plugin - 1.10 + ${build-helper-maven-plugin.version} add_sources @@ -200,7 +200,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.6.1 + ${maven-compiler-plugin.version} 1.8 1.8 @@ -209,7 +209,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.10.4 + ${maven-javadoc-plugin.version} attach-javadocs @@ -222,7 +222,7 @@ org.apache.maven.plugins maven-source-plugin - 2.2.1 + ${maven-source-plugin.version} attach-sources @@ -243,7 +243,7 @@ org.apache.maven.plugins maven-gpg-plugin - 1.5 + ${maven-gpg-plugin.version} sign-artifacts @@ -260,14 +260,25 @@ - 1.5.22 - 4.3.9.RELEASE - 2.11.1 + 1.5.22 + 4.3.9.RELEASE + 3.0.2 + 2.11.1 - 0.2.1 - 2.9.10 - 1.0.0 + 0.2.1 + 2.9.10 + 1.0.0 5.8.1 + 1.3.2 + + 3.0.0-M1 + 2.12 + 2.2 + 1.10 + 3.6.1 + 2.10.4 + 2.2.1 + 1.5 \ No newline at end of file diff --git a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml index b2e97c7a49..35f4978411 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml +++ b/spring-swagger-codegen/spring-swagger-codegen-api-client/pom.xml @@ -40,13 +40,13 @@ io.swagger swagger-annotations - ${swagger-annotations-version} + ${swagger-annotations.version} org.springframework spring-web - ${spring-web-version} + ${spring-web.version} @@ -77,12 +77,12 @@ joda-time joda-time - ${jodatime-version} + ${jodatime.version} javax.annotation javax.annotation-api - 1.3.2 + ${javax.annotation-api.version} @@ -189,9 +189,10 @@ - 1.5.15 - 4.3.9.RELEASE - 2.9.9 + 1.5.15 + 4.3.9.RELEASE + 2.9.9 + 1.3.2 2.2 1.5 2.2.1 diff --git a/spring-vault/pom.xml b/spring-vault/pom.xml index 60a5ee18f2..dba6a02e4e 100644 --- a/spring-vault/pom.xml +++ b/spring-vault/pom.xml @@ -36,7 +36,7 @@ org.springframework.vault spring-vault-core - ${spring.vault.core.version} + ${spring-vault-core.version} org.springframework.data @@ -69,18 +69,20 @@ software.amazon.awssdk auth - 2.20.140 + ${auth.version} org.springframework.cloud spring-cloud-starter-vault-config - 3.1.3 + ${spring-cloud-starter-vault-config.version}3.1.3 - 2.3.4 + 2.3.4 + 2.20.140 + 3.1.3 17 From 7e924cefe4a2bb82bd54100095ed2e486e238196 Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Mon, 16 Oct 2023 17:31:19 +0700 Subject: [PATCH 024/108] [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 025/108] [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 459d92fae64464fdfc450a4d73f7a2558eec228f Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Mon, 16 Oct 2023 22:57:25 +0300 Subject: [PATCH 026/108] [JAVA-25997] Fixed typo --- spring-kafka-2/pom.xml | 2 +- spring-vault/pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-kafka-2/pom.xml b/spring-kafka-2/pom.xml index 2aa657d3d8..0bca20447d 100644 --- a/spring-kafka-2/pom.xml +++ b/spring-kafka-2/pom.xml @@ -65,7 +65,7 @@ 1.16.2 - 1.16.2 + 1.16.2 \ No newline at end of file diff --git a/spring-vault/pom.xml b/spring-vault/pom.xml index dba6a02e4e..e8257125bc 100644 --- a/spring-vault/pom.xml +++ b/spring-vault/pom.xml @@ -80,7 +80,7 @@ - 2.3.4 + 2.3.4 2.20.140 3.1.3 17 From 2efe2c7987e399c75e52c0eb528e47a81838ed4d Mon Sep 17 00:00:00 2001 From: "@hangga" Date: Tue, 17 Oct 2023 13:50:31 +0700 Subject: [PATCH 027/108] 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 028/108] 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 029/108] 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 030/108] [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 031/108] [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 032/108] 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 033/108] 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 034/108] 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 0945fde3dd304c82ada8082c056675d5dc4e77fb Mon Sep 17 00:00:00 2001 From: panos-kakos Date: Fri, 20 Oct 2023 15:59:37 +0300 Subject: [PATCH 035/108] [JAVA-25997] Fixed typo --- spring-vault/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-vault/pom.xml b/spring-vault/pom.xml index e8257125bc..b3690c7b7f 100644 --- a/spring-vault/pom.xml +++ b/spring-vault/pom.xml @@ -75,7 +75,7 @@ org.springframework.cloud spring-cloud-starter-vault-config - ${spring-cloud-starter-vault-config.version}3.1.3 + ${spring-cloud-starter-vault-config.version} From 1a7d3aff21733046c7fc019e1c3da01c3b9a87a8 Mon Sep 17 00:00:00 2001 From: timis1 Date: Sat, 21 Oct 2023 20:10:35 +0300 Subject: [PATCH 036/108] 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 b17ab69f4d06ff9347ae9a778d08b86358f7fcb2 Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Sat, 21 Oct 2023 19:15:13 +0100 Subject: [PATCH 037/108] Update HttpSecurityConfig.java --- .../HttpSecurityConfig.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java index 47c4c8de4c..d6361255e5 100644 --- a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/HttpSecurityConfig.java @@ -14,16 +14,16 @@ public class HttpSecurityConfig extends WebSecurityConfigurerAdapter { // Given: HttpSecurity configured http.authorizeRequests() - .antMatchers("/public/**").permitAll() - .antMatchers("/admin/**").hasRole("ADMIN") - .anyRequest().authenticated() - .and() - .formLogin() - .loginPage("/login") - .permitAll() - .and() - .logout() - .permitAll(); + .antMatchers("/public/**").permitAll() + .antMatchers("/admin/**").hasRole("ADMIN") + .anyRequest().authenticated() + .and() + .formLogin() + .loginPage("/login") + .permitAll() + .and() + .logout() + .permitAll(); // When: Accessing specific URLs // Then: Access is granted based on defined rules From 643da8039189ef8cf586c0af647f28df4c87681b Mon Sep 17 00:00:00 2001 From: Rufina Uche <102101377+Finniki@users.noreply.github.com> Date: Sat, 21 Oct 2023 19:17:05 +0100 Subject: [PATCH 038/108] Update WebSecurityConfig.java --- .../httpsecurityvswebsecurity/WebSecurityConfig.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java index 702becbf06..46a82918aa 100644 --- a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/httpsecurityvswebsecurity/WebSecurityConfig.java @@ -25,11 +25,11 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() - .antMatchers("/") - .permitAll() - .anyRequest() - .authenticated() - .and() - .formLogin(); + .antMatchers("/") + .permitAll() + .anyRequest() + .authenticated() + .and() + .formLogin(); } } From 4cd426bb149c68448547c08622bf29e6f00887a7 Mon Sep 17 00:00:00 2001 From: Thibault Faure Date: Thu, 12 Oct 2023 20:52:32 +0200 Subject: [PATCH 039/108] BAEL-7107 Code for the article Arrays mismatch method in Java --- .../README.md | 5 + .../pom.xml | 16 ++ .../array/mismatch/ArrayMismatchUnitTest.java | 269 ++++++++++++++++++ core-java-modules/pom.xml | 1 + 4 files changed, 291 insertions(+) create mode 100644 core-java-modules/core-java-arrays-operations-basic-2/README.md create mode 100644 core-java-modules/core-java-arrays-operations-basic-2/pom.xml create mode 100644 core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/mismatch/ArrayMismatchUnitTest.java 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 new file mode 100644 index 0000000000..da2f17111f --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic-2/README.md @@ -0,0 +1,5 @@ +## Core Java Arrays - Basic Operations + +This module contains articles about Java array fundamentals. They assume no previous background knowledge on working with arrays. + +### Relevant Articles: diff --git a/core-java-modules/core-java-arrays-operations-basic-2/pom.xml b/core-java-modules/core-java-arrays-operations-basic-2/pom.xml new file mode 100644 index 0000000000..7257a39462 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic-2/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + core-java-arrays-operations-basic-2 + core-java-arrays-operations-basic-2 + jar + + + core-java-modules + com.baeldung.core-java-modules + 0.0.1-SNAPSHOT + + + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/mismatch/ArrayMismatchUnitTest.java b/core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/mismatch/ArrayMismatchUnitTest.java new file mode 100644 index 0000000000..464221efd0 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic-2/src/test/java/com/baeldung/array/mismatch/ArrayMismatchUnitTest.java @@ -0,0 +1,269 @@ +package com.baeldung.array.mismatch; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Arrays; +import java.util.Comparator; + +import org.junit.jupiter.api.Test; + +class ArrayMismatchUnitTest { + + @Test + void givenTwoArraysWithACommonPrefix_whenMismatch_thenIndexOfFirstMismatch() { + int[] firstArray = {1, 2, 3, 4, 5}; + int[] secondArray = {1, 2, 3, 5, 8}; + assertEquals(3, Arrays.mismatch(firstArray, secondArray)); + } + + @Test + void givenTwoIdenticalArrays_whenMismatch_thenMinusOne() { + int[] firstArray = {1, 2, 3, 4, 5}; + int[] secondArray = {1, 2, 3, 4, 5}; + assertEquals(-1, Arrays.mismatch(firstArray, secondArray)); + } + + @Test + void givenFirstArrayIsAPrefixOfTheSecond_whenMismatch_thenFirstArrayLength() { + int[] firstArray = {1, 2, 3, 4, 5}; + int[] secondArray = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + assertEquals(firstArray.length, Arrays.mismatch(firstArray, secondArray)); + } + + @Test + void givenNoCommonPrefix_whenMismatch_thenZero() { + int[] firstArray = {1, 2, 3, 4, 5}; + int[] secondArray = {9, 8, 7}; + assertEquals(0, Arrays.mismatch(firstArray, secondArray)); + } + + @Test + void givenAtLeastANullArray_whenMismatch_thenThrowsNullPointerException() { + int[] firstArray = null; + int[] secondArray = {1, 2, 3, 4, 5}; + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, secondArray)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, firstArray)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, firstArray)); + } + + @Test + void givenExactlyOneAnEmptyArray_whenMismatch_thenZero() { + int[] firstArray = {}; + int[] secondArray = {1, 2, 3}; + assertEquals(0, Arrays.mismatch(firstArray, secondArray)); + assertEquals(0, Arrays.mismatch(secondArray, firstArray)); + } + + @Test + void givenTwoEmptyArrays_whenMismatch_thenMinusOne() { + assertEquals(-1, Arrays.mismatch(new int[] {}, new int[] {})); + } + + @Test + void givenTwoSubArraysWithACommonPrefix_whenMismatch_thenIndexOfFirstMismatch() { + int[] firstArray = {1, 2, 3, 4, 5}; + int[] secondArray = {0, 1, 2, 3, 5, 8}; + assertEquals(3, Arrays.mismatch(firstArray, 0, 4, secondArray, 1, 6)); + } + + @Test + void givenTwoIdenticalSubArrays_whenMismatch_thenMinusOne() { + int[] firstArray = {0, 0, 1, 2}; + int[] secondArray = {0, 1, 2, 3, 4}; + assertEquals(-1, Arrays.mismatch(firstArray, 2, 4, secondArray, 1, 3)); + } + + @Test + void givenFirstSubArrayIsAPrefixOfTheSecond_whenMismatch_thenFirstArrayLength() { + int[] firstArray = {2, 3, 4, 5, 4, 3, 2}; + int[] secondArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + assertEquals(4, Arrays.mismatch(firstArray, 0, 4, secondArray, 2, 9)); + } + + @Test + void givenNoCommonPrefixForSubArrays_whenMismatch_thenZero() { + int[] firstArray = {0, 0, 0, 0, 0}; + int[] secondArray = {9, 8, 7, 6, 5}; + assertEquals(0, Arrays.mismatch(firstArray, 1, 2, secondArray, 1, 2)); + } + + @Test + void givenAtLeastANullSubArray_whenMismatch_thenThrowsNullPointerException() { + int[] firstArray = null; + int[] secondArray = {1, 2, 3, 4, 5}; + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, 0, 1, secondArray, 0, 1)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, 0, 1, firstArray, 0, 1)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, 0, 1, firstArray, 0, 1)); + } + + @Test + void givenExactlyOneEmptySubArray_whenMismatch_thenZero() { + int[] firstArray = {1}; + int[] secondArray = {1, 2, 3}; + assertEquals(0, Arrays.mismatch(firstArray, 0, 0, secondArray, 0, 2)); + assertEquals(0, Arrays.mismatch(firstArray, 0, 1, secondArray, 2, 2)); + } + + @Test + void givenTwoEmptySubArrays_whenMismatch_thenMinusOne() { + int[] firstArray = {1}; + int[] secondArray = {1, 2, 3}; + assertEquals(-1, Arrays.mismatch(firstArray, 0, 0, secondArray, 2, 2)); + } + + @Test + void givenToIndexGreaterThanFromIndex_whenMismatch_thenThrowsIllegalArgumentException() { + int[] firstArray = {2, 3, 4, 5, 4, 3, 2}; + int[] secondArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 4, 2, secondArray, 0, 6)); + assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, 6, 0)); + } + + @Test + void givenIllegalIndexes_whenMismatch_thenThrowsArrayIndexOutOfBoundsException() { + int[] firstArray = {2, 3, 4, 5, 4, 3, 2}; + int[] secondArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, -1, 2, secondArray, 0, 6)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 0, 8, secondArray, 0, 6)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, -5, 0)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, 11, 12)); + } + + @Test + void givenTwoStringArraysAndAComparator_whenMismatch_thenIndexOfFirstMismatch() { + String[] firstArray = {"one", "two", "three"}; + String[] secondArray = {"ONE", "TWO", "FOUR"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(2, Arrays.mismatch(firstArray, secondArray, comparator)); + } + + @Test + void givenTwoIdenticalStringArraysForTheComparator_whenMismatch_thenMinusOne() { + String[] firstArray = {"one", "two", "three"}; + String[] secondArray = {"ONE", "TWO", "THREE"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(-1, Arrays.mismatch(firstArray, secondArray, comparator)); + } + + @Test + void givenFirstStringArrayIsAPrefixOfTheSecondForTheComparator_whenMismatch_thenFirstArrayLength() { + String[] firstArray = {"one", "two", "three"}; + String[] secondArray = {"ONE", "TWO", "THREE", "FOUR", "FIVE"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(firstArray.length, Arrays.mismatch(firstArray, secondArray, comparator)); + } + + @Test + void givenNoCommonPrefixForTheComparator_whenMismatch_thenZero() { + String[] firstArray = {"one", "two", "three"}; + String[] secondArray = {"six", "seven", "eight"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(0, Arrays.mismatch(firstArray, secondArray, comparator)); + } + + @Test + void givenAtLeastANullArrayOrNullComparator_whenMismatch_thenThrowsNullPointerException() { + String[] firstArray = null; + String[] secondArray = {"one"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, secondArray, comparator)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, firstArray, comparator)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, secondArray, null)); + } + + @Test + void givenExactlyOneAnEmptyArrayAndAComparator_whenMismatch_thenZero() { + String[] firstArray = {}; + String[] secondArray = {"one"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(0, Arrays.mismatch(firstArray, secondArray, comparator)); + assertEquals(0, Arrays.mismatch(secondArray, firstArray, comparator)); + } + + @Test + void givenTwoEmptyStringArraysForTheComparator_whenMismatch_thenMinusOne() { + assertEquals(-1, Arrays.mismatch(new String[] {}, new String[] {}, String.CASE_INSENSITIVE_ORDER)); + } + + @Test + void givenTwoStringSubarraysAndAComparator_whenMismatch_thenIndexOfFirstMismatch() { + String[] firstArray = {"one", "two", "three", "four"}; + String[] secondArray = {"ZERO", "ONE", "TWO", "FOUR", "EIGHT", "SIXTEEN"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(2, Arrays.mismatch(firstArray, 0, 4, secondArray, 1, 3, comparator)); + } + + @Test + void givenTwoIdenticalStringSubArraysForTheComparator_whenMismatch_thenMinusOne() { + String[] firstArray = {"zero", "zero", "one", "two"}; + String[] secondArray = {"zero", "one", "two", "three", "four"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(-1, Arrays.mismatch(firstArray, 2, 4, secondArray, 1, 3, comparator)); + } + + @Test + void givenFirstSubArrayIsAPrefixOfTheSecondForTheComparator_whenMismatch_thenFirstArrayLength() { + String[] firstArray = {"two", "three", "four", "five", "four", "three", "two"}; + String[] secondArray = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "EIGHT", "NINE", "TEN"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(4, Arrays.mismatch(firstArray, 0, 4, secondArray, 2, 9, comparator)); + } + + @Test + void givenNoCommonPrefixForSubArraysForTheComparator_whenMismatch_thenZero() { + String[] firstArray = {"zero", "one"}; + String[] secondArray = {"TEN", "ELEVEN", "TWELVE"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(0, Arrays.mismatch(firstArray, 1, 2, secondArray, 1, 2, comparator)); + } + + @Test + void givenAtLeastANullSubArrayOrNullComparator_whenMismatch_thenThrowsNullPointerException() { + String[] firstArray = null; + String[] secondArray = {"ONE", "TWO", "THREE", "FOUR", "FIVE"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, 0, 1, secondArray, 0, 1, comparator)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, 0, 1, firstArray, 0, 1, comparator)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(firstArray, 0, 1, firstArray, 0, 1, comparator)); + assertThrows(NullPointerException.class, () -> Arrays.mismatch(secondArray, 0, 1, secondArray, 0, 1, null)); + } + + @Test + void givenExactlyOneEmptySubArrayAndAComparator_whenMismatch_thenZero() { + String[] firstArray = {"one"}; + String[] secondArray = {"ONE", "TWO", "THREE"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(0, Arrays.mismatch(firstArray, 0, 0, secondArray, 0, 2, comparator)); + assertEquals(0, Arrays.mismatch(firstArray, 0, 1, secondArray, 2, 2, comparator)); + } + + @Test + void givenTwoEmptySubArraysAndAComparator_whenMismatch_thenMinusOne() { + String[] firstArray = {"one"}; + String[] secondArray = {"ONE", "TWO", "THREE"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertEquals(-1, Arrays.mismatch(firstArray, 0, 0, secondArray, 2, 2, comparator)); + } + + @Test + void givenToIndexGreaterThanFromIndexAndAComparator_whenMismatch_thenThrowsIllegalArgumentException() { + String[] firstArray = {"two", "three", "four", "five", "four", "three", "two"}; + String[] secondArray = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "EIGHT", "NINE", "TEN"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 4, 2, secondArray, 0, 6, comparator)); + assertThrows(IllegalArgumentException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, 6, 0, comparator)); + } + + @Test + void givenIllegalIndexesAndAComparator_whenMismatch_thenThrowsArrayIndexOutOfBoundsException() { + String[] firstArray = {"two", "three", "four", "five", "four", "three", "two"}; + String[] secondArray = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "EIGHT", "NINE", "TEN"}; + Comparator comparator = String.CASE_INSENSITIVE_ORDER; + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, -1, 2, secondArray, 0, 6, comparator)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 0, 8, secondArray, 0, 6, comparator)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, -5, 0, comparator)); + assertThrows(ArrayIndexOutOfBoundsException.class, () -> Arrays.mismatch(firstArray, 2, 3, secondArray, 11, 12, comparator)); + } + +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 2152b90bcb..bf5b90cd32 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -73,6 +73,7 @@ core-java-arrays-multidimensional core-java-arrays-convert core-java-arrays-operations-basic + core-java-arrays-operations-basic-2 core-java-arrays-operations-advanced core-java-arrays-operations-advanced-2 core-java-booleans From 7392b003f1cee2c312f29a17d1f46cb86aa0bcd9 Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Mon, 23 Oct 2023 14:33:05 +0530 Subject: [PATCH 040/108] 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 041/108] 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 042/108] 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 210eaf2c0b77fb1bd366cbd2040d5ac0376d81de Mon Sep 17 00:00:00 2001 From: emanueltrandafir1993 Date: Mon, 23 Oct 2023 18:07:43 +0200 Subject: [PATCH 043/108] BAEL-7001: fixed formatting --- .../retry/RetryCompletableFuture.java | 100 +++++----- .../retry/RetryCompletableFutureUnitTest.java | 176 +++++++++--------- 2 files changed, 139 insertions(+), 137 deletions(-) diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java index 41f1309311..a3df6b3624 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFuture.java @@ -5,59 +5,59 @@ import java.util.function.Function; import java.util.function.Supplier; public class RetryCompletableFuture { - public static CompletableFuture retryTask(Supplier supplier, int maxRetries) { - Supplier retryableSupplier = retryFunction(supplier, maxRetries); - return CompletableFuture.supplyAsync(retryableSupplier); - } + public static CompletableFuture retryTask(Supplier supplier, int maxRetries) { + Supplier retryableSupplier = retryFunction(supplier, maxRetries); + return CompletableFuture.supplyAsync(retryableSupplier); + } - static Supplier retryFunction(Supplier supplier, int maxRetries) { - return () -> { - int retries = 0; - while (retries < maxRetries) { - try { - return supplier.get(); - } catch (Exception e) { - retries++; - } - } - throw new IllegalStateException(String.format("Task failed after %s attempts", maxRetries)); - }; - } + static Supplier retryFunction(Supplier supplier, int maxRetries) { + return () -> { + int retries = 0; + while (retries < maxRetries) { + try { + return supplier.get(); + } catch (Exception e) { + retries++; + } + } + throw new IllegalStateException(String.format("Task failed after %s attempts", maxRetries)); + }; + } - public static CompletableFuture retryUnsafe(Supplier supplier, int maxRetries) { - CompletableFuture cf = CompletableFuture.supplyAsync(supplier); - sleep(100l); - for (int i = 0; i < maxRetries; i++) { - cf = cf.exceptionally(__ -> supplier.get()); - } - return cf; - } + public static CompletableFuture retryUnsafe(Supplier supplier, int maxRetries) { + CompletableFuture cf = CompletableFuture.supplyAsync(supplier); + sleep(100l); + for (int i = 0; i < maxRetries; i++) { + cf = cf.exceptionally(__ -> supplier.get()); + } + return cf; + } - public static CompletableFuture retryNesting(Supplier supplier, int maxRetries) { - CompletableFuture cf = CompletableFuture.supplyAsync(supplier); - sleep(100); - for (int i = 0; i < maxRetries; i++) { - cf = cf.thenApply(CompletableFuture::completedFuture) - .exceptionally(__ -> CompletableFuture.supplyAsync(supplier)) - .thenCompose(Function.identity()); - } - return cf; - } + public static CompletableFuture retryNesting(Supplier supplier, int maxRetries) { + CompletableFuture cf = CompletableFuture.supplyAsync(supplier); + sleep(100); + for (int i = 0; i < maxRetries; i++) { + cf = cf.thenApply(CompletableFuture::completedFuture) + .exceptionally(__ -> CompletableFuture.supplyAsync(supplier)) + .thenCompose(Function.identity()); + } + return cf; + } - public static CompletableFuture retryExceptionallyAsync(Supplier supplier, int maxRetries) { - CompletableFuture cf = CompletableFuture.supplyAsync(supplier); - sleep(100); - for (int i = 0; i < maxRetries; i++) { - cf = cf.exceptionallyAsync(__ -> supplier.get()); - } - return cf; - } + public static CompletableFuture retryExceptionallyAsync(Supplier supplier, int maxRetries) { + CompletableFuture cf = CompletableFuture.supplyAsync(supplier); + sleep(100); + for (int i = 0; i < maxRetries; i++) { + cf = cf.exceptionallyAsync(__ -> supplier.get()); + } + return cf; + } - private static void sleep(long millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + } } diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java index b48039d4a6..ce847fe751 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java @@ -1,125 +1,127 @@ package com.baeldung.concurrent.completablefuture.retry; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; +import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.retryExceptionallyAsync; +import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.retryNesting; +import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.retryTask; +import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.retryUnsafe; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; -import static com.baeldung.concurrent.completablefuture.retry.RetryCompletableFuture.*; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; class RetryCompletableFutureUnitTest { - private AtomicInteger retriesCounter = new AtomicInteger(0); + private AtomicInteger retriesCounter = new AtomicInteger(0); - @BeforeEach - void beforeEach() { - retriesCounter.set(0); - } + @BeforeEach + void beforeEach() { + retriesCounter.set(0); + } - @Test - void whenRetryingTask_thenReturnsCorrectlyAfterFourInvocations() { - Supplier codeToRun = () -> failFourTimesThenReturn(100); + @Test + void whenRetryingTask_thenReturnsCorrectlyAfterFourInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); - CompletableFuture result = retryTask(codeToRun, 10); + CompletableFuture result = retryTask(codeToRun, 10); - assertThat(result.join()) - .isEqualTo(100); - assertThat(retriesCounter) - .hasValue(4); - } + assertThat(result.join()) + .isEqualTo(100); + assertThat(retriesCounter) + .hasValue(4); + } - @Test - void whenRetryingTask_thenThrowsExceptionAfterThreeInvocations() { - Supplier codeToRun = () -> failFourTimesThenReturn(100); + @Test + void whenRetryingTask_thenThrowsExceptionAfterThreeInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); - CompletableFuture result = retryTask(codeToRun, 3); + CompletableFuture result = retryTask(codeToRun, 3); - assertThatThrownBy(result::join) - .isInstanceOf(CompletionException.class) - .hasMessageContaining("IllegalStateException: Task failed after 3 attempts"); - } + assertThatThrownBy(result::join).isInstanceOf(CompletionException.class) + .hasMessageContaining("IllegalStateException: Task failed after 3 attempts"); + } - @Test - void whenRetryingExceptionally_thenReturnsCorrectlyAfterFourInvocations() { - Supplier codeToRun = () -> failFourTimesThenReturn(100); + @Test + void whenRetryingExceptionally_thenReturnsCorrectlyAfterFourInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); - CompletableFuture result = retryUnsafe(codeToRun, 10); + CompletableFuture result = retryUnsafe(codeToRun, 10); - assertThat(result.join()) - .isEqualTo(100); - assertThat(retriesCounter) - .hasValue(4); - } + assertThat(result.join()) + .isEqualTo(100); + assertThat(retriesCounter) + .hasValue(4); + } - @Test - void whenRetryingExceptionally_thenThrowsExceptionAfterThreeInvocations() { - Supplier codeToRun = () -> failFourTimesThenReturn(100); + @Test + void whenRetryingExceptionally_thenThrowsExceptionAfterThreeInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); - CompletableFuture result = retryUnsafe(codeToRun, 3); + CompletableFuture result = retryUnsafe(codeToRun, 3); - assertThatThrownBy(result::join) - .isInstanceOf(CompletionException.class) - .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); - } + assertThatThrownBy(result::join) + .isInstanceOf(CompletionException.class) + .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); + } - @Test - void whenRetryingExceptionallyAsync_thenReturnsCorrectlyAfterFourInvocations() { - Supplier codeToRun = () -> failFourTimesThenReturn(100); + @Test + void whenRetryingExceptionallyAsync_thenReturnsCorrectlyAfterFourInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); - CompletableFuture result = retryExceptionallyAsync(codeToRun, 10); + CompletableFuture result = retryExceptionallyAsync(codeToRun, 10); - assertThat(result.join()) - .isEqualTo(100); - assertThat(retriesCounter) - .hasValue(4); - } + assertThat(result.join()) + .isEqualTo(100); + assertThat(retriesCounter) + .hasValue(4); + } - @Test - void whenRetryingExceptionallyAsync_thenThrowsExceptionAfterThreeInvocations() { - Supplier codeToRun = () -> failFourTimesThenReturn(100); + @Test + void whenRetryingExceptionallyAsync_thenThrowsExceptionAfterThreeInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); - CompletableFuture result = retryExceptionallyAsync(codeToRun, 3); + CompletableFuture result = retryExceptionallyAsync(codeToRun, 3); - assertThatThrownBy(result::join) - .isInstanceOf(CompletionException.class) - .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); - } + assertThatThrownBy(result::join) + .isInstanceOf(CompletionException.class) + .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); + } - @Test - void whenRetryingNesting_thenReturnsCorrectlyAfterFourInvocations() { - Supplier codeToRun = () -> failFourTimesThenReturn(100); + @Test + void whenRetryingNesting_thenReturnsCorrectlyAfterFourInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); - CompletableFuture result = retryNesting(codeToRun, 10); + CompletableFuture result = retryNesting(codeToRun, 10); - assertThat(result.join()) - .isEqualTo(100); - assertThat(retriesCounter) - .hasValue(4); - } + assertThat(result.join()) + .isEqualTo(100); + assertThat(retriesCounter) + .hasValue(4); + } - @Test - void whenRetryingNesting_thenThrowsExceptionAfterThreeInvocations() { - Supplier codeToRun = () -> failFourTimesThenReturn(100); + @Test + void whenRetryingNesting_thenThrowsExceptionAfterThreeInvocations() { + Supplier codeToRun = () -> failFourTimesThenReturn(100); - CompletableFuture result = retryNesting(codeToRun, 3); + CompletableFuture result = retryNesting(codeToRun, 3); - assertThatThrownBy(result::join) - .isInstanceOf(CompletionException.class) - .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); - } + assertThatThrownBy(result::join) + .isInstanceOf(CompletionException.class) + .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); + } - int failFourTimesThenReturn(int returnValue) { - int retryNr = retriesCounter.get(); - System.out.println(String.format("invocation: %s, thread: %s", retryNr, Thread.currentThread().getName())); - if (retryNr < 4) { - retriesCounter.set(retryNr + 1); - throw new RuntimeException(String.format("task failed for %s time(s)", retryNr)); - } - return returnValue; - } + int failFourTimesThenReturn(int returnValue) { + int retryNr = retriesCounter.get(); + System.out.println(String.format("invocation: %s, thread: %s", retryNr, Thread.currentThread().getName())); + if (retryNr < 4) { + retriesCounter.set(retryNr + 1); + throw new RuntimeException(String.format("task failed for %s time(s)", retryNr)); + } + return returnValue; + } } From 5b4fc0d6f3753e8855d44da343dfba749118d123 Mon Sep 17 00:00:00 2001 From: emanueltrandafir1993 Date: Mon, 23 Oct 2023 18:13:35 +0200 Subject: [PATCH 044/108] BAEL-7001: small fix --- .../retry/RetryCompletableFutureUnitTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java index ce847fe751..7f1ea41f92 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java @@ -41,7 +41,8 @@ class RetryCompletableFutureUnitTest { CompletableFuture result = retryTask(codeToRun, 3); - assertThatThrownBy(result::join).isInstanceOf(CompletionException.class) + assertThatThrownBy(result::join) + .isInstanceOf(CompletionException.class) .hasMessageContaining("IllegalStateException: Task failed after 3 attempts"); } 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 045/108] 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 046/108] 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 46f3aac2995baaf5b466a7226fa7e60479dfb15c Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Tue, 24 Oct 2023 14:10:17 +0530 Subject: [PATCH 047/108] JAVA-26283 Improve module build time --- .../web/interceptor/SessionTimerInterceptorIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java index 07bc22f184..873c28c6a2 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java @@ -49,7 +49,7 @@ public class SessionTimerInterceptorIntegrationTest { .andReturn() .getRequest() .getSession(); - Thread.sleep(51000); + Thread.sleep(5000); mockMvc.perform(get("/auth/foos").session((MockHttpSession) session)) .andExpect(status().is2xxSuccessful()); } From 7dd0b413425ee5a2991ed8020a40a8bd70eeacdc Mon Sep 17 00:00:00 2001 From: Alvin Austria Date: Tue, 24 Oct 2023 10:48:34 +0200 Subject: [PATCH 048/108] JAVA-18813 : Update Creating a Fat Jar in Gradle (#15030) --- gradle-modules/gradle/gradle-fat-jar/build.gradle | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/gradle-modules/gradle/gradle-fat-jar/build.gradle b/gradle-modules/gradle/gradle-fat-jar/build.gradle index 6e2934194e..4c3d86d757 100644 --- a/gradle-modules/gradle/gradle-fat-jar/build.gradle +++ b/gradle-modules/gradle/gradle-fat-jar/build.gradle @@ -8,8 +8,10 @@ buildscript { } } -apply plugin: 'java' -apply plugin: 'com.github.johnrengelman.shadow' +plugins { + id 'com.github.johnrengelman.shadow' version '7.1.2' + id 'java' +} repositories { mavenCentral() @@ -30,7 +32,7 @@ task customFatJar(type: Jar) { manifest { attributes 'Main-Class': 'com.baeldung.fatjar.Application' } - baseName = 'all-in-one-jar' + archiveBaseName = 'all-in-one-jar' duplicatesStrategy = DuplicatesStrategy.EXCLUDE from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } } with jar From 2b7e938e090500d2a970afae1d55f5edf95045b3 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Tue, 24 Oct 2023 14:40:19 +0530 Subject: [PATCH 049/108] JAVA-26379 Change parent of spring-web-modules to parent-spring-5 --- spring-web-modules/pom.xml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-web-modules/pom.xml b/spring-web-modules/pom.xml index 9f03b83392..2be896ad83 100644 --- a/spring-web-modules/pom.xml +++ b/spring-web-modules/pom.xml @@ -10,8 +10,9 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 From 01bce216c4cfdfc4b04baf250d8dd11890367e8d Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Tue, 24 Oct 2023 20:15:46 +0300 Subject: [PATCH 050/108] This PR is related to the article BAEL-6878 (#15057) * Update pom.xml This commit aims to add additional required dependencies: org.apache.xmlbeans xmlbeans 5.0.2 org.apache.logging.log4j log4j-core 2.12.4 * This commit is related to the article BAEL-6878 This commit aims to add the "log4j2.xml" file to the resources folder. * This commit is related to the article BAEL-6878 This commit aims to add a new test class named "XMLObjectToStringUnitTest" that suggests several approaches to convert XML objects to a Java string --- xml-2/pom.xml | 12 ++- xml-2/src/main/resources/log4j2.xml | 13 +++ .../xml2string/XMLObjectToStringUnitTest.java | 87 +++++++++++++++++++ 3 files changed, 111 insertions(+), 1 deletion(-) create mode 100644 xml-2/src/main/resources/log4j2.xml create mode 100644 xml-2/src/test/java/com/baeldung/xml/xml2string/XMLObjectToStringUnitTest.java diff --git a/xml-2/pom.xml b/xml-2/pom.xml index 7d10f36042..0f94588ba0 100644 --- a/xml-2/pom.xml +++ b/xml-2/pom.xml @@ -46,6 +46,16 @@ underscore ${underscore.version} + + org.apache.xmlbeans + xmlbeans + 5.0.2 + + + org.apache.logging.log4j + log4j-core + 2.12.4 + @@ -74,4 +84,4 @@ 1.89 - \ No newline at end of file + diff --git a/xml-2/src/main/resources/log4j2.xml b/xml-2/src/main/resources/log4j2.xml new file mode 100644 index 0000000000..f022ab633b --- /dev/null +++ b/xml-2/src/main/resources/log4j2.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/xml-2/src/test/java/com/baeldung/xml/xml2string/XMLObjectToStringUnitTest.java b/xml-2/src/test/java/com/baeldung/xml/xml2string/XMLObjectToStringUnitTest.java new file mode 100644 index 0000000000..0afa3424f3 --- /dev/null +++ b/xml-2/src/test/java/com/baeldung/xml/xml2string/XMLObjectToStringUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.xml2string; + +import org.apache.xmlbeans.XmlException; +import org.apache.xmlbeans.XmlObject; +import org.apache.xmlbeans.XmlOptions; +import org.junit.Test; +import org.junit.Before; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.io.StringWriter; + +import static org.junit.Assert.assertTrue; + +public class XMLObjectToStringUnitTest { + private Document document; + + @Before + public void setup() throws ParserConfigurationException { +// Create a DocumentBuilder + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + +// Create a new Document + document = builder.newDocument(); + +// Create the root element + Element rootElement = document.createElement("root"); + document.appendChild(rootElement); + +// Create child elements + Element childElement1 = document.createElement("child1"); + Element childElement2 = document.createElement("child2"); + +// Add text content to the child elements + childElement1.appendChild(document.createTextNode("This is child element 1")); + childElement2.appendChild(document.createTextNode("This is child element 2")); + +// Append child elements to the root element + rootElement.appendChild(childElement1); + rootElement.appendChild(childElement2); + } + + @Test + public void givenXMLDocument_whenUsingTransformer_thenConvertXMLToString() throws TransformerException { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + StringWriter stringWriter = new StringWriter(); + transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); + String result = stringWriter.toString(); + + assertTrue(result.contains("")); + assertTrue(result.contains("This is child element 1")); + assertTrue(result.contains("This is child element 2")); + } + + @Test + public void givenXMLDocument_whenUsingXmlBeans_thenConvertXMLToString() { + try { + + XmlObject xmlObject = XmlObject.Factory.parse(document); + + XmlOptions options = new XmlOptions(); + options.setSavePrettyPrint(); + options.setUseDefaultNamespace(); + options.setSaveAggressiveNamespaces(); + + String xmlString = xmlObject.xmlText(options); + + xmlString = "" + xmlString; + + assertTrue(xmlString.contains("")); + assertTrue(xmlString.contains("This is child element 1")); + assertTrue(xmlString.contains("This is child element 2")); + } catch (XmlException e) { + e.printStackTrace(); + } + } +} From 03c9dce8cf0a141e8dfd705d03aaaef06579dd30 Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Wed, 25 Oct 2023 10:40:32 +0530 Subject: [PATCH 051/108] 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 052/108] 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 053/108] 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 054/108] 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 055/108] 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 6807803bd328c1c375a6697617ab7fb9c743a724 Mon Sep 17 00:00:00 2001 From: Saikat Chakraborty <40471715+saikatcse03@users.noreply.github.com> Date: Wed, 25 Oct 2023 17:10:55 +0530 Subject: [PATCH 056/108] Renamed file to skip test in jenkins (#14870) * Renamed file to skip test in jenkins * javadoc add --- .../cassandra/inquery/ProductRepositoryNestedLiveTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/cassandra/inquery/ProductRepositoryNestedLiveTest.java b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/cassandra/inquery/ProductRepositoryNestedLiveTest.java index 3592c8b80d..3d99782afd 100644 --- a/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/cassandra/inquery/ProductRepositoryNestedLiveTest.java +++ b/persistence-modules/spring-data-cassandra-2/src/test/java/org/baeldung/cassandra/inquery/ProductRepositoryNestedLiveTest.java @@ -20,7 +20,9 @@ import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; - +/** + * This live test requires a running Docker instance so that a Cassandra container can be created + */ @Testcontainers @SpringBootTest class ProductRepositoryNestedLiveTest { From 69aaf2dbf72d13e5b76a8b8efe07cd0556302dbb Mon Sep 17 00:00:00 2001 From: Mo Helmy <135069400+BenHelmyBen@users.noreply.github.com> Date: Wed, 25 Oct 2023 19:10:28 +0300 Subject: [PATCH 057/108] This commit is related to the article BAEL-7089 (#15065) This commit aims to update the evenElementsQueue queue with oddElementsQueue. --- .../RemoveQueueElementsUnitTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java index 66cfade866..38fdc58099 100644 --- a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java +++ b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/removequeueelements/RemoveQueueElementsUnitTest.java @@ -12,7 +12,7 @@ public class RemoveQueueElementsUnitTest { @Test public void givenQueueWithEvenAndOddNumbers_whenRemovingEvenNumbers_thenOddNumbersRemain() { Queue queue = new LinkedList<>(); - Queue evenElementsQueue = new LinkedList<>(); + Queue oddElementsQueue = new LinkedList<>(); queue.add(1); queue.add(2); queue.add(3); @@ -22,14 +22,14 @@ public class RemoveQueueElementsUnitTest { while (queue.peek() != null) { int element = queue.remove(); if (element % 2 != 0) { - evenElementsQueue.add(element); + oddElementsQueue.add(element); } } - assertEquals(3, evenElementsQueue.size()); - assertTrue(evenElementsQueue.contains(1)); - assertTrue(evenElementsQueue.contains(3)); - assertTrue(evenElementsQueue.contains(5)); + assertEquals(3, oddElementsQueue.size()); + assertTrue(oddElementsQueue.contains(1)); + assertTrue(oddElementsQueue.contains(3)); + assertTrue(oddElementsQueue.contains(5)); } @Test From f182b714a94aa0315dc770616f6af7a1b34b803a Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Wed, 25 Oct 2023 22:42:51 +0530 Subject: [PATCH 058/108] JAVA-26379 Fix failing test --- spring-web-modules/spring-mvc-xml-2/pom.xml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/spring-web-modules/spring-mvc-xml-2/pom.xml b/spring-web-modules/spring-mvc-xml-2/pom.xml index f4326ccf68..8c0062f538 100644 --- a/spring-web-modules/spring-mvc-xml-2/pom.xml +++ b/spring-web-modules/spring-mvc-xml-2/pom.xml @@ -19,12 +19,12 @@ org.springframework spring-web - ${org.springframework.version} + ${spring.version} org.springframework spring-webmvc - ${org.springframework.version} + ${spring.version} @@ -64,7 +64,7 @@ org.springframework.boot spring-boot-starter-test - ${spring-boot.version} + ${spring-boot-starter-test.version} test @@ -95,8 +95,6 @@ - 5.0.2.RELEASE - 1.5.10.RELEASE 5.1.40 4.4.5 4.5.2 From f5bb9479b455c4a2e4faebeeabeb95bcc7244690 Mon Sep 17 00:00:00 2001 From: emanueltrandafir1993 Date: Wed, 25 Oct 2023 19:53:50 +0200 Subject: [PATCH 059/108] MKT-7001: formatting --- .../retry/RetryCompletableFutureUnitTest.java | 32 +++++++------------ 1 file changed, 12 insertions(+), 20 deletions(-) diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java index 7f1ea41f92..ea49f0fa08 100644 --- a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/retry/RetryCompletableFutureUnitTest.java @@ -29,10 +29,8 @@ class RetryCompletableFutureUnitTest { CompletableFuture result = retryTask(codeToRun, 10); - assertThat(result.join()) - .isEqualTo(100); - assertThat(retriesCounter) - .hasValue(4); + assertThat(result.join()).isEqualTo(100); + assertThat(retriesCounter).hasValue(4); } @Test @@ -52,10 +50,8 @@ class RetryCompletableFutureUnitTest { CompletableFuture result = retryUnsafe(codeToRun, 10); - assertThat(result.join()) - .isEqualTo(100); - assertThat(retriesCounter) - .hasValue(4); + assertThat(result.join()).isEqualTo(100); + assertThat(retriesCounter).hasValue(4); } @Test @@ -65,8 +61,8 @@ class RetryCompletableFutureUnitTest { CompletableFuture result = retryUnsafe(codeToRun, 3); assertThatThrownBy(result::join) - .isInstanceOf(CompletionException.class) - .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); + .isInstanceOf(CompletionException.class) + .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); } @Test @@ -75,10 +71,8 @@ class RetryCompletableFutureUnitTest { CompletableFuture result = retryExceptionallyAsync(codeToRun, 10); - assertThat(result.join()) - .isEqualTo(100); - assertThat(retriesCounter) - .hasValue(4); + assertThat(result.join()).isEqualTo(100); + assertThat(retriesCounter).hasValue(4); } @Test @@ -88,7 +82,7 @@ class RetryCompletableFutureUnitTest { CompletableFuture result = retryExceptionallyAsync(codeToRun, 3); assertThatThrownBy(result::join) - .isInstanceOf(CompletionException.class) + .isInstanceOf(CompletionException.class) .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); } @@ -98,10 +92,8 @@ class RetryCompletableFutureUnitTest { CompletableFuture result = retryNesting(codeToRun, 10); - assertThat(result.join()) - .isEqualTo(100); - assertThat(retriesCounter) - .hasValue(4); + assertThat(result.join()).isEqualTo(100); + assertThat(retriesCounter).hasValue(4); } @Test @@ -111,7 +103,7 @@ class RetryCompletableFutureUnitTest { CompletableFuture result = retryNesting(codeToRun, 3); assertThatThrownBy(result::join) - .isInstanceOf(CompletionException.class) + .isInstanceOf(CompletionException.class) .hasMessageContaining("RuntimeException: task failed for 3 time(s)"); } From b4db616646fece37908ed789ccec7ca7dbc10a42 Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Thu, 26 Oct 2023 08:18:01 +0200 Subject: [PATCH 060/108] BAEL-7026: Check If a String Contains a Number Value in Java (#14867) Co-authored-by: Luis Javier Peris Morillo --- .../core-java-string-operations-7/pom.xml | 142 +++++++++--------- .../StrContainsNumberUtils.java | 77 ++++++++++ .../StrContainsNumberUtilsUnitTest.java | 69 +++++++++ 3 files changed, 217 insertions(+), 71 deletions(-) create mode 100644 core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/strcontainsnumber/StrContainsNumberUtils.java create mode 100644 core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/strcontainsnumber/StrContainsNumberUtilsUnitTest.java diff --git a/core-java-modules/core-java-string-operations-7/pom.xml b/core-java-modules/core-java-string-operations-7/pom.xml index 595f918fcd..a2c7036e34 100644 --- a/core-java-modules/core-java-string-operations-7/pom.xml +++ b/core-java-modules/core-java-string-operations-7/pom.xml @@ -1,72 +1,72 @@ - - - 4.0.0 - core-java-string-operations-7 - core-java-string-operations-7 - jar - - - com.baeldung.core-java-modules - core-java-modules - 0.0.1-SNAPSHOT - - - - - org.apache.commons - commons-lang3 - ${apache.commons.lang3.version} - - - org.apache.commons - commons-text - ${commons-text.version} - - - org.liquibase - liquibase-core - 4.9.1 - test - - - org.junit.jupiter - junit-jupiter - 5.8.1 - test - - - org.liquibase - liquibase-core - 4.9.1 - test - - - junit - junit - 4.13.2 - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - - - 11 - 11 - 3.12.0 - 1.10.0 - - + + + 4.0.0 + core-java-string-operations-7 + core-java-string-operations-7 + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + org.apache.commons + commons-lang3 + ${apache.commons.lang3.version} + + + org.apache.commons + commons-text + ${commons-text.version} + + + org.liquibase + liquibase-core + 4.9.1 + test + + + org.junit.jupiter + junit-jupiter + 5.8.1 + test + + + org.liquibase + liquibase-core + 4.9.1 + test + + + junit + junit + 4.13.2 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven.compiler.source} + ${maven.compiler.target} + + + + + + + 11 + 11 + 3.13.0 + 1.10.0 + + \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/strcontainsnumber/StrContainsNumberUtils.java b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/strcontainsnumber/StrContainsNumberUtils.java new file mode 100644 index 0000000000..a609b94cb8 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/strcontainsnumber/StrContainsNumberUtils.java @@ -0,0 +1,77 @@ +package com.baeldung.strcontainsnumber; + +import java.util.regex.Pattern; + +import org.apache.commons.lang3.StringUtils; + +import com.google.common.base.CharMatcher; + +public class StrContainsNumberUtils { + + static boolean checkUsingMatchesMethod(String input) { + if (input == null || input.isEmpty()) { + return false; + } + + return input.matches(".*\\d.*"); + } + + static boolean checkUsingPatternClass(String input) { + if (input == null || input.isEmpty()) { + return false; + } + + return Pattern.compile(".*\\d.*") + .matcher(input) + .matches(); + } + + static boolean checkUsingReplaceAllMethod(String input) { + if (input == null || input.isEmpty()) { + return false; + } + + String result = input.replaceAll("\\d", ""); + return result.length() != input.length(); + } + + static boolean checkUsingIsDigitMethod(String input) { + if (input == null || input.isEmpty()) { + return false; + } + + for (char c : input.toCharArray()) { + if (Character.isDigit(c)) { + return true; + } + } + + return false; + } + + static boolean checkUsingStreamApi(String input) { + if (input == null || input.isEmpty()) { + return false; + } + + return input.chars() + .anyMatch(Character::isDigit); + } + + static boolean checkUsingApacheCommonsLang(String input) { + String result = StringUtils.getDigits(input); + return result != null && !result.isEmpty(); + } + + static boolean checkUsingGuava(String input) { + if (input == null || input.isEmpty()) { + return false; + } + + String result = CharMatcher.forPredicate(Character::isDigit) + .retainFrom(input); + + return !result.isEmpty(); + } + +} diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/strcontainsnumber/StrContainsNumberUtilsUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/strcontainsnumber/StrContainsNumberUtilsUnitTest.java new file mode 100644 index 0000000000..9a60a827e0 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/strcontainsnumber/StrContainsNumberUtilsUnitTest.java @@ -0,0 +1,69 @@ +package com.baeldung.strcontainsnumber; + +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import org.junit.Test; + +public class StrContainsNumberUtilsUnitTest { + + private static final String INPUT_WITH_NUMBERS = "We hope 2024 will be great"; + private static final String INPUT_WITHOUT_NUMBERS = "Hello world"; + + @Test + public void givenInputString_whenUsingMatchesMethod_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingMatchesMethod(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingMatchesMethod(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingMatchesMethod("")); + assertFalse(StrContainsNumberUtils.checkUsingMatchesMethod(null)); + } + + @Test + public void givenInputString_whenUsingPatternClass_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingPatternClass(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingPatternClass(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingPatternClass("")); + assertFalse(StrContainsNumberUtils.checkUsingPatternClass(null)); + } + + @Test + public void givenInputString_whenUsingReplaceAllMethod_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingReplaceAllMethod(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingReplaceAllMethod(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingReplaceAllMethod("")); + assertFalse(StrContainsNumberUtils.checkUsingReplaceAllMethod(null)); + } + + @Test + public void givenInputString_whenUsingIsDigitMethod_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingIsDigitMethod(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingIsDigitMethod(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingIsDigitMethod("")); + assertFalse(StrContainsNumberUtils.checkUsingIsDigitMethod(null)); + } + + @Test + public void givenInputString_whenUsingStreamApi_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingStreamApi(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingStreamApi(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingStreamApi("")); + assertFalse(StrContainsNumberUtils.checkUsingStreamApi(null)); + } + + @Test + public void givenInputString_whenUsingApacheCommonsLang_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingApacheCommonsLang(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingApacheCommonsLang(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingApacheCommonsLang("")); + assertFalse(StrContainsNumberUtils.checkUsingApacheCommonsLang(null)); + } + + @Test + public void givenInputString_whenUsingGuava_ThenCheck() { + assertTrue(StrContainsNumberUtils.checkUsingGuava(INPUT_WITH_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingGuava(INPUT_WITHOUT_NUMBERS)); + assertFalse(StrContainsNumberUtils.checkUsingGuava("")); + assertFalse(StrContainsNumberUtils.checkUsingGuava(null)); + } + +} From ed75b80958f0ce23157017a2dde51baa2d7471f9 Mon Sep 17 00:00:00 2001 From: CHANDRAKANT Kumar Date: Thu, 26 Oct 2023 23:15:14 +0530 Subject: [PATCH 061/108] 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 d9c72a1c1af4d0c01ba518fef819a65a548efd4f Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Fri, 27 Oct 2023 05:44:00 +0100 Subject: [PATCH 062/108] Limit for Repository Query Methods (#15055) * Limit for Repository Query Methods * Limit for Repository Query Methods --- .../java/com/baeldung/boot/passenger/PassengerRepository.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java index 14d5403cb5..7b5a307b81 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java +++ b/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/boot/passenger/PassengerRepository.java @@ -12,6 +12,9 @@ interface PassengerRepository extends JpaRepository, CustomPass Passenger findTopByOrderBySeatNumberAsc(); List findByOrderBySeatNumberAsc(); + + //The Limit type is a new feature in Spring Data JPA version 3.2 + //List findByOrderBySeatNumberAsc(Limit limit); List findByFirstNameIgnoreCase(String firstName); From 16b931c4df6ad17d5ab4e0a58e32018bba92b550 Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Fri, 27 Oct 2023 08:46:04 +0200 Subject: [PATCH 063/108] BAEL-7055: How can I capitalize the first letter of each word in a string? (#14927) Co-authored-by: Mo Helmy <135069400+BenHelmyBen@users.noreply.github.com> --- ...CapitalizeFirstCharacterEachWordUtils.java | 40 +++++++++++++++++++ ...zeFirstCharacterEachWordUtilsUnitTest.java | 38 ++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtils.java create mode 100644 core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtilsUnitTest.java diff --git a/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtils.java b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtils.java new file mode 100644 index 0000000000..cccc745499 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/main/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtils.java @@ -0,0 +1,40 @@ +package com.baeldung.capitalizefirstcharactereachword; + +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.StringUtils; + +class CapitalizeFirstCharacterEachWordUtils { + + static String usingCharacterToUpperCaseMethod(String input) { + if (input == null || input.isEmpty()) { + return null; + } + + return Arrays.stream(input.split("\\s+")) + .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1)) + .collect(Collectors.joining(" ")); + } + + static String usingStringToUpperCaseMethod(String input) { + if (input == null || input.isEmpty()) { + return null; + } + + return Arrays.stream(input.split("\\s+")) + .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1)) + .collect(Collectors.joining(" ")); + } + + static String usingStringUtilsClass(String input) { + if (input == null || input.isEmpty()) { + return null; + } + + return Arrays.stream(input.split("\\s+")) + .map(StringUtils::capitalize) + .collect(Collectors.joining(" ")); + } + +} diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtilsUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtilsUnitTest.java new file mode 100644 index 0000000000..27c7ddb4c4 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/capitalizefirstcharactereachword/CapitalizeFirstCharacterEachWordUtilsUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.capitalizefirstcharactereachword; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.apache.commons.text.WordUtils; +import org.junit.jupiter.api.Test; + +class CapitalizeFirstCharacterEachWordUtilsUnitTest { + + @Test + void givenString_whenUsingCharacterToUpperCaseMethod_thenCapitalizeFirstCharacter() { + String input = "hello baeldung visitors"; + + assertEquals("Hello Baeldung Visitors", CapitalizeFirstCharacterEachWordUtils.usingCharacterToUpperCaseMethod(input)); + } + + @Test + void givenString_whenUsingSubstringMethod_thenCapitalizeFirstCharacter() { + String input = "Hi, my name is azhrioun"; + + assertEquals("Hi, My Name Is Azhrioun", CapitalizeFirstCharacterEachWordUtils.usingStringToUpperCaseMethod(input)); + } + + @Test + void givenString_whenUsingStringUtilsClass_thenCapitalizeFirstCharacter() { + String input = "life is short the world is wide"; + + assertEquals("Life Is Short The World Is Wide", CapitalizeFirstCharacterEachWordUtils.usingStringUtilsClass(input)); + } + + @Test + void givenString_whenUsingWordUtilsClass_thenCapitalizeFirstCharacter() { + String input = "smile sunshine is good for your teeth"; + + assertEquals("Smile Sunshine Is Good For Your Teeth", WordUtils.capitalizeFully(input)); + } + +} From 1028ab97c4efff930a9b8668cb84b1bf9a117c28 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Fri, 27 Oct 2023 15:57:32 +0530 Subject: [PATCH 064/108] Java 26392 Move modules to patterns-module (#15060) * JAVA-26392 Move axon module and ddd module to patterns-modules * JAVA-26292 Move ddd-contexts to patterns-module --- {axon => patterns-modules/axon}/README.md | 0 {axon => patterns-modules/axon}/pom.xml | 2 +- .../com/baeldung/axon/OrderApplication.java | 0 .../axon/OrderApplicationConfiguration.java | 0 .../commandmodel/order/OrderAggregate.java | 0 .../axon/commandmodel/order/OrderLine.java | 0 .../coreapi/commands/AddProductCommand.java | 0 .../coreapi/commands/ConfirmOrderCommand.java | 0 .../coreapi/commands/CreateOrderCommand.java | 0 .../DecrementProductCountCommand.java | 0 .../IncrementProductCountCommand.java | 0 .../coreapi/commands/ShipOrderCommand.java | 0 .../coreapi/events/OrderConfirmedEvent.java | 0 .../coreapi/events/OrderCreatedEvent.java | 0 .../coreapi/events/OrderShippedEvent.java | 0 .../coreapi/events/ProductAddedEvent.java | 0 .../events/ProductCountDecrementedEvent.java | 0 .../events/ProductCountIncrementedEvent.java | 0 .../coreapi/events/ProductRemovedEvent.java | 0 .../DuplicateOrderLineException.java | 0 .../OrderAlreadyConfirmedException.java | 0 .../exceptions/UnconfirmedOrderException.java | 0 .../queries/FindAllOrderedProductsQuery.java | 0 .../baeldung/axon/coreapi/queries/Order.java | 0 .../axon/coreapi/queries/OrderStatus.java | 0 .../coreapi/queries/OrderUpdatesQuery.java | 0 .../queries/TotalProductsShippedQuery.java | 0 .../baeldung/axon/gui/OrderRestEndpoint.java | 0 .../InMemoryOrdersEventHandler.java | 0 .../axon/querymodel/LegacyQueryHandler.java | 0 .../axon/querymodel/MongoConfiguration.java | 0 .../querymodel/MongoOrdersEventHandler.java | 0 .../axon/querymodel/OrderQueryService.java | 0 .../axon/querymodel/OrderResponse.java | 0 .../axon/querymodel/OrderStatusResponse.java | 0 .../axon/querymodel/OrdersEventHandler.java | 0 .../resources/application-mongo.properties | 0 .../src/main/resources/application.properties | 0 .../axon}/src/main/resources/logback.xml | 0 .../axon}/src/main/resources/order-api.http | 0 .../commandmodel/OrderAggregateUnitTest.java | 0 .../axon/gui/OrderRestEndpointManualTest.java | 0 .../AbstractOrdersEventHandlerUnitTest.java | 0 .../InMemoryOrdersEventHandlerUnitTest.java | 0 .../MongoOrdersEventHandlerUnitTest.java | 0 .../OrderQueryServiceIntegrationTest.java | 0 .../src/test/resources/application.properties | 0 .../axon}/start_axon_server.sh | 0 .../axon}/start_mongo.sh | 0 .../ddd-contexts}/README.md | 0 .../ddd-contexts-infrastructure/pom.xml | 0 .../infrastructure/db/InMemoryOrderStore.java | 0 .../infrastructure/events/SimpleEventBus.java | 0 .../src/main/java/module-info.java | 0 .../ddd-contexts-mainapp/pom.xml | 0 .../dddcontexts/mainapp/Application.java | 0 .../src/main/java/module-info.java | 0 .../ddd-contexts-ordercontext/pom.xml | 0 .../ordercontext/model/CustomerOrder.java | 0 .../ordercontext/model/OrderItem.java | 0 .../repository/CustomerOrderRepository.java | 0 .../service/CustomerOrderService.java | 0 .../ordercontext/service/OrderService.java | 0 .../src/main/java/module-info.java | 0 .../ddd-contexts-sharedkernel/pom.xml | 0 .../sharedkernel/events/ApplicationEvent.java | 0 .../sharedkernel/events/EventBus.java | 0 .../sharedkernel/events/EventSubscriber.java | 0 .../service/ApplicationService.java | 0 .../src/main/java/module-info.java | 0 .../ddd-contexts-shippingcontext/pom.xml | 0 .../shippingcontext/model/PackageItem.java | 0 .../shippingcontext/model/Parcel.java | 0 .../shippingcontext/model/ShippableOrder.java | 0 .../repository/ShippingOrderRepository.java | 0 .../service/ParcelShippingService.java | 0 .../service/ShippingService.java | 0 .../src/main/java/module-info.java | 0 .../ddd-contexts}/pom.xml | 2 +- {ddd => patterns-modules/ddd}/README.md | 0 {ddd => patterns-modules/ddd}/pom.xml | 2 +- .../PersistingDddAggregatesApplication.java | 24 +++++++++---------- .../java/com/baeldung/ddd/order/Order.java | 0 .../com/baeldung/ddd/order/OrderLine.java | 0 .../java/com/baeldung/ddd/order/Product.java | 0 .../config/CustomMongoConfiguration.java | 0 .../AmountBasedDiscountPolicy.java | 0 .../order/doubledispatch/DiscountPolicy.java | 0 .../doubledispatch/FlatDiscountPolicy.java | 0 .../ddd/order/doubledispatch/Order.java | 0 .../doubledispatch/SpecialDiscountPolicy.java | 0 .../order/doubledispatch/SpecialOrder.java | 0 .../visitor/HtmlOrderViewCreator.java | 0 .../doubledispatch/visitor/OrderVisitor.java | 0 .../doubledispatch/visitor/Visitable.java | 0 .../com/baeldung/ddd/order/jpa/JpaOrder.java | 0 .../baeldung/ddd/order/jpa/JpaOrderLine.java | 0 .../ddd/order/jpa/JpaOrderRepository.java | 0 .../baeldung/ddd/order/jpa/JpaProduct.java | 0 .../ddd/order/mongo/OrderMongoRepository.java | 0 .../DomainLayerApplication.java | 0 .../application/cli/CliOrderController.java | 0 .../request/AddProductRequest.java | 0 .../request/CreateOrderRequest.java | 0 .../response/CreateOrderResponse.java | 0 .../application/rest/OrderController.java | 0 .../domain/DomainException.java | 0 .../dddhexagonalspring/domain/Order.java | 0 .../dddhexagonalspring/domain/OrderItem.java | 0 .../domain/OrderStatus.java | 0 .../dddhexagonalspring/domain/Product.java | 0 .../domain/repository/OrderRepository.java | 0 .../domain/service/DomainOrderService.java | 0 .../domain/service/OrderService.java | 0 .../configuration/BeanConfiguration.java | 0 .../configuration/CassandraConfiguration.java | 0 .../configuration/MongoDBConfiguration.java | 0 .../cassandra/CassandraDbOrderRepository.java | 0 .../repository/cassandra/OrderEntity.java | 0 .../repository/cassandra/OrderItemEntity.java | 0 .../SpringDataCassandraOrderRepository.java | 0 .../mongo/MongoDbOrderRepository.java | 0 .../mongo/SpringDataMongoOrderRepository.java | 0 .../src/main/resources/ddd-layers.properties | 0 .../baeldung/ddd/order/OrderFixtureUtils.java | 0 .../com/baeldung/ddd/order/OrderUnitTest.java | 0 .../DoubleDispatchDiscountPolicyUnitTest.java | 0 .../HtmlOrderViewCreatorUnitTest.java | 0 .../MethodOverloadExampleUnitTest.java | 0 .../SingleDispatchDiscountPolicyUnitTest.java | 0 .../ddd/order/jpa/PersistOrderLiveTest.java | 0 .../ViolateOrderBusinessRulesUnitTest.java | 0 .../ddd/order/mongo/OrderMongoLiveTest.java | 0 .../domain/OrderProvider.java | 0 .../domain/OrderUnitTest.java | 0 .../service/DomainOrderServiceUnitTest.java | 0 .../CassandraDbOrderRepositoryLiveTest.java | 0 .../MongoDbOrderRepositoryLiveTest.java | 0 .../MongoDbOrderRepositoryUnitTest.java | 0 .../com/baeldung/dddhexagonalspring/README.md | 0 .../dddhexagonalspring/cassandra-init.cql | 0 .../dddhexagonalspring/docker-compose.yml | 0 .../baeldung/dddhexagonalspring/mongo-init.js | 0 .../test/resources/ddd-layers-test.properties | 0 patterns-modules/pom.xml | 13 ++++++---- pom.xml | 8 ------- 146 files changed, 23 insertions(+), 28 deletions(-) rename {axon => patterns-modules/axon}/README.md (100%) rename {axon => patterns-modules/axon}/pom.xml (98%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/OrderApplication.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/OrderApplicationConfiguration.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/commandmodel/order/OrderAggregate.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/commandmodel/order/OrderLine.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/commands/AddProductCommand.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/commands/CreateOrderCommand.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/commands/DecrementProductCountCommand.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/commands/IncrementProductCountCommand.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/events/OrderCreatedEvent.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/events/ProductAddedEvent.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/events/ProductCountDecrementedEvent.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/events/ProductCountIncrementedEvent.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/events/ProductRemovedEvent.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/exceptions/DuplicateOrderLineException.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/exceptions/OrderAlreadyConfirmedException.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/queries/Order.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/queries/OrderUpdatesQuery.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/coreapi/queries/TotalProductsShippedQuery.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandler.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/querymodel/LegacyQueryHandler.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/querymodel/MongoConfiguration.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/querymodel/MongoOrdersEventHandler.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/querymodel/OrderQueryService.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/querymodel/OrderResponse.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/querymodel/OrderStatusResponse.java (100%) rename {axon => patterns-modules/axon}/src/main/java/com/baeldung/axon/querymodel/OrdersEventHandler.java (100%) rename {axon => patterns-modules/axon}/src/main/resources/application-mongo.properties (100%) rename {axon => patterns-modules/axon}/src/main/resources/application.properties (100%) rename {axon => patterns-modules/axon}/src/main/resources/logback.xml (100%) rename {axon => patterns-modules/axon}/src/main/resources/order-api.http (100%) rename {axon => patterns-modules/axon}/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java (100%) rename {axon => patterns-modules/axon}/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java (100%) rename {axon => patterns-modules/axon}/src/test/java/com/baeldung/axon/querymodel/AbstractOrdersEventHandlerUnitTest.java (100%) rename {axon => patterns-modules/axon}/src/test/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandlerUnitTest.java (100%) rename {axon => patterns-modules/axon}/src/test/java/com/baeldung/axon/querymodel/MongoOrdersEventHandlerUnitTest.java (100%) rename {axon => patterns-modules/axon}/src/test/java/com/baeldung/axon/querymodel/OrderQueryServiceIntegrationTest.java (100%) rename {axon => patterns-modules/axon}/src/test/resources/application.properties (100%) rename {axon => patterns-modules/axon}/start_axon_server.sh (100%) mode change 100755 => 100644 rename {axon => patterns-modules/axon}/start_mongo.sh (100%) mode change 100755 => 100644 rename {ddd-contexts => patterns-modules/ddd-contexts}/README.md (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-infrastructure/pom.xml (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-infrastructure/src/main/java/module-info.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-mainapp/pom.xml (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-mainapp/src/main/java/module-info.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-ordercontext/pom.xml (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-ordercontext/src/main/java/module-info.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-sharedkernel/pom.xml (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-sharedkernel/src/main/java/module-info.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-shippingcontext/pom.xml (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/ddd-contexts-shippingcontext/src/main/java/module-info.java (100%) rename {ddd-contexts => patterns-modules/ddd-contexts}/pom.xml (98%) rename {ddd => patterns-modules/ddd}/README.md (100%) rename {ddd => patterns-modules/ddd}/pom.xml (98%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java (96%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/Order.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/OrderLine.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/Product.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/doubledispatch/AmountBasedDiscountPolicy.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/doubledispatch/DiscountPolicy.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/doubledispatch/FlatDiscountPolicy.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/doubledispatch/Order.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialDiscountPolicy.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialOrder.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/HtmlOrderViewCreator.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/OrderVisitor.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/Visitable.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderRepository.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/ddd/order/mongo/OrderMongoRepository.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/application/cli/CliOrderController.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/application/response/CreateOrderResponse.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/application/rest/OrderController.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/domain/DomainException.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderItem.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderStatus.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/domain/Product.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/domain/repository/OrderRepository.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderService.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/domain/service/OrderService.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/BeanConfiguration.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/CassandraConfiguration.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/CassandraDbOrderRepository.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderEntity.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderItemEntity.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/SpringDataCassandraOrderRepository.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/MongoDbOrderRepository.java (100%) rename {ddd => patterns-modules/ddd}/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/SpringDataMongoOrderRepository.java (100%) rename {ddd => patterns-modules/ddd}/src/main/resources/ddd-layers.properties (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/ddd/order/OrderFixtureUtils.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/ddd/order/OrderUnitTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/ddd/order/doubledispatch/DoubleDispatchDiscountPolicyUnitTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/ddd/order/doubledispatch/HtmlOrderViewCreatorUnitTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/ddd/order/doubledispatch/MethodOverloadExampleUnitTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/ddd/order/doubledispatch/SingleDispatchDiscountPolicyUnitTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderLiveTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/ddd/order/jpa/ViolateOrderBusinessRulesUnitTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoLiveTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderProvider.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderUnitTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderServiceUnitTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryLiveTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryLiveTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java (100%) rename {ddd => patterns-modules/ddd}/src/test/resources/com/baeldung/dddhexagonalspring/README.md (100%) rename {ddd => patterns-modules/ddd}/src/test/resources/com/baeldung/dddhexagonalspring/cassandra-init.cql (100%) rename {ddd => patterns-modules/ddd}/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml (100%) rename {ddd => patterns-modules/ddd}/src/test/resources/com/baeldung/dddhexagonalspring/mongo-init.js (100%) rename {ddd => patterns-modules/ddd}/src/test/resources/ddd-layers-test.properties (100%) diff --git a/axon/README.md b/patterns-modules/axon/README.md similarity index 100% rename from axon/README.md rename to patterns-modules/axon/README.md diff --git a/axon/pom.xml b/patterns-modules/axon/pom.xml similarity index 98% rename from axon/pom.xml rename to patterns-modules/axon/pom.xml index 5eed742aab..473a1b0e15 100644 --- a/axon/pom.xml +++ b/patterns-modules/axon/pom.xml @@ -11,7 +11,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 diff --git a/axon/src/main/java/com/baeldung/axon/OrderApplication.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/OrderApplication.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/OrderApplication.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/OrderApplication.java diff --git a/axon/src/main/java/com/baeldung/axon/OrderApplicationConfiguration.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/OrderApplicationConfiguration.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/OrderApplicationConfiguration.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/OrderApplicationConfiguration.java diff --git a/axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderAggregate.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderAggregate.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderAggregate.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderAggregate.java diff --git a/axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderLine.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderLine.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderLine.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/commandmodel/order/OrderLine.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/AddProductCommand.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/AddProductCommand.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/commands/AddProductCommand.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/AddProductCommand.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/ConfirmOrderCommand.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/CreateOrderCommand.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/CreateOrderCommand.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/commands/CreateOrderCommand.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/CreateOrderCommand.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/DecrementProductCountCommand.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/DecrementProductCountCommand.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/commands/DecrementProductCountCommand.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/DecrementProductCountCommand.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/IncrementProductCountCommand.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/IncrementProductCountCommand.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/commands/IncrementProductCountCommand.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/IncrementProductCountCommand.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/commands/ShipOrderCommand.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderConfirmedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderCreatedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderCreatedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/OrderCreatedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderCreatedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/OrderShippedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductAddedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductAddedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/ProductAddedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductAddedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountDecrementedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountDecrementedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountDecrementedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountDecrementedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountIncrementedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountIncrementedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountIncrementedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductCountIncrementedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductRemovedEvent.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductRemovedEvent.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/events/ProductRemovedEvent.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/events/ProductRemovedEvent.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/DuplicateOrderLineException.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/DuplicateOrderLineException.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/exceptions/DuplicateOrderLineException.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/DuplicateOrderLineException.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/OrderAlreadyConfirmedException.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/OrderAlreadyConfirmedException.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/exceptions/OrderAlreadyConfirmedException.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/OrderAlreadyConfirmedException.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/exceptions/UnconfirmedOrderException.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/FindAllOrderedProductsQuery.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/Order.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/Order.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/queries/Order.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/Order.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderStatus.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderUpdatesQuery.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderUpdatesQuery.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderUpdatesQuery.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/OrderUpdatesQuery.java diff --git a/axon/src/main/java/com/baeldung/axon/coreapi/queries/TotalProductsShippedQuery.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/TotalProductsShippedQuery.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/coreapi/queries/TotalProductsShippedQuery.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/coreapi/queries/TotalProductsShippedQuery.java diff --git a/axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/gui/OrderRestEndpoint.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandler.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandler.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandler.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandler.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/LegacyQueryHandler.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/LegacyQueryHandler.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/LegacyQueryHandler.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/LegacyQueryHandler.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/MongoConfiguration.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/MongoConfiguration.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/MongoConfiguration.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/MongoConfiguration.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/MongoOrdersEventHandler.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/MongoOrdersEventHandler.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/MongoOrdersEventHandler.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/MongoOrdersEventHandler.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrderQueryService.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrderQueryService.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/OrderQueryService.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrderQueryService.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrderResponse.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrderResponse.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/OrderResponse.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrderResponse.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrderStatusResponse.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrderStatusResponse.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/OrderStatusResponse.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrderStatusResponse.java diff --git a/axon/src/main/java/com/baeldung/axon/querymodel/OrdersEventHandler.java b/patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrdersEventHandler.java similarity index 100% rename from axon/src/main/java/com/baeldung/axon/querymodel/OrdersEventHandler.java rename to patterns-modules/axon/src/main/java/com/baeldung/axon/querymodel/OrdersEventHandler.java diff --git a/axon/src/main/resources/application-mongo.properties b/patterns-modules/axon/src/main/resources/application-mongo.properties similarity index 100% rename from axon/src/main/resources/application-mongo.properties rename to patterns-modules/axon/src/main/resources/application-mongo.properties diff --git a/axon/src/main/resources/application.properties b/patterns-modules/axon/src/main/resources/application.properties similarity index 100% rename from axon/src/main/resources/application.properties rename to patterns-modules/axon/src/main/resources/application.properties diff --git a/axon/src/main/resources/logback.xml b/patterns-modules/axon/src/main/resources/logback.xml similarity index 100% rename from axon/src/main/resources/logback.xml rename to patterns-modules/axon/src/main/resources/logback.xml diff --git a/axon/src/main/resources/order-api.http b/patterns-modules/axon/src/main/resources/order-api.http similarity index 100% rename from axon/src/main/resources/order-api.http rename to patterns-modules/axon/src/main/resources/order-api.http diff --git a/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java b/patterns-modules/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java similarity index 100% rename from axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java rename to patterns-modules/axon/src/test/java/com/baeldung/axon/commandmodel/OrderAggregateUnitTest.java diff --git a/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java b/patterns-modules/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java similarity index 100% rename from axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java rename to patterns-modules/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java diff --git a/axon/src/test/java/com/baeldung/axon/querymodel/AbstractOrdersEventHandlerUnitTest.java b/patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/AbstractOrdersEventHandlerUnitTest.java similarity index 100% rename from axon/src/test/java/com/baeldung/axon/querymodel/AbstractOrdersEventHandlerUnitTest.java rename to patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/AbstractOrdersEventHandlerUnitTest.java diff --git a/axon/src/test/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandlerUnitTest.java b/patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandlerUnitTest.java similarity index 100% rename from axon/src/test/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandlerUnitTest.java rename to patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/InMemoryOrdersEventHandlerUnitTest.java diff --git a/axon/src/test/java/com/baeldung/axon/querymodel/MongoOrdersEventHandlerUnitTest.java b/patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/MongoOrdersEventHandlerUnitTest.java similarity index 100% rename from axon/src/test/java/com/baeldung/axon/querymodel/MongoOrdersEventHandlerUnitTest.java rename to patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/MongoOrdersEventHandlerUnitTest.java diff --git a/axon/src/test/java/com/baeldung/axon/querymodel/OrderQueryServiceIntegrationTest.java b/patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/OrderQueryServiceIntegrationTest.java similarity index 100% rename from axon/src/test/java/com/baeldung/axon/querymodel/OrderQueryServiceIntegrationTest.java rename to patterns-modules/axon/src/test/java/com/baeldung/axon/querymodel/OrderQueryServiceIntegrationTest.java diff --git a/axon/src/test/resources/application.properties b/patterns-modules/axon/src/test/resources/application.properties similarity index 100% rename from axon/src/test/resources/application.properties rename to patterns-modules/axon/src/test/resources/application.properties diff --git a/axon/start_axon_server.sh b/patterns-modules/axon/start_axon_server.sh old mode 100755 new mode 100644 similarity index 100% rename from axon/start_axon_server.sh rename to patterns-modules/axon/start_axon_server.sh diff --git a/axon/start_mongo.sh b/patterns-modules/axon/start_mongo.sh old mode 100755 new mode 100644 similarity index 100% rename from axon/start_mongo.sh rename to patterns-modules/axon/start_mongo.sh diff --git a/ddd-contexts/README.md b/patterns-modules/ddd-contexts/README.md similarity index 100% rename from ddd-contexts/README.md rename to patterns-modules/ddd-contexts/README.md diff --git a/ddd-contexts/ddd-contexts-infrastructure/pom.xml b/patterns-modules/ddd-contexts/ddd-contexts-infrastructure/pom.xml similarity index 100% rename from ddd-contexts/ddd-contexts-infrastructure/pom.xml rename to patterns-modules/ddd-contexts/ddd-contexts-infrastructure/pom.xml diff --git a/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java b/patterns-modules/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java similarity index 100% rename from ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java rename to patterns-modules/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/db/InMemoryOrderStore.java diff --git a/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java b/patterns-modules/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java similarity index 100% rename from ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java rename to patterns-modules/ddd-contexts/ddd-contexts-infrastructure/src/main/java/com/baeldung/dddcontexts/infrastructure/events/SimpleEventBus.java diff --git a/ddd-contexts/ddd-contexts-infrastructure/src/main/java/module-info.java b/patterns-modules/ddd-contexts/ddd-contexts-infrastructure/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/ddd-contexts-infrastructure/src/main/java/module-info.java rename to patterns-modules/ddd-contexts/ddd-contexts-infrastructure/src/main/java/module-info.java diff --git a/ddd-contexts/ddd-contexts-mainapp/pom.xml b/patterns-modules/ddd-contexts/ddd-contexts-mainapp/pom.xml similarity index 100% rename from ddd-contexts/ddd-contexts-mainapp/pom.xml rename to patterns-modules/ddd-contexts/ddd-contexts-mainapp/pom.xml diff --git a/ddd-contexts/ddd-contexts-mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java b/patterns-modules/ddd-contexts/ddd-contexts-mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java similarity index 100% rename from ddd-contexts/ddd-contexts-mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java rename to patterns-modules/ddd-contexts/ddd-contexts-mainapp/src/main/java/com/baeldung/dddcontexts/mainapp/Application.java diff --git a/ddd-contexts/ddd-contexts-mainapp/src/main/java/module-info.java b/patterns-modules/ddd-contexts/ddd-contexts-mainapp/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/ddd-contexts-mainapp/src/main/java/module-info.java rename to patterns-modules/ddd-contexts/ddd-contexts-mainapp/src/main/java/module-info.java diff --git a/ddd-contexts/ddd-contexts-ordercontext/pom.xml b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/pom.xml similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/pom.xml rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/pom.xml diff --git a/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/CustomerOrder.java diff --git a/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/model/OrderItem.java diff --git a/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/repository/CustomerOrderRepository.java diff --git a/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/CustomerOrderService.java diff --git a/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/com/baeldung/dddcontexts/ordercontext/service/OrderService.java diff --git a/ddd-contexts/ddd-contexts-ordercontext/src/main/java/module-info.java b/patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/ddd-contexts-ordercontext/src/main/java/module-info.java rename to patterns-modules/ddd-contexts/ddd-contexts-ordercontext/src/main/java/module-info.java diff --git a/ddd-contexts/ddd-contexts-sharedkernel/pom.xml b/patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/pom.xml similarity index 100% rename from ddd-contexts/ddd-contexts-sharedkernel/pom.xml rename to patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/pom.xml diff --git a/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java b/patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java similarity index 100% rename from ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java rename to patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/ApplicationEvent.java diff --git a/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java b/patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java similarity index 100% rename from ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java rename to patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventBus.java diff --git a/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java b/patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java similarity index 100% rename from ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java rename to patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/events/EventSubscriber.java diff --git a/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java b/patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java similarity index 100% rename from ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java rename to patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/com/baeldung/dddcontexts/sharedkernel/service/ApplicationService.java diff --git a/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/module-info.java b/patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/ddd-contexts-sharedkernel/src/main/java/module-info.java rename to patterns-modules/ddd-contexts/ddd-contexts-sharedkernel/src/main/java/module-info.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/pom.xml b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/pom.xml similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/pom.xml rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/pom.xml diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/PackageItem.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/Parcel.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/model/ShippableOrder.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/repository/ShippingOrderRepository.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ParcelShippingService.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/com/baeldung/dddcontexts/shippingcontext/service/ShippingService.java diff --git a/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/module-info.java b/patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/module-info.java similarity index 100% rename from ddd-contexts/ddd-contexts-shippingcontext/src/main/java/module-info.java rename to patterns-modules/ddd-contexts/ddd-contexts-shippingcontext/src/main/java/module-info.java diff --git a/ddd-contexts/pom.xml b/patterns-modules/ddd-contexts/pom.xml similarity index 98% rename from ddd-contexts/pom.xml rename to patterns-modules/ddd-contexts/pom.xml index 961a1d1624..f43581b0c8 100644 --- a/ddd-contexts/pom.xml +++ b/patterns-modules/ddd-contexts/pom.xml @@ -11,7 +11,7 @@ com.baeldung - parent-modules + patterns-modules 1.0.0-SNAPSHOT diff --git a/ddd/README.md b/patterns-modules/ddd/README.md similarity index 100% rename from ddd/README.md rename to patterns-modules/ddd/README.md diff --git a/ddd/pom.xml b/patterns-modules/ddd/pom.xml similarity index 98% rename from ddd/pom.xml rename to patterns-modules/ddd/pom.xml index 443b2b5148..80147c29c6 100644 --- a/ddd/pom.xml +++ b/patterns-modules/ddd/pom.xml @@ -12,7 +12,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 diff --git a/ddd/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java similarity index 96% rename from ddd/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java index 3a52fd0440..2d671ff85e 100644 --- a/ddd/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java +++ b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/PersistingDddAggregatesApplication.java @@ -1,12 +1,12 @@ -package com.baeldung.ddd; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication(scanBasePackages = "com.baeldung.ddd.order") -public class PersistingDddAggregatesApplication { - - public static void main(String[] args) { - SpringApplication.run(PersistingDddAggregatesApplication.class, args); - } -} +package com.baeldung.ddd; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = "com.baeldung.ddd.order") +public class PersistingDddAggregatesApplication { + + public static void main(String[] args) { + SpringApplication.run(PersistingDddAggregatesApplication.class, args); + } +} diff --git a/ddd/src/main/java/com/baeldung/ddd/order/Order.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/Order.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/Order.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/Order.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/OrderLine.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/OrderLine.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/OrderLine.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/OrderLine.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/Product.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/Product.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/Product.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/Product.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/config/CustomMongoConfiguration.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/AmountBasedDiscountPolicy.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/AmountBasedDiscountPolicy.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/AmountBasedDiscountPolicy.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/AmountBasedDiscountPolicy.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/DiscountPolicy.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/DiscountPolicy.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/DiscountPolicy.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/DiscountPolicy.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/FlatDiscountPolicy.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/FlatDiscountPolicy.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/FlatDiscountPolicy.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/FlatDiscountPolicy.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/Order.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/Order.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/Order.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/Order.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialDiscountPolicy.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialDiscountPolicy.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialDiscountPolicy.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialDiscountPolicy.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialOrder.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialOrder.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialOrder.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/SpecialOrder.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/HtmlOrderViewCreator.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/HtmlOrderViewCreator.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/HtmlOrderViewCreator.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/HtmlOrderViewCreator.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/OrderVisitor.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/OrderVisitor.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/OrderVisitor.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/OrderVisitor.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/Visitable.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/Visitable.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/Visitable.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/doubledispatch/visitor/Visitable.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderRepository.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java diff --git a/ddd/src/main/java/com/baeldung/ddd/order/mongo/OrderMongoRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/mongo/OrderMongoRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/ddd/order/mongo/OrderMongoRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/mongo/OrderMongoRepository.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/DomainLayerApplication.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/cli/CliOrderController.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/cli/CliOrderController.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/application/cli/CliOrderController.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/cli/CliOrderController.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/response/CreateOrderResponse.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/response/CreateOrderResponse.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/application/response/CreateOrderResponse.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/response/CreateOrderResponse.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/rest/OrderController.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/rest/OrderController.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/application/rest/OrderController.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/rest/OrderController.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/DomainException.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/DomainException.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/DomainException.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/DomainException.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Order.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderItem.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderItem.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderItem.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderItem.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderStatus.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderStatus.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderStatus.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/OrderStatus.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Product.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Product.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Product.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/Product.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/repository/OrderRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/repository/OrderRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/repository/OrderRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/repository/OrderRepository.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderService.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderService.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderService.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderService.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/OrderService.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/OrderService.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/OrderService.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/domain/service/OrderService.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/BeanConfiguration.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/BeanConfiguration.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/BeanConfiguration.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/BeanConfiguration.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/CassandraConfiguration.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/CassandraConfiguration.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/CassandraConfiguration.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/CassandraConfiguration.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/configuration/MongoDBConfiguration.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/CassandraDbOrderRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/CassandraDbOrderRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/CassandraDbOrderRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/CassandraDbOrderRepository.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderEntity.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderEntity.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderEntity.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderEntity.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderItemEntity.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderItemEntity.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderItemEntity.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/OrderItemEntity.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/SpringDataCassandraOrderRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/SpringDataCassandraOrderRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/SpringDataCassandraOrderRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/cassandra/SpringDataCassandraOrderRepository.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/MongoDbOrderRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/MongoDbOrderRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/MongoDbOrderRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/MongoDbOrderRepository.java diff --git a/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/SpringDataMongoOrderRepository.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/SpringDataMongoOrderRepository.java similarity index 100% rename from ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/SpringDataMongoOrderRepository.java rename to patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/infrastracture/repository/mongo/SpringDataMongoOrderRepository.java diff --git a/ddd/src/main/resources/ddd-layers.properties b/patterns-modules/ddd/src/main/resources/ddd-layers.properties similarity index 100% rename from ddd/src/main/resources/ddd-layers.properties rename to patterns-modules/ddd/src/main/resources/ddd-layers.properties diff --git a/ddd/src/test/java/com/baeldung/ddd/order/OrderFixtureUtils.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/OrderFixtureUtils.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/OrderFixtureUtils.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/OrderFixtureUtils.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/OrderUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/OrderUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/OrderUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/OrderUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/DoubleDispatchDiscountPolicyUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/DoubleDispatchDiscountPolicyUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/DoubleDispatchDiscountPolicyUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/DoubleDispatchDiscountPolicyUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/HtmlOrderViewCreatorUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/HtmlOrderViewCreatorUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/HtmlOrderViewCreatorUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/HtmlOrderViewCreatorUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/MethodOverloadExampleUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/MethodOverloadExampleUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/MethodOverloadExampleUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/MethodOverloadExampleUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/SingleDispatchDiscountPolicyUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/SingleDispatchDiscountPolicyUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/SingleDispatchDiscountPolicyUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/doubledispatch/SingleDispatchDiscountPolicyUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderLiveTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderLiveTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderLiveTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/jpa/PersistOrderLiveTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/jpa/ViolateOrderBusinessRulesUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/jpa/ViolateOrderBusinessRulesUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/jpa/ViolateOrderBusinessRulesUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/jpa/ViolateOrderBusinessRulesUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoLiveTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoLiveTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoLiveTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/ddd/order/mongo/OrderMongoLiveTest.java diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderProvider.java b/patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderProvider.java similarity index 100% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderProvider.java rename to patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderProvider.java diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/OrderUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderServiceUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderServiceUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderServiceUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/domain/service/DomainOrderServiceUnitTest.java diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryLiveTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryLiveTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryLiveTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/CassandraDbOrderRepositoryLiveTest.java diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryLiveTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryLiveTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryLiveTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryLiveTest.java diff --git a/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java b/patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java similarity index 100% rename from ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java rename to patterns-modules/ddd/src/test/java/com/baeldung/dddhexagonalspring/infrastracture/repository/MongoDbOrderRepositoryUnitTest.java diff --git a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/README.md b/patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/README.md similarity index 100% rename from ddd/src/test/resources/com/baeldung/dddhexagonalspring/README.md rename to patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/README.md diff --git a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/cassandra-init.cql b/patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/cassandra-init.cql similarity index 100% rename from ddd/src/test/resources/com/baeldung/dddhexagonalspring/cassandra-init.cql rename to patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/cassandra-init.cql diff --git a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml b/patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml similarity index 100% rename from ddd/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml rename to patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/docker-compose.yml diff --git a/ddd/src/test/resources/com/baeldung/dddhexagonalspring/mongo-init.js b/patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/mongo-init.js similarity index 100% rename from ddd/src/test/resources/com/baeldung/dddhexagonalspring/mongo-init.js rename to patterns-modules/ddd/src/test/resources/com/baeldung/dddhexagonalspring/mongo-init.js diff --git a/ddd/src/test/resources/ddd-layers-test.properties b/patterns-modules/ddd/src/test/resources/ddd-layers-test.properties similarity index 100% rename from ddd/src/test/resources/ddd-layers-test.properties rename to patterns-modules/ddd/src/test/resources/ddd-layers-test.properties diff --git a/patterns-modules/pom.xml b/patterns-modules/pom.xml index add2b0475b..7dd26ac31c 100644 --- a/patterns-modules/pom.xml +++ b/patterns-modules/pom.xml @@ -14,6 +14,12 @@ + axon + clean-architecture + coupling + cqrs-es + ddd + ddd-contexts design-patterns-architectural design-patterns-behavioral design-patterns-behavioral-2 @@ -24,14 +30,11 @@ design-patterns-singleton design-patterns-structural dip - cqrs-es + enterprise-patterns front-controller + idd intercepting-filter solid - clean-architecture - enterprise-patterns - coupling - idd diff --git a/pom.xml b/pom.xml index 327d83017f..a5abb59502 100644 --- a/pom.xml +++ b/pom.xml @@ -771,7 +771,6 @@ core-java-modules custom-pmd data-structures - ddd-contexts jackson-modules jmh deeplearning4j @@ -821,11 +820,8 @@ atomikos atomix - axon - bazel google-auto-project - ddd disruptor dozer dubbo @@ -1057,7 +1053,6 @@ spring-aop-2 custom-pmd data-structures - ddd-contexts jackson-modules jmh deeplearning4j @@ -1107,11 +1102,8 @@ atomikos atomix - axon - bazel google-auto-project - ddd disruptor dozer From 520b679733d06d32a7fd9792c9e3519924f0be98 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Fri, 27 Oct 2023 17:04:45 +0530 Subject: [PATCH 065/108] JAVA-26393 Move couchbase to persistence-modules (#15059) --- {couchbase => persistence-modules/couchbase}/.gitignore | 0 {couchbase => persistence-modules/couchbase}/README.md | 0 {couchbase => persistence-modules/couchbase}/mvnw | 0 {couchbase => persistence-modules/couchbase}/mvnw.cmd | 0 {couchbase => persistence-modules/couchbase}/pom.xml | 2 +- .../java/com/baeldung/couchbase/async/CouchbaseEntity.java | 0 .../main/java/com/baeldung/couchbase/async/person/Person.java | 0 .../baeldung/couchbase/async/person/PersonCrudService.java | 0 .../couchbase/async/person/PersonDocumentConverter.java | 0 .../baeldung/couchbase/async/person/RegistrationService.java | 0 .../couchbase/async/service/AbstractBucketService.java | 0 .../baeldung/couchbase/async/service/AbstractCrudService.java | 0 .../com/baeldung/couchbase/async/service/BucketService.java | 0 .../com/baeldung/couchbase/async/service/ClusterService.java | 0 .../baeldung/couchbase/async/service/ClusterServiceImpl.java | 0 .../com/baeldung/couchbase/async/service/CrudService.java | 0 .../couchbase/async/service/JsonDocumentConverter.java | 0 .../couchbase/async/service/TutorialBucketService.java | 0 .../main/java/com/baeldung/couchbase/intro/CodeSnippets.java | 0 .../baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java | 0 .../baeldung/couchbase/mapreduce/DuplicateKeyException.java | 0 .../com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java | 0 .../java/com/baeldung/couchbase/mapreduce/StudentGrade.java | 0 .../couchbase/mapreduce/StudentGradeKeyGenerator.java | 0 .../couchbase/mapreduce/StudentGradeQueryBuilder.java | 0 .../com/baeldung/couchbase/mapreduce/StudentGradeService.java | 0 .../main/java/com/baeldung/couchbase/n1ql/BucketFactory.java | 0 .../main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java | 0 .../java/com/baeldung/couchbase/spring/person/Person.java | 0 .../baeldung/couchbase/spring/person/PersonCrudService.java | 0 .../couchbase/spring/person/PersonDocumentConverter.java | 0 .../baeldung/couchbase/spring/person/RegistrationService.java | 0 .../com/baeldung/couchbase/spring/service/BucketService.java | 0 .../com/baeldung/couchbase/spring/service/ClusterService.java | 0 .../baeldung/couchbase/spring/service/ClusterServiceImpl.java | 0 .../com/baeldung/couchbase/spring/service/CrudService.java | 0 .../couchbase/spring/service/JsonDocumentConverter.java | 0 .../couchbase/spring/service/TutorialBucketService.java | 0 .../couchbase}/src/main/resources/application.properties | 0 .../couchbase}/src/main/resources/logback.xml | 0 .../com/baeldung/couchbase/async/AsyncIntegrationTest.java | 0 .../baeldung/couchbase/async/AsyncIntegrationTestConfig.java | 0 .../async/person/PersonCrudServiceIntegrationTestConfig.java | 0 .../couchbase/async/person/PersonCrudServiceLiveTest.java | 0 .../couchbase/async/service/ClusterServiceLiveTest.java | 0 .../couchbase/mapreduce/StudentGradeServiceLiveTest.java | 0 .../com/baeldung/couchbase/n1ql/IntegrationTestConfig.java | 0 .../test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java | 0 .../java/com/baeldung/couchbase/spring/IntegrationTest.java | 0 .../com/baeldung/couchbase/spring/IntegrationTestConfig.java | 0 .../couchbase/spring/person/PersonCrudServiceLiveTest.java | 0 .../couchbase/spring/service/ClusterServiceLiveTest.java | 0 .../couchbase}/src/test/resources/logback.xml | 0 persistence-modules/pom.xml | 1 + pom.xml | 4 +--- 55 files changed, 3 insertions(+), 4 deletions(-) rename {couchbase => persistence-modules/couchbase}/.gitignore (100%) rename {couchbase => persistence-modules/couchbase}/README.md (100%) rename {couchbase => persistence-modules/couchbase}/mvnw (100%) rename {couchbase => persistence-modules/couchbase}/mvnw.cmd (100%) rename {couchbase => persistence-modules/couchbase}/pom.xml (98%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/person/Person.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/service/BucketService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/service/CrudService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/spring/person/Person.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java (100%) rename {couchbase => persistence-modules/couchbase}/src/main/resources/application.properties (100%) rename {couchbase => persistence-modules/couchbase}/src/main/resources/logback.xml (100%) rename {couchbase => persistence-modules/couchbase}/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java (100%) rename {couchbase => persistence-modules/couchbase}/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java (100%) rename {couchbase => persistence-modules/couchbase}/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java (100%) rename {couchbase => persistence-modules/couchbase}/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java (100%) rename {couchbase => persistence-modules/couchbase}/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java (100%) rename {couchbase => persistence-modules/couchbase}/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java (100%) rename {couchbase => persistence-modules/couchbase}/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java (100%) rename {couchbase => persistence-modules/couchbase}/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java (100%) rename {couchbase => persistence-modules/couchbase}/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java (100%) rename {couchbase => persistence-modules/couchbase}/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java (100%) rename {couchbase => persistence-modules/couchbase}/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java (100%) rename {couchbase => persistence-modules/couchbase}/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java (100%) rename {couchbase => persistence-modules/couchbase}/src/test/resources/logback.xml (100%) diff --git a/couchbase/.gitignore b/persistence-modules/couchbase/.gitignore similarity index 100% rename from couchbase/.gitignore rename to persistence-modules/couchbase/.gitignore diff --git a/couchbase/README.md b/persistence-modules/couchbase/README.md similarity index 100% rename from couchbase/README.md rename to persistence-modules/couchbase/README.md diff --git a/couchbase/mvnw b/persistence-modules/couchbase/mvnw similarity index 100% rename from couchbase/mvnw rename to persistence-modules/couchbase/mvnw diff --git a/couchbase/mvnw.cmd b/persistence-modules/couchbase/mvnw.cmd similarity index 100% rename from couchbase/mvnw.cmd rename to persistence-modules/couchbase/mvnw.cmd diff --git a/couchbase/pom.xml b/persistence-modules/couchbase/pom.xml similarity index 98% rename from couchbase/pom.xml rename to persistence-modules/couchbase/pom.xml index 823b33ee29..b98c0cc387 100644 --- a/couchbase/pom.xml +++ b/persistence-modules/couchbase/pom.xml @@ -10,7 +10,7 @@ com.baeldung - parent-modules + persistence-modules 1.0.0-SNAPSHOT diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/CouchbaseEntity.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/person/Person.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/Person.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/person/Person.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/Person.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonCrudService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/PersonDocumentConverter.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/person/RegistrationService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractBucketService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/AbstractCrudService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/BucketService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/BucketService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/BucketService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/BucketService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/ClusterServiceImpl.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/CrudService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/CrudService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/CrudService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/CrudService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/JsonDocumentConverter.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/async/service/TutorialBucketService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/intro/CodeSnippets.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/CouchbaseKeyGenerator.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/DuplicateKeyException.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/RandomUUIDGenerator.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGrade.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeKeyGenerator.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeQueryBuilder.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/mapreduce/StudentGradeService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/n1ql/BucketFactory.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/n1ql/CodeSnippets.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/person/Person.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/Person.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/person/Person.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/Person.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonCrudService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/PersonDocumentConverter.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/person/RegistrationService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/BucketService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/ClusterServiceImpl.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/CrudService.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/JsonDocumentConverter.java diff --git a/couchbase/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java b/persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java similarity index 100% rename from couchbase/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java rename to persistence-modules/couchbase/src/main/java/com/baeldung/couchbase/spring/service/TutorialBucketService.java diff --git a/couchbase/src/main/resources/application.properties b/persistence-modules/couchbase/src/main/resources/application.properties similarity index 100% rename from couchbase/src/main/resources/application.properties rename to persistence-modules/couchbase/src/main/resources/application.properties diff --git a/couchbase/src/main/resources/logback.xml b/persistence-modules/couchbase/src/main/resources/logback.xml similarity index 100% rename from couchbase/src/main/resources/logback.xml rename to persistence-modules/couchbase/src/main/resources/logback.xml diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/AsyncIntegrationTestConfig.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceIntegrationTestConfig.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/person/PersonCrudServiceLiveTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/async/service/ClusterServiceLiveTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/mapreduce/StudentGradeServiceLiveTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/n1ql/IntegrationTestConfig.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/n1ql/N1QLLiveTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/IntegrationTestConfig.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/person/PersonCrudServiceLiveTest.java diff --git a/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java b/persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java similarity index 100% rename from couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java rename to persistence-modules/couchbase/src/test/java/com/baeldung/couchbase/spring/service/ClusterServiceLiveTest.java diff --git a/couchbase/src/test/resources/logback.xml b/persistence-modules/couchbase/src/test/resources/logback.xml similarity index 100% rename from couchbase/src/test/resources/logback.xml rename to persistence-modules/couchbase/src/test/resources/logback.xml diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index a99a180390..53e408c3a5 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -21,6 +21,7 @@ blaze-persistence core-java-persistence core-java-persistence-2 + couchbase elasticsearch flyway flyway-repair diff --git a/pom.xml b/pom.xml index a5abb59502..17a914d619 100644 --- a/pom.xml +++ b/pom.xml @@ -765,7 +765,6 @@ aws-modules checker-framework - couchbase core-groovy-modules core-java-modules @@ -1035,8 +1034,7 @@ aws-modules checker-framework - couchbase - + core-groovy-modules core-java-modules From ce6640a476d145fe54b2ebb39c01e184e8544e8e Mon Sep 17 00:00:00 2001 From: Ehsan Sasanianno Date: Fri, 27 Oct 2023 18:42:59 +0200 Subject: [PATCH 066/108] 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 3c8d10dd828178d786a7dcb978991c7688913006 Mon Sep 17 00:00:00 2001 From: Anton Dalagan Date: Fri, 27 Oct 2023 18:44:07 +0200 Subject: [PATCH 067/108] Bael 7146 improvement to this article convert double to float in java (#15067) * Commit 1 - Anton Dalagan Code for Evaluation article. Contains Unit tests, domain class, and App main method. * BAEL-7146 Updated the unit test to display the results of the conversion. This will be explained in the article itself. * BAEL-7146 cleaned up pR --- .../FloatDoubleConversionsTest.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsTest.java index 9c6b01e9de..9da50276a9 100644 --- a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsTest.java +++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/floatdoubleconversions/FloatDoubleConversionsTest.java @@ -7,23 +7,27 @@ public class FloatDoubleConversionsTest { @Test public void whenDoubleType_thenFloatTypeSuccess(){ - double interestRatesYearly = 13.333333333333334; + double interestRatesYearly = 13.333333333333333; float interest = (float) interestRatesYearly; - Assert.assertEquals(13.333333f, interest, 0.000004f); + System.out.println(interest); //13.333333 + Assert.assertEquals(13.333333f, interest, 0.000001f); - Double monthlyRates = 2.111111111111112; + Double monthlyRates = 2.111111111111111; float rates = monthlyRates.floatValue(); - Assert.assertEquals(2.1111112f, rates, 0.00000013); + System.out.println(rates); //2.1111112 + Assert.assertEquals(2.1111111f, rates, 0.0000001f); } @Test public void whenFloatType_thenDoubleTypeSuccess(){ float gradeAverage =2.05f; double average = gradeAverage; - Assert.assertEquals(2.05, average, 0.06); + System.out.println(average); //2.049999952316284 + Assert.assertEquals(2.05, average, 0.01); - Float monthlyRates = 2.1111112f; + Float monthlyRates = 2.1111111f; Double rates = monthlyRates.doubleValue(); - Assert.assertEquals(2.11111112, rates, 0.0000002);//true + System.out.println(rates); //2.1111111640930176 + Assert.assertEquals(2.11111111, rates, 0.0000001);//true } } From 65411d9deec5338b3a2f9f9425649432c5d27fa2 Mon Sep 17 00:00:00 2001 From: Mo Helmy <135069400+BenHelmyBen@users.noreply.github.com> Date: Fri, 27 Oct 2023 18:49:21 +0200 Subject: [PATCH 068/108] This commit is related to the article BAEL-7084 (#15070) This commit aims to add a test class "XMLStringToDocumentObjectUnitTest.java" that provides a test method to convert XML string into a Document object in Java. --- .../XMLStringToDocumentObjectUnitTest.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 xml-2/src/test/java/com/baeldung/xml/xml2document/XMLStringToDocumentObjectUnitTest.java diff --git a/xml-2/src/test/java/com/baeldung/xml/xml2document/XMLStringToDocumentObjectUnitTest.java b/xml-2/src/test/java/com/baeldung/xml/xml2document/XMLStringToDocumentObjectUnitTest.java new file mode 100644 index 0000000000..f573e1c96d --- /dev/null +++ b/xml-2/src/test/java/com/baeldung/xml/xml2document/XMLStringToDocumentObjectUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.xml2document; + +import org.junit.Test; +import org.w3c.dom.*; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import java.io.IOException; +import java.io.StringReader; + +import static org.junit.Assert.assertEquals; + +public class XMLStringToDocumentObjectUnitTest { + @Test + public void givenValidXMLString_whenParsing_thenDocumentIsCorrect() throws ParserConfigurationException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + String xmlString = "XML Parsing Example"; + InputSource is = new InputSource(new StringReader(xmlString)); + Document xmlDoc = null; + try { + xmlDoc = builder.parse(is); + } catch (SAXException e) { + throw new RuntimeException(e); + } catch (IOException e) { + throw new RuntimeException(e); + } + + assertEquals("root", xmlDoc.getDocumentElement().getNodeName()); + assertEquals("element", xmlDoc.getDocumentElement().getElementsByTagName("element").item(0).getNodeName()); + assertEquals("XML Parsing Example", xmlDoc.getDocumentElement().getElementsByTagName("element").item(0).getTextContent()); + } +} From 0abadb03a59827d3382e521832e75ab3a0f8d8a3 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Fri, 27 Oct 2023 22:42:27 +0530 Subject: [PATCH 069/108] 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 6341e1844fd923825423c9cf445b3cf54f6bc154 Mon Sep 17 00:00:00 2001 From: Constantin <50400363+constantinurs@users.noreply.github.com> Date: Fri, 27 Oct 2023 21:31:28 +0300 Subject: [PATCH 070/108] BAEL-6769: Override Cucumber option values (#15078) --- spring-cucumber/pom.xml | 9 ++++- .../CucumberOptionsApplication.java | 13 +++++++ .../HealthCheckController.java | 22 +++++++++++ .../HealthCheckStepDefsIntegrationTest.java | 38 +++++++++++++++++++ .../cucumberoptions/healthcheck.feature | 11 ++++++ .../src/test/resources/cucumber.properties | 1 + 6 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 spring-cucumber/src/main/java/com/baeldung/cucumberoptions/CucumberOptionsApplication.java create mode 100644 spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java create mode 100644 spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java create mode 100644 spring-cucumber/src/test/resources/com/baeldung/cucumberoptions/healthcheck.feature create mode 100644 spring-cucumber/src/test/resources/cucumber.properties diff --git a/spring-cucumber/pom.xml b/spring-cucumber/pom.xml index c6c163d7d1..042e81971f 100644 --- a/spring-cucumber/pom.xml +++ b/spring-cucumber/pom.xml @@ -45,6 +45,12 @@ ${cucumber.version} test + + org.junit.vintage + junit-vintage-engine + ${junit-vintage-engine.version} + test + org.apache.commons @@ -54,8 +60,9 @@ - 6.8.0 + 7.14.0 1.3.2 + 5.10.0 \ No newline at end of file diff --git a/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/CucumberOptionsApplication.java b/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/CucumberOptionsApplication.java new file mode 100644 index 0000000000..03082128b3 --- /dev/null +++ b/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/CucumberOptionsApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.cucumberoptions; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CucumberOptionsApplication { + + public static void main(String[] args) { + SpringApplication.run(CucumberOptionsApplication.class, args); + } + +} \ No newline at end of file diff --git a/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java b/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java new file mode 100644 index 0000000000..637dbdb540 --- /dev/null +++ b/spring-cucumber/src/main/java/com/baeldung/cucumberoptions/HealthCheckController.java @@ -0,0 +1,22 @@ +package com.baeldung.cucumberoptions; + +import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HealthCheckController { + + @GetMapping(path = "/v1/status", produces = APPLICATION_JSON_VALUE) + public HttpStatus getV1Status() { + return ResponseEntity.ok().build().getStatusCode(); + } + + @GetMapping(path = "/v2/status", produces = APPLICATION_JSON_VALUE) + public HttpStatus getV2Status() { + return ResponseEntity.ok().build().getStatusCode(); + } +} \ No newline at end of file diff --git a/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java b/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java new file mode 100644 index 0000000000..999adadbef --- /dev/null +++ b/spring-cucumber/src/test/java/com/baeldung/cucumberoptions/HealthCheckStepDefsIntegrationTest.java @@ -0,0 +1,38 @@ +package com.baeldung.cucumberoptions; + +import io.cucumber.java.en.Then; +import io.cucumber.java.en.When; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + +import com.baeldung.SpringIntegrationTest; + +public class HealthCheckStepDefsIntegrationTest extends SpringIntegrationTest { + + private ResponseEntity statusResponse; + + private ResponseEntity doGet(String url) { + return new RestTemplate().getForEntity(url, String.class); + } + + @When("^the client calls /v1/status") + public void checkV1Status() throws Throwable { + statusResponse = doGet("http://localhost:8082/v1/status"); + } + + @When("^the client calls /v2/status") + public void checkV2Status() throws Throwable { + statusResponse = doGet("http://localhost:8082/v2/status"); + } + + @Then("^the client receives (\\d+) status code$") + public void verifyStatusCode(int statusCode) throws Throwable { + final HttpStatus currentStatusCode = statusResponse.getStatusCode(); + assertThat(currentStatusCode.value(), is(statusCode)); + } +} \ No newline at end of file diff --git a/spring-cucumber/src/test/resources/com/baeldung/cucumberoptions/healthcheck.feature b/spring-cucumber/src/test/resources/com/baeldung/cucumberoptions/healthcheck.feature new file mode 100644 index 0000000000..33e07c1add --- /dev/null +++ b/spring-cucumber/src/test/resources/com/baeldung/cucumberoptions/healthcheck.feature @@ -0,0 +1,11 @@ +Feature: healthcheck endpoints can be verified + + @v1 + Scenario: v1 status is healthy + When the client calls /v1/status + Then the client receives 200 status code + + @v2 + Scenario: v2 status is healthy + When the client calls /v2/status + Then the client receives 200 status code diff --git a/spring-cucumber/src/test/resources/cucumber.properties b/spring-cucumber/src/test/resources/cucumber.properties new file mode 100644 index 0000000000..22c3379201 --- /dev/null +++ b/spring-cucumber/src/test/resources/cucumber.properties @@ -0,0 +1 @@ +cucumber.filter.tags=not @v2 \ No newline at end of file From 2db8c97c1f338b2a5257baea7e9e73cf6d5197b0 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Sat, 28 Oct 2023 12:45:52 +0530 Subject: [PATCH 071/108] JAVA-25111: Changes made for reoving duplicate module (#15076) --- pom.xml | 1 - 1 file changed, 1 deletion(-) diff --git a/pom.xml b/pom.xml index 17a914d619..07b9d6d842 100644 --- a/pom.xml +++ b/pom.xml @@ -1211,7 +1211,6 @@ gradle-modules/gradle/maven-to-gradle persistence-modules/spring-data-neo4j spring-actuator - gcp-firebase spring-di-4 spring-kafka-2 From 235cba0dbd10cf7579002b2156535b54965bab88 Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 28 Oct 2023 13:08:15 +0530 Subject: [PATCH 072/108] updated backlink --- core-java-modules/core-java-8/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-8/README.md b/core-java-modules/core-java-8/README.md index 6061f3318d..0921c1538a 100644 --- a/core-java-modules/core-java-8/README.md +++ b/core-java-modules/core-java-8/README.md @@ -11,5 +11,5 @@ This module contains articles about Java 8 core features - [Finding Min/Max in an Array with Java](https://www.baeldung.com/java-array-min-max) - [Internationalization and Localization in Java 8](https://www.baeldung.com/java-8-localization) - [Generalized Target-Type Inference in Java](https://www.baeldung.com/java-generalized-target-type-inference) -- [Monads in Java](https://www.baeldung.com/java-monads) +- [Monads in Java – Optional](https://www.baeldung.com/java-monads) - [[More -->]](/core-java-modules/core-java-8-2) From 30523bdc89d568c05999d074f994187e106370ad Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 28 Oct 2023 13:24:41 +0530 Subject: [PATCH 073/108] backlink removed --- aws-modules/aws-miscellaneous/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/aws-modules/aws-miscellaneous/README.md b/aws-modules/aws-miscellaneous/README.md index 5be8e6a3f2..104c8719df 100644 --- a/aws-modules/aws-miscellaneous/README.md +++ b/aws-modules/aws-miscellaneous/README.md @@ -5,6 +5,5 @@ This module contains articles about various Amazon Web Services (AWS) such as EC ### Relevant articles - [Managing EC2 Instances in Java](https://www.baeldung.com/ec2-java) -- [Integration Testing with a Local DynamoDB Instance](https://www.baeldung.com/dynamodb-local-integration-tests) - [Managing Amazon SQS Queues in Java](https://www.baeldung.com/aws-queues-java) - [Guide to AWS Aurora RDS with Java](https://www.baeldung.com/aws-aurora-rds-java) From 96b32de7ba49b06580c79efe00ac998d176f1aaf Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 28 Oct 2023 14:33:07 +0530 Subject: [PATCH 074/108] backlink added --- core-java-modules/core-java-string-operations-7/README.md | 1 + 1 file changed, 1 insertion(+) 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 2dce44d217..7020369f02 100644 --- a/core-java-modules/core-java-string-operations-7/README.md +++ b/core-java-modules/core-java-string-operations-7/README.md @@ -1,2 +1,3 @@ ### Relevant Articles: +[How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output) From 3042166f4bb63d2e542df96ca8aa67f4a1fafc1c Mon Sep 17 00:00:00 2001 From: collaboratewithakash <38683470+collaboratewithakash@users.noreply.github.com> Date: Sat, 28 Oct 2023 14:39:02 +0530 Subject: [PATCH 075/108] readme created or backlink added --- core-java-modules/core-java-concurrency-advanced-5/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-advanced-5/README.md diff --git a/core-java-modules/core-java-concurrency-advanced-5/README.md b/core-java-modules/core-java-concurrency-advanced-5/README.md new file mode 100644 index 0000000000..ba845a7c4b --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-5/README.md @@ -0,0 +1,3 @@ + +### Relevant Articles: +- [Why wait() Requires Synchronization?](https://www.baeldung.com/java-wait-necessary-synchronization) From c65981938f9be61a5182259c911462a21671a940 Mon Sep 17 00:00:00 2001 From: lucaCambi77 Date: Sat, 28 Oct 2023 23:56:11 +0200 Subject: [PATCH 076/108] [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 077/108] 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 078/108] 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 079/108] 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 080/108] 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 081/108] 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 082/108] 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 083/108] 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 084/108] 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 085/108] 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 086/108] 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 087/108] 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 088/108] 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 089/108] 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 090/108] 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 091/108] 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 092/108] 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 093/108] 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 094/108] 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 095/108] [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 096/108] 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 097/108] 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 098/108] 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 099/108] 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 100/108] 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 101/108] 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 102/108] 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 103/108] 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 104/108] 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 105/108] 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 106/108] 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 107/108] 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 108/108] 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 +}