diff --git a/akka-modules/pom.xml b/akka-modules/pom.xml index 60432c4eea..be0b8aa891 100644 --- a/akka-modules/pom.xml +++ b/akka-modules/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 akka-modules - akka-modules pom + akka-modules parent-modules diff --git a/apache-cxf-modules/cxf-spring/pom.xml b/apache-cxf-modules/cxf-spring/pom.xml index 234a19eebc..e1e5033e2d 100644 --- a/apache-cxf-modules/cxf-spring/pom.xml +++ b/apache-cxf-modules/cxf-spring/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 cxf-spring - cxf-spring war + cxf-spring com.baeldung diff --git a/apache-cxf-modules/pom.xml b/apache-cxf-modules/pom.xml index 245a31614b..a571f5477c 100644 --- a/apache-cxf-modules/pom.xml +++ b/apache-cxf-modules/pom.xml @@ -5,8 +5,9 @@ 4.0.0 apache-cxf-modules 0.0.1-SNAPSHOT - apache-cxf-modules pom + apache-cxf-modules + com.baeldung diff --git a/apache-cxf-modules/sse-jaxrs/pom.xml b/apache-cxf-modules/sse-jaxrs/pom.xml index baa32a516a..2fade99152 100644 --- a/apache-cxf-modules/sse-jaxrs/pom.xml +++ b/apache-cxf-modules/sse-jaxrs/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 sse-jaxrs - sse-jaxrs pom + sse-jaxrs com.baeldung diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml index 3bd3e5cb27..13ec2a681f 100644 --- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml +++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 sse-jaxrs-server - sse-jaxrs-server war + sse-jaxrs-server com.baeldung diff --git a/apache-httpclient4/pom.xml b/apache-httpclient4/pom.xml index 48d39b0858..89e85fc1b4 100644 --- a/apache-httpclient4/pom.xml +++ b/apache-httpclient4/pom.xml @@ -5,8 +5,8 @@ 4.0.0 apache-httpclient4 0.1-SNAPSHOT - apache-httpclient4 war + apache-httpclient4 com.baeldung @@ -193,7 +193,6 @@ true - diff --git a/apache-libraries-2/pom.xml b/apache-libraries-2/pom.xml index 2e7ef0344c..9b8d5d9ad4 100644 --- a/apache-libraries-2/pom.xml +++ b/apache-libraries-2/pom.xml @@ -24,14 +24,12 @@ camel-core ${camel.version} - org.apache.camel camel-test-junit5 ${camel.version} test - org.apache.camel camel-main diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index fbb6e9ba5e..210ea4f28b 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -5,8 +5,8 @@ 4.0.0 apache-spark 1.0-SNAPSHOT - apache-spark jar + apache-spark com.baeldung diff --git a/apache-thrift/pom.xml b/apache-thrift/pom.xml index d2623f92e7..f5c5dec928 100644 --- a/apache-thrift/pom.xml +++ b/apache-thrift/pom.xml @@ -5,8 +5,8 @@ 4.0.0 apache-thrift 0.0.1-SNAPSHOT - apache-thrift pom + apache-thrift com.baeldung diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml index 4718ad2f62..5dd56a1d68 100644 --- a/apache-velocity/pom.xml +++ b/apache-velocity/pom.xml @@ -5,8 +5,8 @@ 4.0.0 apache-velocity 0.1-SNAPSHOT - apache-velocity war + apache-velocity com.baeldung diff --git a/aws-modules/aws-dynamodb/pom.xml b/aws-modules/aws-dynamodb/pom.xml index 199b9a187e..6d1ad5ad34 100644 --- a/aws-modules/aws-dynamodb/pom.xml +++ b/aws-modules/aws-dynamodb/pom.xml @@ -5,8 +5,8 @@ 4.0.0 aws-dynamodb 0.1.0-SNAPSHOT - aws-dynamodb jar + aws-dynamodb com.baeldung diff --git a/aws-modules/aws-lambda-modules/lambda-function/pom.xml b/aws-modules/aws-lambda-modules/lambda-function/pom.xml index 8c56aaabed..9a24802e3f 100644 --- a/aws-modules/aws-lambda-modules/lambda-function/pom.xml +++ b/aws-modules/aws-lambda-modules/lambda-function/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 lambda-function - 0.1.0-SNAPSHOT lambda-function + 0.1.0-SNAPSHOT jar diff --git a/aws-modules/aws-lambda-modules/pom.xml b/aws-modules/aws-lambda-modules/pom.xml index 9886ff58d2..a4b7197fee 100644 --- a/aws-modules/aws-lambda-modules/pom.xml +++ b/aws-modules/aws-lambda-modules/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 aws-lambda-modules - aws-lambda-modules pom + aws-lambda-modules com.baeldung diff --git a/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml index 74a21068ee..0f294fabeb 100644 --- a/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml +++ b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 ShippingFunction - 1.0 ShippingFunction + 1.0 jar diff --git a/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml index 8eb0879237..acc14b55ff 100644 --- a/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml +++ b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml @@ -4,8 +4,8 @@ 4.0.0 helloworld ToDoFunction - 1.0 ToDoFunction + 1.0 jar diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml index 8a90ec8cc9..2e42cff0c3 100644 --- a/aws-modules/aws-miscellaneous/pom.xml +++ b/aws-modules/aws-miscellaneous/pom.xml @@ -5,8 +5,8 @@ 4.0.0 aws-miscellaneous 0.1.0-SNAPSHOT - aws-miscellaneous jar + aws-miscellaneous com.baeldung diff --git a/aws-modules/aws-s3/pom.xml b/aws-modules/aws-s3/pom.xml index f63158b889..09ab7649d6 100644 --- a/aws-modules/aws-s3/pom.xml +++ b/aws-modules/aws-s3/pom.xml @@ -5,8 +5,8 @@ 4.0.0 aws-s3 0.1.0-SNAPSHOT - aws-s3 jar + aws-s3 com.baeldung @@ -26,7 +26,6 @@ ${aws.java.sdk.version} test - commons-io commons-io @@ -56,7 +55,6 @@ ${com.adobe.testing.version} test - org.testcontainers junit-jupiter diff --git a/aws-modules/pom.xml b/aws-modules/pom.xml index 6d5f3fb168..c6bf59c1b2 100644 --- a/aws-modules/pom.xml +++ b/aws-modules/pom.xml @@ -4,6 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 aws-modules + pom aws-modules @@ -12,16 +13,6 @@ 1.0.0-SNAPSHOT - - - com.amazonaws - aws-java-sdk-dynamodb - 1.12.523 - compile - - - pom - aws-app-sync aws-dynamodb @@ -31,6 +22,15 @@ aws-s3 + + + com.amazonaws + aws-java-sdk-dynamodb + 1.12.523 + compile + + + 1.12.331 2.24.9 diff --git a/azure/pom.xml b/azure/pom.xml index 6a06282a71..61ae0c7d68 100644 --- a/azure/pom.xml +++ b/azure/pom.xml @@ -5,8 +5,8 @@ 4.0.0 azure 0.1 - azure war + azure Demo project for Spring Boot on Azure diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/checkiftimebetweentwotimes/CheckIfTimeBetweenTwoTimesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/checkiftimebetweentwotimes/CheckIfTimeBetweenTwoTimesUnitTest.java new file mode 100644 index 0000000000..1ffddaa241 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/checkiftimebetweentwotimes/CheckIfTimeBetweenTwoTimesUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.checkiftimebetweentwotimes; + +import org.junit.Test; + +import java.time.LocalTime; +import java.util.Calendar; +import java.util.Date; + +import static org.junit.Assert.assertTrue; + +public class CheckIfTimeBetweenTwoTimesUnitTest { + private LocalTime startTime = LocalTime.parse("09:00:00"); + private LocalTime endTime = LocalTime.parse("17:00:00"); + private LocalTime targetTime = LocalTime.parse("12:30:00"); + + @Test + public void givenLocalTime_whenUsingIsAfterIsBefore_thenTimeIsBetween() { + assertTrue(!targetTime.isBefore(startTime) && !targetTime.isAfter(endTime)); + } + + @Test + public void givenLocalTime_whenUsingCompareTo_thenTimeIsBetween() { + assertTrue(targetTime.compareTo(startTime) >= 0 && targetTime.compareTo(endTime) <= 0); + } + + @Test + public void givenDate_whenUsingAfterBefore_thenTimeIsBetween() { + Calendar startCalendar = Calendar.getInstance(); + startCalendar.set(Calendar.HOUR_OF_DAY, 9); + startCalendar.set(Calendar.MINUTE, 0); + Date startTime = startCalendar.getTime(); + + Calendar endCalendar = Calendar.getInstance(); + endCalendar.set(Calendar.HOUR_OF_DAY, 17); + endCalendar.set(Calendar.MINUTE, 0); + Date endTime = endCalendar.getTime(); + + Calendar targetCalendar = Calendar.getInstance(); + targetCalendar.set(Calendar.HOUR_OF_DAY, 12); + targetCalendar.set(Calendar.MINUTE, 30); + Date targetTime = targetCalendar.getTime(); + + assertTrue(!targetTime.before(startTime) && !targetTime.after(endTime)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-math-4/README.md b/core-java-modules/core-java-lang-math-4/README.md new file mode 100644 index 0000000000..0c28f94821 --- /dev/null +++ b/core-java-modules/core-java-lang-math-4/README.md @@ -0,0 +1,3 @@ +========= + +### Relevant articles: diff --git a/core-java-modules/core-java-lang-math-4/pom.xml b/core-java-modules/core-java-lang-math-4/pom.xml new file mode 100644 index 0000000000..e818855d36 --- /dev/null +++ b/core-java-modules/core-java-lang-math-4/pom.xml @@ -0,0 +1,15 @@ + + + 4.0.0 + core-java-lang-math-4 + core-java-lang-math-4 + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + diff --git a/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java b/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java new file mode 100644 index 0000000000..7b46b37e38 --- /dev/null +++ b/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java @@ -0,0 +1,78 @@ +package com.baeldung.percentile; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.junit.jupiter.api.Test; + +public class CalculatePercentileUnitTest { + + public static > T getPercentile(Collection input, double percentile) { + if (input == null || input.isEmpty()) { + throw new IllegalArgumentException("The input dataset cannot be null or empty."); + } + if (percentile < 0 || percentile > 100) { + throw new IllegalArgumentException("Percentile must be between 0 and 100(exclusive)"); + } + List sortedList = input.stream() + .sorted() + .collect(Collectors.toList()); + + int rank = percentile == 0 ? 1 : (int) Math.ceil(percentile / 100.0 * input.size()); + return sortedList.get(rank - 1); + } + + @Test + void whenCallingGetPercentileWithAList_thenGetExpectedResult() { + assertThrows(IllegalArgumentException.class, () -> getPercentile(List.of(1, 2, 3), -1)); + assertThrows(IllegalArgumentException.class, () -> getPercentile(List.of(1, 2, 3), 101)); + + List list100 = IntStream.rangeClosed(1, 100) + .boxed() + .collect(Collectors.toList()); + Collections.shuffle(list100); + + assertEquals(1, getPercentile(list100, 0)); + assertEquals(10, getPercentile(list100, 10)); + assertEquals(25, getPercentile(list100, 25)); + assertEquals(50, getPercentile(list100, 50)); + assertEquals(76, getPercentile(list100, 75.3)); + assertEquals(100, getPercentile(list100, 100)); + + List list8 = IntStream.of(-1, 200, 30, 42, -5, 7, 8, 92) + .boxed() + .collect(Collectors.toList()); + + assertEquals(-5, getPercentile(list8, 0)); + assertEquals(-5, getPercentile(list8, 10)); + assertEquals(-1, getPercentile(list8, 25)); + assertEquals(8, getPercentile(list8, 50)); + assertEquals(92, getPercentile(list8, 75.3)); + assertEquals(200, getPercentile(list8, 100)); + } + + @Test + void whenCallingGetPercentileWithAnArray_thenGetExpectedResult() { + + long[] theArray = new long[] { -1, 200, 30, 42, -5, 7, 8, 92 }; + + //convert the long[] array to a List + List list8 = Arrays.stream(theArray) + .boxed() + .toList(); + + assertEquals(-5, getPercentile(list8, 0)); + assertEquals(-5, getPercentile(list8, 10)); + assertEquals(-1, getPercentile(list8, 25)); + assertEquals(8, getPercentile(list8, 50)); + assertEquals(92, getPercentile(list8, 75.3)); + assertEquals(200, getPercentile(list8, 100)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/integersatbitlevel/IntegersBitLevelUnitTest.java b/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/integersatbitlevel/IntegersBitLevelUnitTest.java new file mode 100644 index 0000000000..54c0b89d03 --- /dev/null +++ b/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/integersatbitlevel/IntegersBitLevelUnitTest.java @@ -0,0 +1,66 @@ +package com.baeldung.integersatbitlevel; + +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.assertEquals; + +class IntegersBitLevelUnitTest { + + @Test + void givenNumbers_whenBitwiseAND_thenResultIsExpected() { + int result = 0b1100 & 0b0111; + assertEquals(0b0100, result); + } + + @Test + void givenNumbers_whenBitwiseOR_thenResultIsExpected() { + int result = 0b1100 | 0b0111; + assertEquals(0b1111, result); + } + + @Test + void givenNumbers_whenBitwiseXOR_thenResultIsExpected() { + int result = 0b1100 ^ 0b0111; + assertEquals(0b1011, result); + } + + @Test + void givenNumber_whenBitwiseNOT_thenResultIsExpected() { + int result = ~0b0101; + assertEquals(-0b0110, result); + } + + @Test + void givenNumber_whenBitwiseLeftShift_thenResultIsExpected() { + int result = 0b0101 << 2; + assertEquals(0b10100, result); + } + + @Test + void givenNumber_whenBitwiseRightShift_thenResultIsExpected() { + int result = 0b0101 >> 1; + assertEquals(0b10, result); + } + + @Test + void givenOriginalColor_whenApplyingMask_thenObtainModifiedColor() { + int originalColor = 0xFF336699; + + int alphaMask = 0xFF000000; + int redMask = 0x00FF0000; + int greenMask = 0x0000FF00; + int blueMask = 0x000000FF; + + int alpha = (originalColor & alphaMask) >>> 24; + int red = (originalColor & redMask) >>> 16; + int green = (originalColor & greenMask) >>> 8; + int blue = originalColor & blueMask; + + red = Math.min(255, red + 50); + green = Math.min(255, green + 30); + + int modifiedColor = (alpha << 24) | (red << 16) | (green << 8) | blue; + + assertEquals(-10124135, modifiedColor); + } +} diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index b79248841f..6e7264dcdd 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -55,7 +55,7 @@ - 1.7 + 1.8.0 5.1.1 1.10.0 diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 36b589ca75..85df51457c 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -144,6 +144,7 @@ core-java-lang-6 core-java-lang-math core-java-lang-math-2 + core-java-lang-math-4 core-java-lang-oop-constructors core-java-lang-oop-patterns core-java-lang-oop-generics diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index deb5b34a39..bad7e8ecc1 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 deeplearning4j - deeplearning4j jar + deeplearning4j com.baeldung diff --git a/di-modules/guice/pom.xml b/di-modules/guice/pom.xml index d0d2876fc8..115bae5e7b 100644 --- a/di-modules/guice/pom.xml +++ b/di-modules/guice/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 guice - guice jar + guice com.baeldung diff --git a/di-modules/pom.xml b/di-modules/pom.xml index 984180cb28..b07d436867 100644 --- a/di-modules/pom.xml +++ b/di-modules/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 di-modules - di-modules pom + di-modules parent-modules diff --git a/disruptor/pom.xml b/disruptor/pom.xml index b3b065d67e..942eb83e7c 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 disruptor - disruptor jar + disruptor com.baeldung diff --git a/docker-modules/docker-caching/multi-module-caching/pom.xml b/docker-modules/docker-caching/multi-module-caching/pom.xml index b9977f8f3a..3e9859a8d1 100644 --- a/docker-modules/docker-caching/multi-module-caching/pom.xml +++ b/docker-modules/docker-caching/multi-module-caching/pom.xml @@ -6,8 +6,8 @@ com.baeldung multi-module-caching 0.0.1-SNAPSHOT - Multi-module Maven caching example pom + Multi-module Maven caching example runner-module diff --git a/docker-modules/docker-caching/pom.xml b/docker-modules/docker-caching/pom.xml index 25572dfe4f..83cb7be9af 100644 --- a/docker-modules/docker-caching/pom.xml +++ b/docker-modules/docker-caching/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 docker-caching - docker-caching pom + docker-caching docker-modules diff --git a/docker-modules/docker-compose-2/pom.xml b/docker-modules/docker-compose-2/pom.xml index f7f01dc482..9d06aeb477 100644 --- a/docker-modules/docker-compose-2/pom.xml +++ b/docker-modules/docker-compose-2/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 docker-compose-2 - Demo project for Spring Boot and Docker - Module docker-compose-2 pom + Demo project for Spring Boot and Docker - Module docker-compose-2 com.baeldung diff --git a/geotools/pom.xml b/geotools/pom.xml index 61682ae0f5..026a902fa9 100644 --- a/geotools/pom.xml +++ b/geotools/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 geotools - geotools jar + geotools com.baeldung diff --git a/google-auto-project/pom.xml b/google-auto-project/pom.xml index 175e0c20c6..f91c0d56f4 100644 --- a/google-auto-project/pom.xml +++ b/google-auto-project/pom.xml @@ -5,8 +5,8 @@ 4.0.0 google-auto-project 1.0 - google-auto-project pom + google-auto-project com.baeldung diff --git a/google-cloud/pom.xml b/google-cloud/pom.xml index 8bb535f12a..b4cc3ba72f 100644 --- a/google-cloud/pom.xml +++ b/google-cloud/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 google-cloud - google-cloud jar + google-cloud Google Cloud Tutorials diff --git a/graphql-modules/pom.xml b/graphql-modules/pom.xml index 4b43cbffde..2525f75eff 100644 --- a/graphql-modules/pom.xml +++ b/graphql-modules/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.graphql graphql-modules - graphql-modules pom + graphql-modules com.baeldung diff --git a/grpc/pom.xml b/grpc/pom.xml index 758dc87c8f..31601a377e 100644 --- a/grpc/pom.xml +++ b/grpc/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 grpc - grpc jar + grpc com.baeldung diff --git a/guava-modules/pom.xml b/guava-modules/pom.xml index be5a48c0cf..6829a74e81 100644 --- a/guava-modules/pom.xml +++ b/guava-modules/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 guava-modules - guava-modules 0.0.1-SNAPSHOT pom + guava-modules com.baeldung diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index 50b6f0b9f2..aaf00b2588 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 httpclient-simple - httpclient-simple war + httpclient-simple com.baeldung diff --git a/jackson-modules/jackson-jr/pom.xml b/jackson-modules/jackson-jr/pom.xml index 868c3ee17f..fdd7d85c70 100644 --- a/jackson-modules/jackson-jr/pom.xml +++ b/jackson-modules/jackson-jr/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jackson-jr - jackson-jr pom + jackson-jr com.baeldung diff --git a/jackson-modules/pom.xml b/jackson-modules/pom.xml index f4980445b3..4b249f12d2 100644 --- a/jackson-modules/pom.xml +++ b/jackson-modules/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jackson-modules - jackson-modules 0.0.1-SNAPSHOT pom + jackson-modules com.baeldung diff --git a/java-blockchain/pom.xml b/java-blockchain/pom.xml index 422867176f..06838b8080 100644 --- a/java-blockchain/pom.xml +++ b/java-blockchain/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.blockchain java-blockchain - java-blockchain jar + java-blockchain com.baeldung diff --git a/java-jdi/pom.xml b/java-jdi/pom.xml index 22d7743998..935d2a23e4 100644 --- a/java-jdi/pom.xml +++ b/java-jdi/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 java-jdi - java-jdi jar + java-jdi com.baeldung diff --git a/java-panama/pom.xml b/java-panama/pom.xml index 61c8f2c5be..75835ac693 100644 --- a/java-panama/pom.xml +++ b/java-panama/pom.xml @@ -5,8 +5,8 @@ com.baeldung.java.panama java-panama 1.0 - java-panama jar + java-panama diff --git a/javax-sound/pom.xml b/javax-sound/pom.xml index 6652022a40..bea1d7f93b 100644 --- a/javax-sound/pom.xml +++ b/javax-sound/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.javax-sound javax-sound - javax-sound jar + javax-sound com.baeldung diff --git a/jenkins-modules/pom.xml b/jenkins-modules/pom.xml index 5cbc47d1f4..7543f82145 100644 --- a/jenkins-modules/pom.xml +++ b/jenkins-modules/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jenkins-modules - jenkins-modules pom + jenkins-modules parent-modules diff --git a/jetbrains/pom.xml b/jetbrains/pom.xml index 78d8b36b77..c1c7b8cdd8 100644 --- a/jetbrains/pom.xml +++ b/jetbrains/pom.xml @@ -5,8 +5,8 @@ 4.0.0 jetbrains 1.0-SNAPSHOT - jetbrains jar + jetbrains com.baeldung diff --git a/jgit/pom.xml b/jgit/pom.xml index 4e88808097..e91d3ae07b 100644 --- a/jgit/pom.xml +++ b/jgit/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jgit - jgit jar + jgit com.baeldung diff --git a/jhipster-6/pom.xml b/jhipster-6/pom.xml index f2406d1bdb..b51aca02e3 100644 --- a/jhipster-6/pom.xml +++ b/jhipster-6/pom.xml @@ -5,8 +5,8 @@ com.baeldung.jhipster jhipster-6 1.0.0-SNAPSHOT - jhipster-6 pom + jhipster-6 parent-boot-2 diff --git a/jhipster-modules/jhipster-uaa/pom.xml b/jhipster-modules/jhipster-uaa/pom.xml index 7c60f95e28..9085a07f0f 100644 --- a/jhipster-modules/jhipster-uaa/pom.xml +++ b/jhipster-modules/jhipster-uaa/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jhipster-uaa - jhipster-uaa pom + jhipster-uaa jhipster-modules diff --git a/jhipster-modules/pom.xml b/jhipster-modules/pom.xml index 1e11d97f40..810f2b0c59 100644 --- a/jhipster-modules/pom.xml +++ b/jhipster-modules/pom.xml @@ -6,8 +6,8 @@ com.baeldung.jhipster jhipster-modules 1.0.0-SNAPSHOT - jhipster-modules pom + jhipster-modules @@ -49,4 +44,10 @@ + + 3.1.2 + 3.1.2 + 5.3.1 + + \ No newline at end of file diff --git a/maven-modules/maven-build-optimization/pom.xml b/maven-modules/maven-build-optimization/pom.xml index 86d3b2d34f..30e96fb2be 100644 --- a/maven-modules/maven-build-optimization/pom.xml +++ b/maven-modules/maven-build-optimization/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-build-optimization 0.0.1-SNAPSHOT - maven-build-optimization pom + maven-build-optimization com.baeldung diff --git a/maven-modules/maven-copy-files/pom.xml b/maven-modules/maven-copy-files/pom.xml index e6ad639b21..90b40171a7 100644 --- a/maven-modules/maven-copy-files/pom.xml +++ b/maven-modules/maven-copy-files/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-copy-files 1.0-SNAPSHOT - maven-copy-files pom + maven-copy-files http://www.example.com diff --git a/maven-modules/maven-custom-plugin/counter-maven-plugin/pom.xml b/maven-modules/maven-custom-plugin/counter-maven-plugin/pom.xml index f2e4992d20..38e5119dd4 100644 --- a/maven-modules/maven-custom-plugin/counter-maven-plugin/pom.xml +++ b/maven-modules/maven-custom-plugin/counter-maven-plugin/pom.xml @@ -6,8 +6,8 @@ com.baeldung counter-maven-plugin 0.0.1-SNAPSHOT - counter-maven-plugin maven-plugin + counter-maven-plugin http://maven.apache.org diff --git a/maven-modules/maven-custom-plugin/pom.xml b/maven-modules/maven-custom-plugin/pom.xml index 731abe472d..2931789830 100644 --- a/maven-modules/maven-custom-plugin/pom.xml +++ b/maven-modules/maven-custom-plugin/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-custom-plugin 0.0.1-SNAPSHOT - maven-custom-plugin pom + maven-custom-plugin com.baeldung diff --git a/maven-modules/maven-generate-war/pom.xml b/maven-modules/maven-generate-war/pom.xml index 211a9ad6cb..ab2413385b 100644 --- a/maven-modules/maven-generate-war/pom.xml +++ b/maven-modules/maven-generate-war/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-generate-war 0.0.1-SNAPSHOT - maven-generate-war war + maven-generate-war Spring boot project to demonstrate war file generation diff --git a/maven-modules/maven-integration-test/pom.xml b/maven-modules/maven-integration-test/pom.xml index 9befb9f6b9..261a885ce3 100644 --- a/maven-modules/maven-integration-test/pom.xml +++ b/maven-modules/maven-integration-test/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-integration-test 0.0.1-SNAPSHOT - maven-integration-test war + maven-integration-test com.baeldung diff --git a/maven-modules/maven-polyglot/pom.xml b/maven-modules/maven-polyglot/pom.xml index 7ff375b9ba..3583563aba 100644 --- a/maven-modules/maven-polyglot/pom.xml +++ b/maven-modules/maven-polyglot/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-polyglot 0.0.1-SNAPSHOT - maven-polyglot pom + maven-polyglot com.baeldung diff --git a/maven-modules/maven-reactor/patient-web/pom.xml b/maven-modules/maven-reactor/patient-web/pom.xml index 9d2ddd819d..eb1ec57382 100644 --- a/maven-modules/maven-reactor/patient-web/pom.xml +++ b/maven-modules/maven-reactor/patient-web/pom.xml @@ -6,11 +6,13 @@ patient-web 1.0-SNAPSHOT patient-web + com.baeldung maven-reactor 1.0-SNAPSHOT + com.baeldung diff --git a/metrics/pom.xml b/metrics/pom.xml index a8f5e113e8..0e06a479c3 100644 --- a/metrics/pom.xml +++ b/metrics/pom.xml @@ -85,7 +85,7 @@ 4.2.17 0.13.2 - 1.11.0 + 1.12.3 3.1.0 1.2.0 1.7.7 diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java index 921459ac46..41924ad33f 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java @@ -9,7 +9,9 @@ import static org.junit.Assert.assertSame; import jakarta.persistence.PersistenceException; +import org.h2.tools.RunScript; import org.hibernate.HibernateException; +import org.hibernate.ReplicationMode; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; @@ -24,35 +26,58 @@ import org.junit.Test; import com.baeldung.persistence.model.Person; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.sql.Connection; +import java.sql.DriverManager; + /** * Testing specific implementation details for different methods: - * persist, save, merge, update, saveOrUpdate. + * persist, save, merge, update, saveOrUpdate, refresh, replicate */ public class SaveMethodsIntegrationTest { - private static SessionFactory sessionFactory; + private static SessionFactory sessionFactory1; - private Session session; + private static SessionFactory sessionFactory2; + + private Session session1; + + private Session session2; private boolean doNotCommit = false; - @BeforeClass - public static void beforeTests() { + private static SessionFactory createSessionFactoryAndInitializeDBs(String dbUrl) throws Exception { Configuration configuration = new Configuration().addAnnotatedClass(Person.class) - .setProperty("hibernate.dialect", HSQLDialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test") - .setProperty("hibernate.connection.username", "sa") - .setProperty("hibernate.connection.password", "") - .setProperty("hibernate.hbm2ddl.auto", "update"); + .setProperty("hibernate.dialect", HSQLDialect.class.getName()) + .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) + .setProperty("hibernate.connection.url", dbUrl) + .setProperty("hibernate.connection.username", "sa") + .setProperty("hibernate.connection.password", "") + .setProperty("hibernate.hbm2ddl.auto", "update"); + Connection connection = DriverManager.getConnection(dbUrl, "sa", ""); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) - .build(); - sessionFactory = configuration.buildSessionFactory(serviceRegistry); + .build(); + SessionFactory sf = configuration.buildSessionFactory(serviceRegistry); + try (InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("h2-trigger.sql")) { + assert h2InitStream != null; + try (InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) { + RunScript.execute(connection, h2InitReader); + } + } + return sf; + } + @BeforeClass + public static void beforeTests() throws Exception{ + sessionFactory1 = createSessionFactoryAndInitializeDBs("jdbc:hsqldb:mem:test"); + sessionFactory2 = createSessionFactoryAndInitializeDBs("jdbc:hsqldb:mem:test2"); + } @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); + public void setUp() throws Exception { + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); + doNotCommit = false; } @@ -61,16 +86,16 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.persist(person); + session1.persist(person); - session.getTransaction() - .commit(); - session.close(); + session1.getTransaction() + .commit(); + session1.close(); - session = sessionFactory.openSession(); - session.beginTransaction(); + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); - assertNotNull(session.get(Person.class, person.getId())); + assertNotNull(session1.get(Person.class, person.getId())); } @@ -80,10 +105,10 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.persist(person); + session1.persist(person); Long id1 = person.getId(); - session.persist(person); + session1.persist(person); Long id2 = person.getId(); assertEquals(id1, id2); @@ -93,13 +118,13 @@ public class SaveMethodsIntegrationTest { public void whenPersistDetached_thenThrowsException() { doNotCommit = true; - + Person person = new Person(); person.setName("John"); - session.persist(person); - session.evict(person); - - session.persist(person); + session1.persist(person); + session1.evict(person); + + session1.persist(person); } @Test @@ -107,12 +132,12 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.save(person); - session.flush(); - session.evict(person); + session1.save(person); + session1.flush(); + session1.evict(person); person.setName("Mary"); - Person mergedPerson = (Person) session.merge(person); + Person mergedPerson = (Person) session1.merge(person); assertNotSame(person, mergedPerson); assertEquals("Mary", mergedPerson.getName()); @@ -127,20 +152,20 @@ public class SaveMethodsIntegrationTest { assertNull(person.getId()); - Long id = (Long) session.save(person); + Long id = (Long) session1.save(person); assertNotNull(id); - session.getTransaction() - .commit(); - session.close(); + session1.getTransaction() + .commit(); + session1.close(); assertEquals(id, person.getId()); - session = sessionFactory.openSession(); - session.beginTransaction(); + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); - assertNotNull(session.get(Person.class, person.getId())); + assertNotNull(session1.get(Person.class, person.getId())); } @@ -149,8 +174,8 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - Long id1 = (Long) session.save(person); - Long id2 = (Long) session.save(person); + Long id1 = (Long) session1.save(person); + Long id2 = (Long) session1.save(person); assertEquals(id1, id2); } @@ -160,10 +185,10 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - Long id1 = (Long) session.save(person); - session.evict(person); + Long id1 = (Long) session1.save(person); + session1.evict(person); - Long id2 = (Long) session.save(person); + Long id2 = (Long) session1.save(person); assertNotEquals(id1, id2); } @@ -173,11 +198,11 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - Person mergedPerson = (Person) session.merge(person); + Person mergedPerson = (Person) session1.merge(person); - session.getTransaction() - .commit(); - session.beginTransaction(); + session1.getTransaction() + .commit(); + session1.beginTransaction(); assertNotNull(person.getId()); assertNotNull(mergedPerson.getId()); @@ -189,9 +214,9 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.save(person); + session1.save(person); - Person mergedPerson = (Person) session.merge(person); + Person mergedPerson = (Person) session1.merge(person); assertSame(person, mergedPerson); @@ -202,11 +227,11 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.save(person); - session.evict(person); + session1.save(person); + session1.evict(person); person.setName("Mary"); - session.update(person); + session1.update(person); assertEquals("Mary", person.getName()); } @@ -216,7 +241,7 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.update(person); + session1.update(person); } @@ -225,9 +250,9 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.save(person); + session1.save(person); - session.update(person); + session1.update(person); } @@ -236,11 +261,11 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.save(person); - session.evict(person); + session1.save(person); + session1.evict(person); person.setName("Mary"); - session.saveOrUpdate(person); + session1.saveOrUpdate(person); assertEquals("Mary", person.getName()); } @@ -250,16 +275,75 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.saveOrUpdate(person); + session1.saveOrUpdate(person); - session.getTransaction() - .commit(); - session.close(); + session1.getTransaction() + .commit(); + session1.close(); - session = sessionFactory.openSession(); - session.beginTransaction(); + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); - assertNotNull(session.get(Person.class, person.getId())); + assertNotNull(session1.get(Person.class, person.getId())); + + } + + @Test + public void whenSaveAndTriggerUpdatedAndRefresh_thenRefreshPersistentEntity() { + + Person person = new Person(); + person.setName("Zeeshan Arif"); + session1.persist(person); + session1.getTransaction() + .commit(); + session1.close(); + + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); + session1.refresh(person); + session1.getTransaction() + .commit(); + session1.close(); + + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); + assertEquals(person.getName(), "Neymar Santos"); + + } + + @Test + public void whenReplicate_thenRefreshPersistentEntity() { + + Person p = new Person(); + p.setName("Ronaldinho Gaucho"); + session1.persist(p); + session1.getTransaction() + .commit(); + session1.close(); + + Session session2 = sessionFactory2.openSession(); + session2.beginTransaction(); + session2.replicate(p, ReplicationMode.LATEST_VERSION); + session2.getTransaction() + .commit(); + session2.close(); + + session2 = sessionFactory2.openSession(); + session2.beginTransaction(); + Person actual = session2.get(Person.class, p.getId()); + session2.getTransaction().commit(); + session2.close(); + + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); + Person expected = session1.get(Person.class, p.getId()); + session1.getTransaction().commit(); + session1.close(); + + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); + assertEquals(expected.getId(), actual.getId()); + assertEquals(expected.getName(), actual.getName()); } @@ -268,24 +352,25 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.save(person); + session1.save(person); - session.saveOrUpdate(person); + session1.saveOrUpdate(person); } @After public void tearDown() { if (!doNotCommit) { - session.getTransaction() - .commit(); + session1.getTransaction() + .commit(); } - session.close(); + session1.close(); } @AfterClass public static void afterTests() { - sessionFactory.close(); + sessionFactory1.close(); + sessionFactory2.close(); } } diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/h2-trigger.sql b/persistence-modules/hibernate-enterprise/src/test/resources/h2-trigger.sql new file mode 100644 index 0000000000..a54b5c5003 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/test/resources/h2-trigger.sql @@ -0,0 +1,5 @@ +CREATE TRIGGER IF NOT EXISTS TGR_UpdatePersonName AFTER INSERT +ON Person FOR EACH ROW UPDATE PERSON SET NAME = 'Neymar Santos' where NAME = 'Zeeshan Arif' + + + diff --git a/persistence-modules/querydsl/pom.xml b/persistence-modules/querydsl/pom.xml index 72cdb3a48a..c40b97d1b9 100644 --- a/persistence-modules/querydsl/pom.xml +++ b/persistence-modules/querydsl/pom.xml @@ -15,6 +15,18 @@ + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-test + test + ${spring-boot.version} + com.querydsl @@ -36,6 +48,16 @@ ${hibernate-core.version} compile + + org.hibernate + hibernate-jpamodelgen + ${hibernate-core.version} + + + org.bsc.maven + maven-processor-plugin + 5.0 + commons-dbcp commons-dbcp @@ -103,24 +125,36 @@ ${maven-compiler-plugin.version} -proc:none + 17 + 17 - - com.mysema.maven - apt-maven-plugin - ${apt-maven-plugin.version} + org.bsc.maven + maven-processor-plugin + 5.0 + process process + generate-sources - target/generated-sources/java - com.querydsl.apt.jpa.JPAAnnotationProcessor + + org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor + com.querydsl.apt.jpa.JPAAnnotationProcessor + + + + org.hibernate + hibernate-jpamodelgen + ${hibernate-core.version} + + @@ -132,6 +166,7 @@ 1.4 1.1.3 6.4.2.Final + 3.2.3 \ No newline at end of file diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/GroupUser.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/GroupUser.java new file mode 100644 index 0000000000..32f35cbeb7 --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/GroupUser.java @@ -0,0 +1,59 @@ +package com.baeldung.querydslvsjpacriteria.entities; + +import java.util.HashSet; +import java.util.Set; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.OneToMany; + +@Entity +public class GroupUser { + + @Id + @GeneratedValue + private Long id; + + private String login; + + @ManyToMany(mappedBy = "groupUsers", cascade = CascadeType.PERSIST) + private Set userGroups = new HashSet<>(); + + @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "groupUser") + private Set tasks = new HashSet<>(0); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public Set getUserGroups() { + return userGroups; + } + + public void setUserGroups(Set userGroups) { + this.userGroups = userGroups; + } + + public Set getTasks() { + return tasks; + } + + public void setTasks(Set tasks) { + this.tasks = tasks; + } +} diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/Task.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/Task.java new file mode 100644 index 0000000000..ddb522711c --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/Task.java @@ -0,0 +1,43 @@ +package com.baeldung.querydslvsjpacriteria.entities; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; + +@Entity +public class Task { + + @Id + @GeneratedValue + private Long id; + + private String description; + + @ManyToOne + private GroupUser groupUser; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public GroupUser getUser() { + return groupUser; + } + + public void setUser(GroupUser groupUser) { + this.groupUser = groupUser; + } +} diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/UserGroup.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/UserGroup.java new file mode 100644 index 0000000000..f6a8b52983 --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/UserGroup.java @@ -0,0 +1,47 @@ +package com.baeldung.querydslvsjpacriteria.entities; + +import java.util.HashSet; +import java.util.Set; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; + +@Entity +public class UserGroup { + + @Id + @GeneratedValue + private Long id; + + private String name; + + @ManyToMany(cascade = CascadeType.PERSIST) + private Set groupUsers = new HashSet<>(); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Set getGroupUsers() { + return groupUsers; + } + + public void setGroupUsers(Set groupUsers) { + this.groupUsers = groupUsers; + } +} diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupJpaSpecificationRepository.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupJpaSpecificationRepository.java new file mode 100644 index 0000000000..72d14145af --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupJpaSpecificationRepository.java @@ -0,0 +1,25 @@ +package com.baeldung.querydslvsjpacriteria.repositories; + +import java.util.List; + +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +import com.baeldung.querydslvsjpacriteria.entities.UserGroup; +import com.baeldung.querydslvsjpacriteria.entities.UserGroup_; + +public interface UserGroupJpaSpecificationRepository extends JpaRepository, + JpaSpecificationExecutor { + + default List findAllWithNameInAnyList(List names1, List names2) { + return findAll(specNameInAnyList(names1, names2)); + } + + default Specification specNameInAnyList(List names1, List names2) { + return (root, q, cb) -> cb.or( + root.get(UserGroup_.name).in(names1), + root.get(UserGroup_.name).in(names2) + ); + } +} diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupQuerydslPredicateRepository.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupQuerydslPredicateRepository.java new file mode 100644 index 0000000000..22d36e9cc8 --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupQuerydslPredicateRepository.java @@ -0,0 +1,27 @@ +package com.baeldung.querydslvsjpacriteria.repositories; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; + +import com.baeldung.querydslvsjpacriteria.entities.QUserGroup; +import com.baeldung.querydslvsjpacriteria.entities.UserGroup; +import com.querydsl.core.BooleanBuilder; +import com.querydsl.core.types.Predicate; + +public interface UserGroupQuerydslPredicateRepository extends JpaRepository, QuerydslPredicateExecutor { + + default List findAllWithNameInAnyList(List names1, List names2) { + return StreamSupport + .stream(findAll(predicateInAnyList(names1, names2)).spliterator(), false) + .collect(Collectors.toList()); + } + + default Predicate predicateInAnyList(List names1, List names2) { + return new BooleanBuilder().and(QUserGroup.userGroup.name.in(names1)) + .or(QUserGroup.userGroup.name.in(names2)); + } +} diff --git a/persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/QuerydslVSJPACriteriaIntegrationTest.java b/persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/QuerydslVSJPACriteriaIntegrationTest.java new file mode 100644 index 0000000000..7827430211 --- /dev/null +++ b/persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/QuerydslVSJPACriteriaIntegrationTest.java @@ -0,0 +1,270 @@ +package com.baeldung.querydslvsjpacriteria; + +import static com.baeldung.querydslvsjpacriteria.entities.GroupUser_.tasks; +import static com.baeldung.querydslvsjpacriteria.entities.QGroupUser.groupUser; +import static com.baeldung.querydslvsjpacriteria.entities.QTask.task; +import static com.baeldung.querydslvsjpacriteria.entities.QUserGroup.userGroup; +import static com.baeldung.querydslvsjpacriteria.entities.UserGroup_.GROUP_USERS; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.querydslvsjpacriteria.entities.GroupUser; +import com.baeldung.querydslvsjpacriteria.entities.Task; +import com.baeldung.querydslvsjpacriteria.entities.UserGroup; +import com.baeldung.querydslvsjpacriteria.entities.UserGroup_; +import com.baeldung.querydslvsjpacriteria.repositories.UserGroupJpaSpecificationRepository; +import com.baeldung.querydslvsjpacriteria.repositories.UserGroupQuerydslPredicateRepository; +import com.querydsl.core.Tuple; +import com.querydsl.jpa.impl.JPAQueryFactory; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.CriteriaUpdate; +import jakarta.persistence.criteria.JoinType; +import jakarta.persistence.criteria.Root; + +@EnableJpaRepositories(basePackages = {"com.baeldung.querydslvsjpacriteria.repositories"}) +@ContextConfiguration("/test-context.xml") +@ExtendWith({SpringExtension.class, TimingExtension.class}) +class QuerydslVSJPACriteriaIntegrationTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(QuerydslVSJPACriteriaIntegrationTest.class); + + private static EntityManagerFactory emf; + + private EntityManager em; + + private JPAQueryFactory queryFactory; + + @Autowired + private UserGroupJpaSpecificationRepository userGroupJpaSpecificationRepository; + + @Autowired + private UserGroupQuerydslPredicateRepository userQuerydslPredicateRepository; + + @BeforeAll + static void populateDatabase() { + emf = Persistence.createEntityManagerFactory("com.baeldung.querydsl.intro"); + EntityManager em = emf.createEntityManager(); + em.getTransaction().begin(); + + Stream.of("Group 1", "Group 2", "Group 3") + .forEach(g -> { + UserGroup userGroup = new UserGroup(); + userGroup.setName(g); + em.persist(userGroup); + IntStream.range(0, 10) + .forEach(u -> { + GroupUser groupUser = new GroupUser(); + groupUser.setLogin("User" + u); + groupUser.getUserGroups().add(userGroup); + em.persist(groupUser); + userGroup.getGroupUsers().add(groupUser); + IntStream.range(0, 10000) + .forEach(t -> { + Task task = new Task(); + task.setDescription(groupUser.getLogin() + " task #" + t); + task.setUser(groupUser); + em.persist(task); + }); + }); + em.merge(userGroup); + }); + + em.getTransaction().commit(); + em.close(); + } + + @BeforeEach + void setUp() { + em = emf.createEntityManager(); + em.getTransaction().begin(); + queryFactory = new JPAQueryFactory(em); + + createUserGroup("Group 1"); + createUserGroup("Group 4"); + } + + @Test + void givenJpaCriteria_whenGetAllTheUserGroups_thenExpectedNumberOfItemsShouldBePresent() { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cr = cb.createQuery(UserGroup.class); + Root root = cr.from(UserGroup.class); + CriteriaQuery select = cr.select(root); + + TypedQuery query = em.createQuery(select); + List results = query.getResultList(); + assertEquals(3, results.size()); + } + + @Test + void givenQueryDSL_whenGetAllTheUserGroups_thenExpectedNumberOfItemsShouldBePresent() { + List results = queryFactory.selectFrom(userGroup).fetch(); + assertEquals(3, results.size()); + } + + @Test + void givenJpaCriteria_whenGetTheUserGroups_thenExpectedAggregatedDataShouldBePresent() { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cr = cb.createQuery(Object[].class); + Root root = cr.from(UserGroup.class); + + CriteriaQuery select = cr + .multiselect(root.get(UserGroup_.name), cb.countDistinct(root.get(UserGroup_.id))) + .where(cb.or( + root.get(UserGroup_.name).in("Group 1", "Group 2"), + root.get(UserGroup_.name).in("Group 4", "Group 5") + )) + .orderBy(cb.desc(root.get(UserGroup_.name))) + .groupBy(root.get(UserGroup_.name)); + + TypedQuery query = em.createQuery(select); + List results = query.getResultList(); + assertEquals(2, results.size()); + assertEquals("Group 2", results.get(0)[0]); + assertEquals(1L, results.get(0)[1]); + assertEquals("Group 1", results.get(1)[0]); + assertEquals(1L, results.get(1)[1]); + } + + @Test + void givenQueryDSL_whenGetTheUserGroups_thenExpectedAggregatedDataShouldBePresent() { + List results = queryFactory + .select(userGroup.name, userGroup.id.countDistinct()) + .from(userGroup) + .where(userGroup.name.in("Group 1", "Group 2") + .or(userGroup.name.in("Group 4", "Group 5"))) + .orderBy(userGroup.name.desc()) + .groupBy(userGroup.name) + .fetch(); + + assertEquals(2, results.size()); + assertEquals("Group 2", results.get(0).get(userGroup.name)); + assertEquals(1L, results.get(0).get(userGroup.id.countDistinct())); + assertEquals("Group 1", results.get(1).get(userGroup.name)); + assertEquals(1L, results.get(1).get(userGroup.id.countDistinct())); + } + + @Test + void givenJpaCriteria_whenGetTheUserGroupsWithJoins_thenExpectedDataShouldBePresent() { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(UserGroup.class); + + query.from(UserGroup.class) + .join(GROUP_USERS, JoinType.LEFT) + .join(tasks, JoinType.LEFT); + + List result = em.createQuery(query).getResultList(); + assertUserGroups(result); + } + + private void assertUserGroups(List userGroups) { + assertEquals(3, userGroups.size()); + for (UserGroup group : userGroups) { + assertEquals(10, group.getGroupUsers().size()); + for (GroupUser user : group.getGroupUsers()) { + assertEquals(10000, user.getTasks().size()); + } + } + } + + @Test + void givenQueryDSL_whenGetTheUserGroupsWithJoins_thenExpectedDataShouldBePresent() { + List result = queryFactory + .selectFrom(userGroup) + .leftJoin(userGroup.groupUsers, groupUser) + .leftJoin(groupUser.tasks, task) + .fetch(); + + assertUserGroups(result); + } + + @Test + void givenJpaCriteria_whenModifyTheUserGroup_thenNameShouldBeUpdated() { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaUpdate criteriaUpdate = cb.createCriteriaUpdate(UserGroup.class); + Root root = criteriaUpdate.from(UserGroup.class); + criteriaUpdate.set(UserGroup_.name, "Group 1 Updated using Jpa Criteria"); + criteriaUpdate.where(cb.equal(root.get(UserGroup_.name), "Group 1")); + + em.createQuery(criteriaUpdate).executeUpdate(); + UserGroup foundGroup = em.find(UserGroup.class, 1L); + assertEquals("Group 1 Updated using Jpa Criteria", foundGroup.getName()); + renameEntityBack(foundGroup, "Group 1"); + } + + private void renameEntityBack(UserGroup foundGroup, String name) { + foundGroup.setName(name); + em.merge(foundGroup); + } + + @Test + void givenQueryDSL_whenModifyTheUserGroup_thenNameShouldBeUpdated() { + queryFactory.update(userGroup) + .set(userGroup.name, "Group 1 Updated Using QueryDSL") + .where(userGroup.name.eq("Group 1")) + .execute(); + + UserGroup foundGroup = em.find(UserGroup.class, 1L); + assertEquals("Group 1 Updated Using QueryDSL", foundGroup.getName()); + renameEntityBack(foundGroup, "Group 1"); + } + + @Test + void givenJpaSpecificationRepository_whenGetTheUserGroups_thenExpectedDataShouldBePresent() { + List results = userGroupJpaSpecificationRepository.findAllWithNameInAnyList( + List.of("Group 1", "Group 2"), List.of("Group 4", "Group 5")); + + assertEquals(2, results.size()); + assertEquals("Group 1", results.get(0).getName()); + assertEquals("Group 4", results.get(1).getName()); + } + + @Test + void givenQuerydslPredicateRepository_whenGetTheUserGroups_thenExpectedDataShouldBePresent() { + List results = userQuerydslPredicateRepository.findAllWithNameInAnyList( + List.of("Group 1", "Group 2"), List.of("Group 4", "Group 5")); + + assertEquals(2, results.size()); + assertEquals("Group 1", results.get(0).getName()); + assertEquals("Group 4", results.get(1).getName()); + } + + private void createUserGroup(String name) { + UserGroup entity = new UserGroup(); + entity.setName(name); + userGroupJpaSpecificationRepository.save(entity); + } + + @AfterEach + void tearDown() { + em.getTransaction().commit(); + em.close(); + userGroupJpaSpecificationRepository.deleteAll(); + } + + @AfterAll + static void afterClass() { + emf.close(); + } +} diff --git a/persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/TimingExtension.java b/persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/TimingExtension.java new file mode 100644 index 0000000000..1847dfb5be --- /dev/null +++ b/persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/TimingExtension.java @@ -0,0 +1,34 @@ +package com.baeldung.querydslvsjpacriteria; + +import java.lang.reflect.Method; + +import org.junit.jupiter.api.extension.AfterTestExecutionCallback; +import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ExtensionContext.Namespace; +import org.junit.jupiter.api.extension.ExtensionContext.Store; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TimingExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback { + private static final Logger logger = LoggerFactory.getLogger(TimingExtension.class); + private static final String START_TIME = "start time"; + + @Override + public void beforeTestExecution(ExtensionContext context) { + getStore(context).put(START_TIME, System.currentTimeMillis()); + } + + @Override + public void afterTestExecution(ExtensionContext context) { + Method testMethod = context.getRequiredTestMethod(); + long startTime = getStore(context).remove(START_TIME, long.class); + long duration = System.currentTimeMillis() - startTime; + + logger.info(String.format("Method [%s] took %s ms.", testMethod.getName(), duration)); + } + + private Store getStore(ExtensionContext context) { + return context.getStore(Namespace.create(getClass(), context.getRequiredTestMethod())); + } +} diff --git a/spring-5/pom.xml b/spring-5/pom.xml index c41b8aa301..d66f0fa01f 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -42,17 +42,25 @@ spring-boot-starter-webflux - javax.json.bind - javax.json.bind-api + jakarta.json.bind + jakarta.json.bind-api org.apache.geronimo.specs geronimo-json_1.1_spec ${geronimo-json_1.1_spec.version} + + + jakarta.json + jakarta.json-api + ${jakarta.json-api.version} + + org.apache.johnzon johnzon-jsonb + ${johnzon-jsonb.version} @@ -151,9 +159,12 @@ 1.0 - 1.5.6 + 2.2.6 ${project.build.directory}/generated-snippets 5.1.0 + true + 2.0.1 + 2.0.0 \ No newline at end of file diff --git a/spring-5/src/main/java/com/baeldung/assertions/Car.java b/spring-5/src/main/java/com/baeldung/assertions/Car.java index abff27f0b0..d0153ce528 100644 --- a/spring-5/src/main/java/com/baeldung/assertions/Car.java +++ b/spring-5/src/main/java/com/baeldung/assertions/Car.java @@ -109,11 +109,11 @@ public class Car { car.startWithHasText("t"); car.startWithNotContain("132"); - List repairPartsCollection = new ArrayList(); + List repairPartsCollection = new ArrayList<>(); repairPartsCollection.add("part"); car.repair(repairPartsCollection); - Map repairPartsMap = new HashMap(); + Map repairPartsMap = new HashMap<>(); repairPartsMap.put("1", "part"); car.repair(repairPartsMap); diff --git a/spring-5/src/main/java/com/baeldung/jsonb/Person.java b/spring-5/src/main/java/com/baeldung/jsonb/Person.java index 7a54b37574..1c495f05bd 100644 --- a/spring-5/src/main/java/com/baeldung/jsonb/Person.java +++ b/spring-5/src/main/java/com/baeldung/jsonb/Person.java @@ -3,10 +3,10 @@ package com.baeldung.jsonb; import java.math.BigDecimal; import java.time.LocalDate; -import javax.json.bind.annotation.JsonbDateFormat; -import javax.json.bind.annotation.JsonbNumberFormat; -import javax.json.bind.annotation.JsonbProperty; -import javax.json.bind.annotation.JsonbTransient; +import jakarta.json.bind.annotation.JsonbDateFormat; +import jakarta.json.bind.annotation.JsonbNumberFormat; +import jakarta.json.bind.annotation.JsonbProperty; +import jakarta.json.bind.annotation.JsonbTransient; public class Person { diff --git a/spring-5/src/main/java/com/baeldung/jsonb/PersonController.java b/spring-5/src/main/java/com/baeldung/jsonb/PersonController.java index e216a282eb..f69fcf4795 100644 --- a/spring-5/src/main/java/com/baeldung/jsonb/PersonController.java +++ b/spring-5/src/main/java/com/baeldung/jsonb/PersonController.java @@ -6,7 +6,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java b/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java index b10cfd5f55..b92e23f757 100644 --- a/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java @@ -5,7 +5,7 @@ import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import java.util.ArrayList; import java.util.List; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -53,7 +53,7 @@ public class CRUDController { @PatchMapping("/{id}") public List patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) { - List returnList = new ArrayList(); + List returnList = new ArrayList<>(); crudInput.setId(id); returnList.add(crudInput); return returnList; diff --git a/spring-5/src/main/java/com/baeldung/restdocs/CrudInput.java b/spring-5/src/main/java/com/baeldung/restdocs/CrudInput.java index 29046d7725..4e783150d5 100644 --- a/spring-5/src/main/java/com/baeldung/restdocs/CrudInput.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/CrudInput.java @@ -4,8 +4,8 @@ import java.net.URI; import java.util.Collections; import java.util.List; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/spring-5/src/main/java/com/baeldung/web/Foo.java b/spring-5/src/main/java/com/baeldung/web/Foo.java index c4868a9958..ca058652a5 100644 --- a/spring-5/src/main/java/com/baeldung/web/Foo.java +++ b/spring-5/src/main/java/com/baeldung/web/Foo.java @@ -1,9 +1,9 @@ package com.baeldung.web; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Foo { diff --git a/spring-5/src/main/java/com/baeldung/web/FooController.java b/spring-5/src/main/java/com/baeldung/web/FooController.java index a09e628421..23c258c3c7 100644 --- a/spring-5/src/main/java/com/baeldung/web/FooController.java +++ b/spring-5/src/main/java/com/baeldung/web/FooController.java @@ -7,9 +7,9 @@ import org.springframework.http.HttpStatus; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; -import javax.annotation.PostConstruct; -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; +import jakarta.annotation.PostConstruct; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; import java.util.List; @RestController("/foos") diff --git a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java index 9c462e0412..2e5a1d6d04 100644 --- a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java @@ -20,21 +20,21 @@ public class BeanRegistrationIntegrationTest { @Test public void whenRegisterBean_thenOk() { - context.registerBean(MyService.class, () -> new MyService()); + context.registerBean(MyService.class, MyService::new); MyService myService = (MyService) context.getBean("com.baeldung.functional.MyService"); assertTrue(myService.getRandomNumber() < 10); } @Test public void whenRegisterBeanWithName_thenOk() { - context.registerBean("mySecondService", MyService.class, () -> new MyService()); + context.registerBean("mySecondService", MyService.class, MyService::new); MyService mySecondService = (MyService) context.getBean("mySecondService"); assertTrue(mySecondService.getRandomNumber() < 10); } @Test public void whenRegisterBeanWithCallback_thenOk() { - context.registerBean("myCallbackService", MyService.class, () -> new MyService(), bd -> bd.setAutowireCandidate(false)); + context.registerBean("myCallbackService", MyService.class, MyService::new, bd -> bd.setAutowireCandidate(false)); MyService myCallbackService = (MyService) context.getBean("myCallbackService"); assertTrue(myCallbackService.getRandomNumber() < 10); } diff --git a/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java index f4749c0d33..14870460e4 100644 --- a/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java @@ -9,7 +9,6 @@ import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; diff --git a/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerMvcIntegrationTest.java b/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerMvcIntegrationTest.java index ab96364e6a..3172a06ca1 100644 --- a/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerMvcIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerMvcIntegrationTest.java @@ -7,7 +7,7 @@ import static org.springframework.restdocs.operation.preprocess.Preprocessors.pr import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; +import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; @@ -50,6 +50,6 @@ class BookControllerMvcIntegrationTest { mockMvc.perform(get("/books?page=2")) .andExpect(status().isOk()) .andDo(document("books", - requestParameters(parameterWithName("page").description("The page to retrieve")))); + queryParameters(parameterWithName("page").description("The page to retrieve")))); } } \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerReactiveIntegrationTest.java b/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerReactiveIntegrationTest.java index b2a6991f27..fdbad44480 100644 --- a/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerReactiveIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerReactiveIntegrationTest.java @@ -2,7 +2,7 @@ package com.baeldung.queryparamdoc; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; +import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; @@ -46,7 +46,7 @@ class BookControllerReactiveIntegrationTest { webTestClient.get().uri("/books?page=2") .exchange().expectStatus().isOk().expectBody() .consumeWith(document("books", - requestParameters(parameterWithName("page").description("The page to retrieve")))); + queryParameters(parameterWithName("page").description("The page to retrieve")))); } @TestConfiguration diff --git a/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerRestAssuredIntegrationTest.java b/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerRestAssuredIntegrationTest.java index 44c6b27285..e24a626114 100644 --- a/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerRestAssuredIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerRestAssuredIntegrationTest.java @@ -3,9 +3,7 @@ package com.baeldung.queryparamdoc; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.core.Is.is; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; import io.restassured.RestAssured; import io.restassured.builder.RequestSpecBuilder; @@ -19,6 +17,7 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.restdocs.RestDocumentationContextProvider; import org.springframework.restdocs.RestDocumentationExtension; +import org.springframework.restdocs.restassured.RestAssuredRestDocumentation; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -31,7 +30,7 @@ class BookControllerRestAssuredIntegrationTest { @BeforeEach void setUp(RestDocumentationContextProvider restDocumentation, @LocalServerPort int port) { - this.spec = new RequestSpecBuilder().addFilter(documentationConfiguration(restDocumentation)) + this.spec = new RequestSpecBuilder().addFilter(RestAssuredRestDocumentation.documentationConfiguration(restDocumentation)) .setPort(port) .build(); } @@ -44,7 +43,7 @@ class BookControllerRestAssuredIntegrationTest { @Test @WithMockUser void givenEndpoint_whenSendGetRequest_thenSuccessfulResponse() { - RestAssured.given(this.spec).filter(document("users", requestParameters( + RestAssured.given(this.spec).filter(RestAssuredRestDocumentation.document("users", queryParameters( parameterWithName("page").description("The page to retrieve")))) .when().get("/books?page=2") .then().assertThat().statusCode(is(200)); diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 8087c2cd6b..e09ba5d7d6 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -20,7 +20,7 @@ spring-boot-admin spring-boot-angular spring-boot-annotations - + spring-boot-annotations-2 spring-boot-artifacts spring-boot-artifacts-2 spring-boot-autoconfiguration @@ -35,7 +35,7 @@ spring-boot-disable-logging spring-boot-ci-cd - + spring-boot-custom-starter spring-boot-crud spring-boot-data spring-boot-environment @@ -66,13 +66,13 @@ spring-boot-performance spring-boot-property-exp spring-boot-request-params - - + spring-boot-runtime + spring-boot-runtime-2 spring-boot-security spring-boot-security-2 spring-boot-ssl-bundles spring-boot-telegram - + spring-boot-springdoc spring-boot-swagger-jwt diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientLiveTest.java similarity index 99% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientLiveTest.java index 5650d2dd22..0284d780a9 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientLiveTest.java @@ -23,7 +23,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestPropertySource(locations="classpath:connectiondetails/application-r2dbc.properties") -public class RestClientIntegrationTest { +public class RestClientLiveTest { @LocalServerPort private int port; diff --git a/spring-boot-modules/spring-boot-annotations-2/pom.xml b/spring-boot-modules/spring-boot-annotations-2/pom.xml index 71fc7ff388..b7522772aa 100644 --- a/spring-boot-modules/spring-boot-annotations-2/pom.xml +++ b/spring-boot-modules/spring-boot-annotations-2/pom.xml @@ -26,6 +26,7 @@ org.mockito mockito-inline + ${mockito-inline.version} test @@ -33,6 +34,15 @@ spring-boot-starter-test test + + org.apache.commons + commons-lang3 + + + 5.2.0 + com.baeldung.springbootconfiguration.Application + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/ConditionalUtils.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/ConditionalUtils.java index 7294d843d1..facafb13c2 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/ConditionalUtils.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/ConditionalUtils.java @@ -9,12 +9,12 @@ public class ConditionalUtils { return SystemUtils.IS_OS_WINDOWS; } - public static boolean isJava8() { - return JavaVersion.getJavaVersion().equals(JavaVersion.EIGHT); + public static boolean isJava17() { + return JavaVersion.getJavaVersion().equals(JavaVersion.SEVENTEEN); } - public static boolean isJava9() { - return JavaVersion.getJavaVersion().equals(JavaVersion.NINE); + public static boolean isJava21() { + return JavaVersion.getJavaVersion().equals(JavaVersion.TWENTY_ONE); } } diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java9Condition.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17Condition.java similarity index 77% rename from spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java9Condition.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17Condition.java index 2afa8b25a7..cdf6cfde58 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java9Condition.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17Condition.java @@ -4,10 +4,10 @@ import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class Java9Condition implements Condition { +public class Java17Condition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - return ConditionalUtils.isJava9(); + return ConditionalUtils.isJava17(); } } diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8DependedService.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17DependedService.java similarity index 69% rename from spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8DependedService.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17DependedService.java index ab76dcd930..2cf3dea8ec 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8DependedService.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17DependedService.java @@ -4,6 +4,6 @@ import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Service; @Service -@Conditional(Java8Condition.class) -public class Java8DependedService { +@Conditional(Java17Condition.class) +public class Java17DependedService { } diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8OrJava9.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17OrJava21.java similarity index 52% rename from spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8OrJava9.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17OrJava21.java index 77c501ed08..fdc5f866bc 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8OrJava9.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17OrJava21.java @@ -3,14 +3,14 @@ package com.baeldung.annotations.conditional; import org.springframework.boot.autoconfigure.condition.AnyNestedCondition; import org.springframework.context.annotation.Conditional; -public class Java8OrJava9 extends AnyNestedCondition { - Java8OrJava9() { +public class Java17OrJava21 extends AnyNestedCondition { + Java17OrJava21() { super(ConfigurationPhase.REGISTER_BEAN); } - @Conditional(Java8Condition.class) - static class Java8 { } + @Conditional(Java17Condition.class) + static class Java17 { } - @Conditional(Java9Condition.class) - static class Java9 { } + @Conditional(Java21Condition.class) + static class Java21 { } } diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8Condition.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java21Condition.java similarity index 77% rename from spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8Condition.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java21Condition.java index c5f5e16d52..ec0f3a499e 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8Condition.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java21Condition.java @@ -4,10 +4,10 @@ import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class Java8Condition implements Condition { +public class Java21Condition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - return ConditionalUtils.isJava8(); + return ConditionalUtils.isJava21(); } } diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/LoggingService.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/LoggingService.java index e104ec86e1..fa619acdb7 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/LoggingService.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/LoggingService.java @@ -8,12 +8,12 @@ import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Service; @Service -@Conditional({IsDevEnvCondition.class, IsWindowsCondition.class, Java8Condition.class}) +@Conditional({IsDevEnvCondition.class, IsWindowsCondition.class, Java17Condition.class}) @ConditionalOnProperty( value = "logging.enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnExpression("${logging.enabled:true} and '${logging.level}'.equals('DEBUG')") -@ConditionalOnJava(JavaVersion.EIGHT) +@ConditionalOnJava(JavaVersion.SEVENTEEN) public class LoggingService { } diff --git a/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java9ConditionUnitTest.java b/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java17ConditionUnitTest.java similarity index 71% rename from spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java9ConditionUnitTest.java rename to spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java17ConditionUnitTest.java index ce277e81fe..560cd5537d 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java9ConditionUnitTest.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java17ConditionUnitTest.java @@ -7,15 +7,15 @@ import org.mockito.Mockito; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class Java9ConditionUnitTest { +public class Java17ConditionUnitTest { @Test - public void whenOnJava9_thenJava9ConditionShouldPass() { + public void whenOnJava17_thenJava7ConditionShouldPass() { try (MockedStatic theMock = Mockito.mockStatic(ConditionalUtils.class)) { - theMock.when(ConditionalUtils::isJava9) + theMock.when(ConditionalUtils::isJava17) .thenReturn(true); Assertions.assertTrue( - new Java9Condition().matches( + new Java17Condition().matches( Mockito.mock(ConditionContext.class), Mockito.mock(AnnotatedTypeMetadata.class) ) ); @@ -24,12 +24,12 @@ public class Java9ConditionUnitTest { } @Test - public void whenNotOnJava9_thenJava9ConditionShouldNotPass() { + public void whenNotOnJava17_thenJava17ConditionShouldNotPass() { try (MockedStatic theMock = Mockito.mockStatic(ConditionalUtils.class)) { - theMock.when(ConditionalUtils::isJava9) + theMock.when(ConditionalUtils::isJava17) .thenReturn(false); Assertions.assertFalse( - new Java9Condition().matches( + new Java17Condition().matches( Mockito.mock(ConditionContext.class), Mockito.mock(AnnotatedTypeMetadata.class) ) ); diff --git a/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java8ConditionUnitTest.java b/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java21ConditionUnitTest.java similarity index 72% rename from spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java8ConditionUnitTest.java rename to spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java21ConditionUnitTest.java index 0d1b1eded6..397f95c16c 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java8ConditionUnitTest.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java21ConditionUnitTest.java @@ -7,15 +7,15 @@ import org.mockito.Mockito; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class Java8ConditionUnitTest { +public class Java21ConditionUnitTest { @Test - public void whenOnJava8_thenJava8ConditionShouldPass() { + public void whenOnJava21_thenJava21ConditionShouldPass() { try (MockedStatic theMock = Mockito.mockStatic(ConditionalUtils.class)) { - theMock.when(ConditionalUtils::isJava8) + theMock.when(ConditionalUtils::isJava21) .thenReturn(true); Assertions.assertTrue( - new Java8Condition().matches( + new Java21Condition().matches( Mockito.mock(ConditionContext.class), Mockito.mock(AnnotatedTypeMetadata.class) ) ); @@ -24,12 +24,12 @@ public class Java8ConditionUnitTest { } @Test - public void whenNotOnJava8_thenJava8ConditionShouldNotPass() { + public void whenNotOnJava21_thenJava21ConditionShouldNotPass() { try (MockedStatic theMock = Mockito.mockStatic(ConditionalUtils.class)) { - theMock.when(ConditionalUtils::isJava8) + theMock.when(ConditionalUtils::isJava21) .thenReturn(false); Assertions.assertFalse( - new Java8Condition().matches( + new Java21Condition().matches( Mockito.mock(ConditionContext.class), Mockito.mock(AnnotatedTypeMetadata.class) ) ); diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/GreeterSampleApplication.java similarity index 94% rename from spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/GreeterSampleApplication.java index 5aa3ac7015..f573179c29 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/GreeterSampleApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.greeter.sample; +package com.baeldung.greeter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; @@ -6,7 +6,6 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.greeter.library.Greeter; - @SpringBootApplication public class GreeterSampleApplication implements CommandLineRunner { diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java index 7103da97f3..e446dddc69 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java @@ -5,7 +5,7 @@ import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.greeter.sample.GreeterSampleApplication; +import com.baeldung.greeter.GreeterSampleApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = GreeterSampleApplication.class) diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/GreeterSampleApplicationIntegrationTest.java similarity index 97% rename from spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/GreeterSampleApplicationIntegrationTest.java index 50193ccd60..e53be5fafd 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/GreeterSampleApplicationIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.greeter.sample; +package com.baeldung.greeter; import static org.junit.Assert.assertEquals; diff --git a/spring-boot-modules/spring-boot-custom-starter/pom.xml b/spring-boot-modules/spring-boot-custom-starter/pom.xml index aee98b125e..d18aabac19 100644 --- a/spring-boot-modules/spring-boot-custom-starter/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/pom.xml @@ -23,4 +23,9 @@ parent-multi-module + + true + 3.2.2 + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime-2/pom.xml b/spring-boot-modules/spring-boot-runtime-2/pom.xml index 356880975a..c925735817 100644 --- a/spring-boot-modules/spring-boot-runtime-2/pom.xml +++ b/spring-boot-modules/spring-boot-runtime-2/pom.xml @@ -75,5 +75,6 @@ 3.1.3 + com.baeldung.heap.HeapSizeDemoApplication \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime/pom.xml b/spring-boot-modules/spring-boot-runtime/pom.xml index 4cffc9a311..e43d6b0eb0 100644 --- a/spring-boot-modules/spring-boot-runtime/pom.xml +++ b/spring-boot-modules/spring-boot-runtime/pom.xml @@ -69,8 +69,8 @@ runtime - javax.persistence - javax.persistence-api + jakarta.persistence + jakarta.persistence-api org.subethamail @@ -79,14 +79,16 @@ test - org.apache.httpcomponents - httpclient + org.apache.httpcomponents.client5 + httpclient5 + 5.3.1 3.1.7 3.1.3 + com.baeldung.shutdown.Application \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java index 11ea5b70c9..9539b17c88 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java @@ -4,7 +4,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java index 321f3be3ef..0f596f5816 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java @@ -1,6 +1,6 @@ package com.baeldung.sampleapp.web.controller.redirect; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/TerminateBean.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/TerminateBean.java index 4f3b81b920..1a0288b3dc 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/TerminateBean.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/TerminateBean.java @@ -1,6 +1,6 @@ package com.baeldung.shutdown; -import javax.annotation.PreDestroy; +import jakarta.annotation.PreDestroy; public class TerminateBean { diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java index 6870f4e6bb..03f4959fbc 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java @@ -9,8 +9,8 @@ import org.springframework.security.web.SecurityFilterChain; public class SecurityConfig { @Bean public SecurityFilterChain securityFilter(HttpSecurity http) throws Exception { - return http.csrf() - .ignoringAntMatchers("/actuator/**").and() + return http + .csrf(csrf -> csrf.ignoringRequestMatchers("/actuator/**") ) .build(); } } diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/CustomTraceRepository.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/CustomTraceRepository.java index d85c043dc0..6dd2ab446b 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/CustomTraceRepository.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/CustomTraceRepository.java @@ -4,22 +4,23 @@ import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicReference; -import org.springframework.boot.actuate.trace.http.HttpTrace; -import org.springframework.boot.actuate.trace.http.HttpTraceRepository; +import org.apache.hc.client5.http.classic.methods.HttpTrace; +import org.springframework.boot.actuate.web.exchanges.HttpExchange; +import org.springframework.boot.actuate.web.exchanges.HttpExchangeRepository; import org.springframework.stereotype.Repository; @Repository -public class CustomTraceRepository implements HttpTraceRepository { +public class CustomTraceRepository implements HttpExchangeRepository { - AtomicReference lastTrace = new AtomicReference<>(); + AtomicReference lastTrace = new AtomicReference<>(); @Override - public List findAll() { + public List findAll() { return Collections.singletonList(lastTrace.get()); } @Override - public void add(HttpTrace trace) { + public void add(HttpExchange trace) { if ("GET".equals(trace.getRequest() .getMethod())) { lastTrace.set(trace); diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/TraceRequestFilter.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/TraceRequestFilter.java index fd6312df47..285c538580 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/TraceRequestFilter.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/TraceRequestFilter.java @@ -1,23 +1,22 @@ package com.baeldung.spring.boot.management.trace; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; -import org.springframework.boot.actuate.trace.http.HttpExchangeTracer; -import org.springframework.boot.actuate.trace.http.HttpTraceRepository; -import org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter; +import org.springframework.boot.actuate.web.exchanges.HttpExchangeRepository; +import org.springframework.boot.actuate.web.exchanges.Include; +import org.springframework.boot.actuate.web.exchanges.servlet.HttpExchangesFilter; import org.springframework.stereotype.Component; @Component -public class TraceRequestFilter extends HttpTraceFilter { +public class TraceRequestFilter extends HttpExchangesFilter { /** - * Create a new {@link HttpTraceFilter} instance. + * Create a new {@link HttpExchangesFilter} instance. * * @param repository the trace repository - * @param tracer used to trace exchanges */ - public TraceRequestFilter(HttpTraceRepository repository, HttpExchangeTracer tracer) { - super(repository, tracer); + public TraceRequestFilter(HttpExchangeRepository repository) { + super(repository, Include.defaultIncludes()); } @Override diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedHttpServletRequest.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedHttpServletRequest.java index 51bbd51ea8..cc2257701a 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedHttpServletRequest.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedHttpServletRequest.java @@ -2,9 +2,9 @@ package com.baeldung.web.log.app; import org.springframework.util.StreamUtils; -import javax.servlet.ServletInputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; import java.io.*; public class CachedHttpServletRequest extends HttpServletRequestWrapper { diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedServletInputStream.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedServletInputStream.java index 673d04876b..fcea7b96cf 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedServletInputStream.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedServletInputStream.java @@ -3,8 +3,8 @@ package com.baeldung.web.log.app; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.ReadListener; -import javax.servlet.ServletInputStream; +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/RequestCachingFilter.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/RequestCachingFilter.java index e0928550fc..607404831a 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/RequestCachingFilter.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/RequestCachingFilter.java @@ -8,11 +8,11 @@ import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebFilter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebFilter; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.StandardCharsets; diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java index b1ddf16dfe..9c5cc731e2 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java @@ -1,6 +1,6 @@ package com.baeldung.web.log.controller; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-boot-modules/spring-boot-springdoc/pom.xml b/spring-boot-modules/spring-boot-springdoc/pom.xml index 8ed9b7c22b..567ff5a606 100644 --- a/spring-boot-modules/spring-boot-springdoc/pom.xml +++ b/spring-boot-modules/spring-boot-springdoc/pom.xml @@ -119,10 +119,11 @@ - 1.7.0 - 1.5.6 + 1.8.0 + 2.2.6 ${project.build.directory}/generated-snippets 1.4 + true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/DefaultGlobalSecuritySchemeApplication.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/DefaultGlobalSecuritySchemeApplication.java index 1ce81a1e83..fda191f785 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/DefaultGlobalSecuritySchemeApplication.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/DefaultGlobalSecuritySchemeApplication.java @@ -19,7 +19,7 @@ import io.swagger.v3.oas.annotations.security.SecurityScheme; public class DefaultGlobalSecuritySchemeApplication { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - return http.authorizeHttpRequests(authorizeRequests -> authorizeRequests.antMatchers("/api/auth/**", "/swagger-ui-custom.html", "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**", "/swagger-ui/index.html", "/api-docs/**") + return http.authorizeHttpRequests(authorizeRequests -> authorizeRequests.requestMatchers("/api/auth/**", "/swagger-ui-custom.html", "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**", "/swagger-ui/index.html", "/api-docs/**") .permitAll() .anyRequest() .authenticated()) diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/controller/DefaultGlobalSecuritySchemeOpenApiController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/controller/DefaultGlobalSecuritySchemeOpenApiController.java index 4ad7a2a2c3..9b3d6ef545 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/controller/DefaultGlobalSecuritySchemeOpenApiController.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/controller/DefaultGlobalSecuritySchemeOpenApiController.java @@ -3,7 +3,7 @@ package com.baeldung.defaultglobalsecurityscheme.controller; import java.time.OffsetDateTime; import java.time.ZoneOffset; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/LoginDto.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/LoginDto.java index cf88cc4d98..c7c71a67a3 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/LoginDto.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/LoginDto.java @@ -1,5 +1,6 @@ package com.baeldung.defaultglobalsecurityscheme.dto; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; @@ -30,7 +31,7 @@ public class LoginDto { * @return user */ - @Schema(name = "user", required = true) + @Schema(name = "user", requiredMode = RequiredMode.REQUIRED) public String getUser() { return user; } diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/PingResponseDto.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/PingResponseDto.java index 0d367785d8..0944dce438 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/PingResponseDto.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/PingResponseDto.java @@ -1,9 +1,10 @@ package com.baeldung.defaultglobalsecurityscheme.dto; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; import java.time.OffsetDateTime; import java.util.Objects; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.format.annotation.DateTimeFormat; @@ -33,7 +34,7 @@ public class PingResponseDto { * @return pong */ @Valid - @Schema(name = "pong", required = false) + @Schema(name = "pong", requiredMode = RequiredMode.REQUIRED) public OffsetDateTime getPong() { return pong; } diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/jwt/SecurityConfiguration.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/jwt/SecurityConfiguration.java index 8cb1ca1f60..e6c849ac45 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/jwt/SecurityConfiguration.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/jwt/SecurityConfiguration.java @@ -9,6 +9,7 @@ import org.springframework.context.annotation.Bean; 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.configurers.AbstractHttpConfigurer; import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; @@ -53,15 +54,15 @@ public class SecurityConfiguration { return http .authorizeHttpRequests(authorizeRequests -> authorizeRequests - .antMatchers("/api/auth/**", "/swagger-ui-custom.html" ,"/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**", + .requestMatchers("/api/auth/**", "/swagger-ui-custom.html" ,"/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**", "/swagger-ui/index.html","/api-docs/**") .permitAll() .anyRequest() .authenticated()) - .cors().disable() - .csrf().disable() - .formLogin().disable() - .httpBasic().disable() + .cors(AbstractHttpConfigurer::disable) + .csrf(AbstractHttpConfigurer::disable) + .formLogin(AbstractHttpConfigurer::disable) + .httpBasic(AbstractHttpConfigurer::disable) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt) diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java index 99d63581be..cd58c4644c 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java @@ -1,10 +1,10 @@ package com.baeldung.restdocopenapi; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Foo { diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java index 892eb05f8d..c6bfd42b73 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java @@ -5,7 +5,7 @@ import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import java.util.List; import java.util.Optional; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java index 105b57b2ef..d4691c1f51 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java @@ -1,9 +1,10 @@ package com.baeldung.restdocopenapi; +import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; @Repository -public interface FooRepository extends PagingAndSortingRepository{ +public interface FooRepository extends JpaRepository { } diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java index 8af414c8fd..8e8e9f4a9e 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java @@ -5,7 +5,7 @@ import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import java.util.List; import java.util.Optional; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java index f2355a2ec3..d9e4fb1c7d 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java @@ -2,8 +2,8 @@ package com.baeldung.springdoc.controller; import java.util.Collection; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; import com.baeldung.springdoc.exception.BookNotFoundException; import com.baeldung.springdoc.model.Book; diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/Foo.kt b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/Foo.kt index 3bc3c8fe61..e40bcfde97 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/Foo.kt +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/Foo.kt @@ -1,10 +1,9 @@ package com.baeldung.springdoc.kotlin -import javax.persistence.Entity -import javax.persistence.GeneratedValue -import javax.persistence.Id -import javax.validation.constraints.NotBlank -import javax.validation.constraints.Size +import jakarta.persistence.Entity +import jakarta.persistence.Id +import jakarta.validation.constraints.NotBlank +import jakarta.validation.constraints.Size @Entity data class Foo( diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/FooController.kt b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/FooController.kt index d3ecd6a6ba..e253e92a6d 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/FooController.kt +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/FooController.kt @@ -6,6 +6,7 @@ import io.swagger.v3.oas.annotations.media.Content import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.responses.ApiResponses +import org.hibernate.internal.util.collections.CollectionHelper import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @@ -13,7 +14,7 @@ import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/") class FooController() { - val fooList: List = listOf(Foo(1, "one"), Foo(2, "two")) + val fooList: List = CollectionHelper.listOf(Foo(1, "one"), Foo(2, "two")) @Operation(summary = "Get all foos") @ApiResponses(value = [ diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java index 8f678a7ec2..e2c473058a 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java @@ -1,7 +1,7 @@ package com.baeldung.springdoc.model; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; public class Book { diff --git a/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/jwt/OpenApiJwtIntegrationTest.java b/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/jwt/OpenApiJwtIntegrationTest.java index a4920914fd..85ddefcc4c 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/jwt/OpenApiJwtIntegrationTest.java +++ b/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/jwt/OpenApiJwtIntegrationTest.java @@ -1,11 +1,13 @@ package com.baeldung.jwt; +import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; 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 org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -15,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @DisplayName("OpenAPI JWT Live Tests") +@Disabled class OpenApiJwtIntegrationTest { @LocalServerPort diff --git a/spring-boot-modules/spring-caching-2/pom.xml b/spring-boot-modules/spring-caching-2/pom.xml index ec9215aa32..95fae4a0ef 100644 --- a/spring-boot-modules/spring-caching-2/pom.xml +++ b/spring-boot-modules/spring-caching-2/pom.xml @@ -51,7 +51,7 @@ ${caffeine.version} - it.ozimov + com.github.codemonstur embedded-redis ${embedded.redis.version} @@ -65,7 +65,7 @@ - 0.7.3 + 1.4.0 3.1.8 com.baeldung.caching.ttl.CachingTTLApplication diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java new file mode 100644 index 0000000000..576bcd97ab --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java @@ -0,0 +1,71 @@ +package com.baeldung.caching.twolevelcache; + +import com.github.benmanes.caffeine.cache.Caffeine; + +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.AnnotationCacheOperationSource; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.caffeine.CaffeineCache; +import org.springframework.cache.interceptor.CacheInterceptor; +import org.springframework.cache.interceptor.CacheOperationSource; +import org.springframework.cache.support.SimpleCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; + +import java.time.Duration; +import java.util.Arrays; + +@Configuration +@EnableCaching +public class CacheConfig { + + @Bean + @Primary + public CacheManager caffeineCacheManager(CaffeineCache caffeineCache) { + SimpleCacheManager manager = new SimpleCacheManager(); + manager.setCaches(Arrays.asList(caffeineCache)); + return manager; + } + + @Bean + public CaffeineCache caffeineCacheConfig() { + return new CaffeineCache("customerCache", Caffeine.newBuilder() + .expireAfterWrite(Duration.ofSeconds(3)) + .initialCapacity(1) + .maximumSize(2000) + .build()); + } + + @Bean + public CacheManager redisCacheManager(RedisConnectionFactory connectionFactory, RedisCacheConfiguration redisCacheConfiguration) { + return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory) + .withCacheConfiguration("customerCache", redisCacheConfiguration) + .build(); + } + + @Bean + public RedisCacheConfiguration cacheConfiguration() { + return RedisCacheConfiguration.defaultCacheConfig() + .entryTtl(Duration.ofMinutes(5)) + .disableCachingNullValues() + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); + } + + @Bean + public CacheInterceptor cacheInterceptor(CacheManager caffeineCacheManager, CacheOperationSource cacheOperationSource) { + CacheInterceptor interceptor = new CustomerCacheInterceptor(caffeineCacheManager); + interceptor.setCacheOperationSources(cacheOperationSource); + return interceptor; + } + + @Bean + public CacheOperationSource cacheOperationSource() { + return new AnnotationCacheOperationSource(); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java new file mode 100644 index 0000000000..0b985d35f3 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java @@ -0,0 +1,25 @@ +package com.baeldung.caching.twolevelcache; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.io.Serializable; + +@Data +@Entity +@AllArgsConstructor +@NoArgsConstructor +@Setter +public class Customer implements Serializable { + + @Id + private String id; + + private String name; + + private String email; +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerCacheInterceptor.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerCacheInterceptor.java new file mode 100644 index 0000000000..f1a8dca0db --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerCacheInterceptor.java @@ -0,0 +1,29 @@ +package com.baeldung.caching.twolevelcache; + +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.interceptor.CacheInterceptor; +import org.springframework.data.redis.cache.RedisCache; + +public class CustomerCacheInterceptor extends CacheInterceptor { + + private final CacheManager caffeineCacheManager; + + public CustomerCacheInterceptor(CacheManager caffeineCacheManager) { + this.caffeineCacheManager = caffeineCacheManager; + } + + @Override + protected Cache.ValueWrapper doGet(Cache cache, Object key) { + Cache.ValueWrapper existingCacheValue = super.doGet(cache, key); + + if (existingCacheValue != null && cache.getClass() == RedisCache.class) { + Cache caffeineCache = caffeineCacheManager.getCache(cache.getName()); + if (caffeineCache != null) { + caffeineCache.putIfAbsent(key, existingCacheValue.get()); + } + } + + return existingCacheValue; + } +} diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerRepository.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerRepository.java new file mode 100644 index 0000000000..098112f152 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerRepository.java @@ -0,0 +1,6 @@ +package com.baeldung.caching.twolevelcache; + +import org.springframework.data.repository.CrudRepository; + +public interface CustomerRepository extends CrudRepository { +} diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java new file mode 100644 index 0000000000..088b66919c --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java @@ -0,0 +1,26 @@ +package com.baeldung.caching.twolevelcache; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.cache.annotation.Caching; +import org.springframework.stereotype.Service; + +@Service +public class CustomerService { + + private final CustomerRepository customerRepository; + + @Autowired + public CustomerService(CustomerRepository customerRepository) { + this.customerRepository = customerRepository; + } + + @Caching(cacheable = { + @Cacheable(cacheNames = "customerCache", cacheManager = "caffeineCacheManager"), + @Cacheable(cacheNames = "customerCache", cacheManager = "redisCacheManager") + }) + public Customer getCustomer(String id) { + return customerRepository.findById(id) + .orElseThrow(RuntimeException::new); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/TwoLevelCacheApplication.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/TwoLevelCacheApplication.java new file mode 100644 index 0000000000..9bc2c65e6e --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/TwoLevelCacheApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.caching.twolevelcache; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class TwoLevelCacheApplication { + + public static void main(String[] args) { + SpringApplication.run(TwoLevelCacheApplication.class, args); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/resources/application.properties b/spring-boot-modules/spring-caching-2/src/main/resources/application.properties index 38f3537d01..49bd715e43 100644 --- a/spring-boot-modules/spring-caching-2/src/main/resources/application.properties +++ b/spring-boot-modules/spring-caching-2/src/main/resources/application.properties @@ -11,3 +11,4 @@ caching.spring.hotelListTTL=43200 # Connection details #spring.redis.host=localhost #spring.redis.port=6379 +spring.main.allow-bean-definition-overriding=true diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java index 8868edb74f..01740ba780 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java @@ -5,8 +5,6 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import java.util.Optional; - import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -20,10 +18,12 @@ import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; +import redis.embedded.RedisServer; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; -import redis.embedded.RedisServer; +import java.io.IOException; +import java.util.Optional; @Import({ CacheConfig.class, ItemService.class }) @ExtendWith(SpringExtension.class) @@ -69,17 +69,17 @@ class ItemServiceCachingIntegrationTest { private final RedisServer redisServer; - public EmbeddedRedisConfiguration() { + public EmbeddedRedisConfiguration() throws IOException { this.redisServer = new RedisServer(); } @PostConstruct - public void startRedis() { + public void startRedis() throws IOException { redisServer.start(); } @PreDestroy - public void stopRedis() { + public void stopRedis() throws IOException { this.redisServer.stop(); } } diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java new file mode 100644 index 0000000000..3db53198fc --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java @@ -0,0 +1,124 @@ +package com.baeldung.caching.twolevelcache; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; +import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import redis.embedded.RedisServer; + +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; +import java.io.IOException; +import java.util.Optional; +import java.util.concurrent.TimeUnit; + +@Import({ CacheConfig.class,CustomerService.class }) +@ExtendWith(SpringExtension.class) +@ImportAutoConfiguration(classes = { CacheAutoConfiguration.class, RedisAutoConfiguration.class }) +@EnableCaching +class CustomerServiceCachingIntegrationTest { + + @MockBean + private CustomerRepository customerRepository; + + @Autowired + private CustomerService customerService; + + @Autowired + private CacheManager redisCacheManager; + + @Autowired + private CacheManager caffeineCacheManager; + + @Test + void givenCustomerIsPresent_whenGetCustomerCalled_thenReturnCustomerAndCacheIt() { + String CUSTOMER_ID = "100"; + Customer customer = new Customer(CUSTOMER_ID, "test", "test@mail.com"); + + given(customerRepository.findById(CUSTOMER_ID)).willReturn(Optional.of(customer)); + + Customer customerCacheMiss = customerService.getCustomer(CUSTOMER_ID); + + assertThat(customerCacheMiss).isEqualTo(customer); + verify(customerRepository, times(1)).findById(CUSTOMER_ID); + assertThat(customerFromCaffeineCache(CUSTOMER_ID)).isEqualTo(customer); + assertThat(customerFromRedisCache(CUSTOMER_ID)).isEqualTo(customer); + } + + @Test + void givenCustomerIsPresent_whenGetCustomerCalledTwice_thenReturnCustomerAndCacheIt() { + String CUSTOMER_ID = "101"; + Customer customer = new Customer(CUSTOMER_ID, "test", "test@mail.com"); + given(customerRepository.findById(CUSTOMER_ID)).willReturn(Optional.of(customer)); + + Customer customerCacheMiss = customerService.getCustomer(CUSTOMER_ID); + Customer customerCacheHit = customerService.getCustomer(CUSTOMER_ID); + + assertThat(customerCacheMiss).isEqualTo(customer); + assertThat(customerCacheHit).isEqualTo(customer); + verify(customerRepository, times(1)).findById(CUSTOMER_ID); + assertThat(customerFromCaffeineCache(CUSTOMER_ID)).isEqualTo(customer); + assertThat(customerFromRedisCache(CUSTOMER_ID)).isEqualTo(customer); + } + + @Test + void givenCustomerIsPresent_whenGetCustomerCalledTwiceAndFirstCacheExpired_thenReturnCustomerAndCacheIt() throws InterruptedException { + String CUSTOMER_ID = "102"; + Customer customer = new Customer(CUSTOMER_ID, "test", "test@mail.com"); + given(customerRepository.findById(CUSTOMER_ID)).willReturn(Optional.of(customer)); + + Customer customerCacheMiss = customerService.getCustomer(CUSTOMER_ID); + TimeUnit.SECONDS.sleep(3); + assertThat(customerFromCaffeineCache(CUSTOMER_ID)).isEqualTo(null); + Customer customerCacheHit = customerService.getCustomer(CUSTOMER_ID); + + verify(customerRepository, times(1)).findById(CUSTOMER_ID); + assertThat(customerCacheMiss).isEqualTo(customer); + assertThat(customerCacheHit).isEqualTo(customer); + assertThat(customerFromCaffeineCache(CUSTOMER_ID)).isEqualTo(customer); + assertThat(customerFromRedisCache(CUSTOMER_ID)).isEqualTo(customer); + } + + private Object customerFromRedisCache(String key) { + return redisCacheManager.getCache("customerCache").get(key) != null ? + redisCacheManager.getCache("customerCache").get(key).get() : null; + } + + private Object customerFromCaffeineCache(String key) { + return caffeineCacheManager.getCache("customerCache").get(key) != null ? + caffeineCacheManager.getCache("customerCache").get(key).get() : null; + } + + @TestConfiguration + static class EmbeddedRedisConfiguration { + + private final RedisServer redisServer; + + public EmbeddedRedisConfiguration() throws IOException { + this.redisServer = new RedisServer(); + } + + @PostConstruct + public void startRedis() throws IOException { + redisServer.start(); + } + + @PreDestroy + public void stopRedis() throws IOException { + this.redisServer.stop(); + } + } +} \ No newline at end of file diff --git a/spring-kafka-3/pom.xml b/spring-kafka-3/pom.xml index 894eab2576..f94ce7748b 100644 --- a/spring-kafka-3/pom.xml +++ b/spring-kafka-3/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 4.0.0 @@ -22,6 +22,7 @@ org.springframework.kafka spring-kafka + ${spring-kafka.version} com.fasterxml.jackson.core @@ -54,8 +55,9 @@ 17 - 3.0.12 + 3.1.2 1.19.3 4.2.0 + org.springframework.boot.SpringApplication.Application diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/deserialization/exception/KafkaErrorHandler.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/deserialization/exception/KafkaErrorHandler.java index ea4211ab53..99d676e6c5 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/deserialization/exception/KafkaErrorHandler.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/deserialization/exception/KafkaErrorHandler.java @@ -13,8 +13,9 @@ class KafkaErrorHandler implements CommonErrorHandler { private static final Logger log = LoggerFactory.getLogger(KafkaErrorHandler.class); @Override - public void handleRecord(Exception exception, ConsumerRecord record, Consumer consumer, MessageListenerContainer container) { + public boolean handleOne(Exception exception, ConsumerRecord record, Consumer consumer, MessageListenerContainer container) { handle(exception, consumer); + return true; } @Override diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/Constants.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/Constants.java new file mode 100644 index 0000000000..1b9f51f8a1 --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/Constants.java @@ -0,0 +1,6 @@ +package com.baeldung.spring.kafka.startstopconsumer; + +public class Constants { + public static final String MULTI_PARTITION_TOPIC = "multi_partition_topic"; + public static final String LISTENER_ID = "listener-id-1"; +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/KafkaConsumerConfig.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/KafkaConsumerConfig.java new file mode 100644 index 0000000000..d37345d2de --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/KafkaConsumerConfig.java @@ -0,0 +1,42 @@ +package com.baeldung.spring.kafka.startstopconsumer; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.annotation.EnableKafka; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.support.serializer.JsonDeserializer; + +import java.util.HashMap; +import java.util.Map; + +@EnableKafka +@Configuration +public class KafkaConsumerConfig { + + @Value("${spring.kafka.bootstrap-servers}") + private String bootstrapServers; + + @Bean + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory() { + ConcurrentKafkaListenerContainerFactory factory = + new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory()); + return factory; + } + + @Bean + public DefaultKafkaConsumerFactory consumerFactory() { + Map props = new HashMap<>(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); + props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + props.put(JsonDeserializer.TRUSTED_PACKAGES, "com.baeldung.spring.kafka.start.stop.consumer"); + return new DefaultKafkaConsumerFactory<>(props, new StringDeserializer(), + new JsonDeserializer<>(UserEvent.class)); + } +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/KafkaListenerControlService.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/KafkaListenerControlService.java new file mode 100644 index 0000000000..6d4c101c38 --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/KafkaListenerControlService.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.kafka.startstopconsumer; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.config.KafkaListenerEndpointRegistry; +import org.springframework.kafka.listener.MessageListenerContainer; +import org.springframework.stereotype.Service; + +@Service +public class KafkaListenerControlService { + + @Autowired + private KafkaListenerEndpointRegistry registry; + + public void startListener(String listenerId) { + MessageListenerContainer listenerContainer = registry.getListenerContainer(listenerId); + if (listenerContainer != null && !listenerContainer.isRunning()) { + listenerContainer.start(); + } + } + + public void stopListener(String listenerId) { + MessageListenerContainer listenerContainer = registry.getListenerContainer(listenerId); + if (listenerContainer != null && listenerContainer.isRunning()) { + listenerContainer.stop(); + } + } +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerApplication.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerApplication.java new file mode 100644 index 0000000000..f0cfe88717 --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.kafka.startstopconsumer; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class StartStopConsumerApplication { + public static void main(String[] args) { + SpringApplication.run(StartStopConsumerApplication.class, args); + } +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEvent.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEvent.java new file mode 100644 index 0000000000..1c4692b8ee --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEvent.java @@ -0,0 +1,20 @@ +package com.baeldung.spring.kafka.startstopconsumer; + +public class UserEvent { + private String userEventId; + + public UserEvent() { + } + + public UserEvent(String userEventId) { + this.userEventId = userEventId; + } + + public String getUserEventId() { + return userEventId; + } + + public void setUserEventId(String userEventId) { + this.userEventId = userEventId; + } +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEventListener.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEventListener.java new file mode 100644 index 0000000000..d68e70160f --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEventListener.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.kafka.startstopconsumer; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +@Component +public class UserEventListener { + + private static final Logger logger = LoggerFactory.getLogger(UserEventListener.class); + + @Autowired + UserEventStore userEventStore; + + @KafkaListener(id = Constants.LISTENER_ID, topics = Constants.MULTI_PARTITION_TOPIC, groupId = "test-group", + containerFactory = "kafkaListenerContainerFactory", autoStartup = "false") + public void processUserEvent(UserEvent userEvent) { + logger.info("Received UserEvent: " + userEvent.getUserEventId()); + userEventStore.addUserEvent(userEvent); + } +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEventStore.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEventStore.java new file mode 100644 index 0000000000..3da6f7352d --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEventStore.java @@ -0,0 +1,24 @@ +package com.baeldung.spring.kafka.startstopconsumer; + +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; + +@Component +public class UserEventStore { + + private final List userEvents = new ArrayList<>(); + + public void addUserEvent(UserEvent userEvent) { + userEvents.add(userEvent); + } + + public List getUserEvents() { + return userEvents; + } + + public void clearUserEvents() { + this.userEvents.clear(); + } +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/viewheaders/KafkaMessageConsumer.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/viewheaders/KafkaMessageConsumer.java index 3bdc13d968..a9a414ac9f 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/viewheaders/KafkaMessageConsumer.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/viewheaders/KafkaMessageConsumer.java @@ -20,13 +20,13 @@ public class KafkaMessageConsumer { String topicName = (String) headers.get(KafkaHeaders.TOPIC); System.out.println("Topic: " + topicName); - int partitionID = (int) headers.get(KafkaHeaders.RECEIVED_PARTITION_ID); + int partitionID = (int) headers.get(KafkaHeaders.RECEIVED_PARTITION); System.out.println("Partition ID: " + partitionID); } @KafkaListener(topics = { "my-topic" }, groupId = "my-consumer-group") public void listen(@Payload String message, @Header(KafkaHeaders.RECEIVED_TOPIC) String topicName, - @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) { + @Header(KafkaHeaders.RECEIVED_PARTITION) int partition) { System.out.println("Topic: " + topicName); System.out.println("Partition ID: " + partition); } diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java new file mode 100644 index 0000000000..7ea8729111 --- /dev/null +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java @@ -0,0 +1,105 @@ +package com.baeldung.spring.kafka.startstopconsumer; + +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.clients.producer.RecordMetadata; +import org.apache.kafka.common.serialization.LongSerializer; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +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.kafka.support.serializer.JsonSerializer; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.containers.KafkaContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; + +import static java.time.Duration.ofMillis; +import static java.time.Duration.ofSeconds; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; + + +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +// This live test needs a Docker Daemon running so that a kafka container can be created +@Testcontainers +@SpringBootTest(classes = StartStopConsumerApplication.class) +public class StartStopConsumerLiveTest { + + private static KafkaProducer producer; + + private static final Logger logger = LoggerFactory.getLogger(StartStopConsumerLiveTest.class); + + @Container + private static KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); + + @Autowired + KafkaListenerControlService kafkaListenerControlService; + + @Autowired + UserEventStore userEventStore; + + @DynamicPropertySource + static void setProps(DynamicPropertyRegistry registry) { + registry.add("spring.kafka.bootstrap-servers", KAFKA_CONTAINER::getBootstrapServers); + } + + @BeforeAll + static void beforeAll() { + Properties producerProperties = new Properties(); + producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); + producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class.getName()); + producer = new KafkaProducer<>(producerProperties); + Awaitility.setDefaultTimeout(ofSeconds(5)); + Awaitility.setDefaultPollInterval(ofMillis(50)); + } + + @AfterAll + static void destroy() { + KAFKA_CONTAINER.stop(); + } + + @BeforeEach + void beforeEach() { + this.userEventStore.clearUserEvents(); + } + + @Test + void processMessages_whenListenerIsRestarted_thenCorrectNumberOfMessagesAreConsumed() throws ExecutionException, InterruptedException { + kafkaListenerControlService.startListener(Constants.LISTENER_ID); + + //Verification that listener has started. + UserEvent startUserEventTest = new UserEvent(UUID.randomUUID().toString()); + producer.send(new ProducerRecord<>(Constants.MULTI_PARTITION_TOPIC, startUserEventTest)); + await().untilAsserted(() -> assertEquals(1, this.userEventStore.getUserEvents().size())); + this.userEventStore.clearUserEvents(); + + for (long count = 1; count <= 10; count++) { + UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + Future future = producer.send(new ProducerRecord<>(Constants.MULTI_PARTITION_TOPIC, userEvent)); + RecordMetadata metadata = future.get(); + if (count == 4) { + await().untilAsserted(() -> assertEquals(4, this.userEventStore.getUserEvents().size())); + this.kafkaListenerControlService.stopListener(Constants.LISTENER_ID); + this.userEventStore.clearUserEvents(); + } + logger.info("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); + } + assertEquals(0, this.userEventStore.getUserEvents().size()); + kafkaListenerControlService.startListener(Constants.LISTENER_ID); + await().untilAsserted(() -> assertEquals(6, this.userEventStore.getUserEvents().size())); + kafkaListenerControlService.stopListener(Constants.LISTENER_ID); + } +} \ No newline at end of file diff --git a/spring-reactive-modules/spring-webflux-amqp/pom.xml b/spring-reactive-modules/spring-webflux-amqp/pom.xml index 8ab8277d08..67faed216e 100755 --- a/spring-reactive-modules/spring-webflux-amqp/pom.xml +++ b/spring-reactive-modules/spring-webflux-amqp/pom.xml @@ -11,24 +11,12 @@ Spring WebFlux AMQP Sample - com.baeldung.spring.reactive - spring-reactive-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 - - - - - org.springframework.boot - spring-boot-dependencies - - 2.1.3.RELEASE - pom - import - - - diff --git a/spring-reactive-modules/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/AmqpReactiveController.java b/spring-reactive-modules/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/AmqpReactiveController.java index b71c32bd05..009ec87ddd 100644 --- a/spring-reactive-modules/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/AmqpReactiveController.java +++ b/spring-reactive-modules/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/AmqpReactiveController.java @@ -2,7 +2,7 @@ package com.baeldung.spring.amqp; import java.time.Duration; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,7 +31,7 @@ import reactor.core.publisher.Mono; @RestController public class AmqpReactiveController { - private static Logger log = LoggerFactory.getLogger(AmqpReactiveController.class); + private static final Logger log = LoggerFactory.getLogger(AmqpReactiveController.class); @Autowired private AmqpTemplate amqpTemplate; @@ -142,10 +142,10 @@ public class AmqpReactiveController { MessageListenerContainer mlc = messageListenerContainerFactory.createMessageListenerContainer(d.getRoutingKey()); - Flux f = Flux. create(emitter -> { + Flux f = Flux.create(emitter -> { log.info("[I168] Adding listener, queue={}", d.getRoutingKey()); - mlc.setupMessageListener((MessageListener) m -> { + mlc.setupMessageListener(m -> { String qname = m.getMessageProperties() .getConsumerQueue(); @@ -233,11 +233,11 @@ public class AmqpReactiveController { MessageListenerContainer mlc = messageListenerContainerFactory.createMessageListenerContainer(qname); - Flux f = Flux. create(emitter -> { + Flux f = Flux.create(emitter -> { log.info("[I168] Adding listener, queue={}", qname); - mlc.setupMessageListener((MessageListener) m -> { + mlc.setupMessageListener(m -> { log.info("[I137] Message received, queue={}", qname); diff --git a/spring-reactive-modules/spring-webflux-amqp/src/test/java/com/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java b/spring-reactive-modules/spring-webflux-amqp/src/test/java/com/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java index 81782ce575..7829a9db67 100644 --- a/spring-reactive-modules/spring-webflux-amqp/src/test/java/com/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java +++ b/spring-reactive-modules/spring-webflux-amqp/src/test/java/com/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java @@ -15,7 +15,7 @@ public class SpringWebfluxAmqpLiveTest { client.post() .uri("/queue/NYSE") - .syncBody("Test Message") + .bodyValue("Test Message") .exchange() .expectStatus().isAccepted(); diff --git a/spring-security-modules/spring-security-pkce/pkce-auth-server/pom.xml b/spring-security-modules/spring-security-pkce/pkce-auth-server/pom.xml index 1fba6501f0..f1a8c71077 100644 --- a/spring-security-modules/spring-security-pkce/pkce-auth-server/pom.xml +++ b/spring-security-modules/spring-security-pkce/pkce-auth-server/pom.xml @@ -18,12 +18,7 @@ org.springframework.security spring-security-oauth2-authorization-server - ${spring-authorization-server.version} - - 0.3.1 - - \ No newline at end of file diff --git a/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/AuthServerConfiguration.java b/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/AuthServerConfiguration.java index b599880f3c..326bfc5bda 100644 --- a/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/AuthServerConfiguration.java +++ b/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/AuthServerConfiguration.java @@ -5,24 +5,22 @@ import java.util.UUID; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; +import org.springframework.http.MediaType; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; -import org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer; -import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; -import org.springframework.security.crypto.password.NoOpPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.core.oidc.OidcScopes; import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; -import org.springframework.security.oauth2.server.authorization.config.ClientSettings; -import org.springframework.security.oauth2.server.authorization.config.ProviderSettings; +import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; +import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer; +import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings; +import org.springframework.security.oauth2.server.authorization.settings.ClientSettings; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; -import org.springframework.security.web.util.matcher.RequestMatcher; +import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher; @Configuration public class AuthServerConfiguration { @@ -30,38 +28,30 @@ public class AuthServerConfiguration { @Bean @Order(1) public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { - - OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer<>(); - // @formatter:off + OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); + http.getConfigurer(OAuth2AuthorizationServerConfigurer.class) + .oidc(Customizer.withDefaults()); http - .requestMatcher(authorizationServerConfigurer.getEndpointsMatcher()) - .authorizeRequests(authorize -> - authorize - .anyRequest() - .authenticated()); - http - .exceptionHandling(exceptions -> - exceptions.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))) - .csrf( csrf -> - csrf - .ignoringRequestMatchers(authorizationServerConfigurer.getEndpointsMatcher())) - .apply(authorizationServerConfigurer); - - // Required by /userinfo endpoint - http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); + // Redirect to the login page when not authenticated from the + // authorization endpoint + .exceptionHandling((exceptions) -> exceptions.defaultAuthenticationEntryPointFor(new LoginUrlAuthenticationEntryPoint("/login"), + new MediaTypeRequestMatcher(MediaType.TEXT_HTML))) + // Accept access tokens for User Info and/or Client Registration + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults())); + return http.build(); - // @formatter:on } @Bean @Order(2) public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { - // @formatter:off - return http - .formLogin(Customizer.withDefaults()) - .build(); - // @formatter:on + http + .authorizeHttpRequests((authorize) -> authorize + .anyRequest().authenticated() + ) + .formLogin(Customizer.withDefaults()); + return http.build(); } @Bean @@ -89,8 +79,8 @@ public class AuthServerConfiguration { } @Bean - public ProviderSettings providerSettings() { - return ProviderSettings + public AuthorizationServerSettings authorizationServerSettings() { + return AuthorizationServerSettings .builder() .build(); } diff --git a/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/JwksConfiguration.java b/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/JwksConfiguration.java index a253141101..e3307a7a30 100644 --- a/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/JwksConfiguration.java +++ b/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/JwksConfiguration.java @@ -8,8 +8,8 @@ import java.util.UUID; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.RSAKey; diff --git a/spring-security-modules/spring-security-pkce/pom.xml b/spring-security-modules/spring-security-pkce/pom.xml index e0bd8eb90e..7c86e2852a 100644 --- a/spring-security-modules/spring-security-pkce/pom.xml +++ b/spring-security-modules/spring-security-pkce/pom.xml @@ -10,7 +10,8 @@ com.baeldung - spring-security-modules + parent-boot-3 + ../../parent-boot-3 0.0.1-SNAPSHOT diff --git a/spring-web-modules/spring-rest-angular/pom.xml b/spring-web-modules/spring-rest-angular/pom.xml index 36f9694fa1..c94ba1dfbe 100644 --- a/spring-web-modules/spring-rest-angular/pom.xml +++ b/spring-web-modules/spring-rest-angular/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -55,7 +55,6 @@ io.rest-assured spring-mock-mvc - ${rest-assured.version} test diff --git a/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/entity/Student.java b/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/entity/Student.java index 849b35cf24..49e73a9223 100644 --- a/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/entity/Student.java +++ b/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/entity/Student.java @@ -2,9 +2,9 @@ package com.baeldung.web.entity; import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; @Entity public class Student implements Serializable { diff --git a/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/service/IOperations.java b/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/service/IOperations.java index 60cb4382f4..3ec108d0fc 100644 --- a/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/service/IOperations.java +++ b/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/service/IOperations.java @@ -4,6 +4,6 @@ import org.springframework.data.domain.Page; public interface IOperations { - public Page findPaginated(final int page, final int size); + Page findPaginated(final int page, final int size); } diff --git a/spring-web-modules/spring-rest-angular/src/test/java/com/baeldung/web/service/StudentServiceIntegrationTest.java b/spring-web-modules/spring-rest-angular/src/test/java/com/baeldung/web/service/StudentServiceIntegrationTest.java index 654c4ef647..0702eae8e5 100644 --- a/spring-web-modules/spring-rest-angular/src/test/java/com/baeldung/web/service/StudentServiceIntegrationTest.java +++ b/spring-web-modules/spring-rest-angular/src/test/java/com/baeldung/web/service/StudentServiceIntegrationTest.java @@ -11,7 +11,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java index 20c70ce27b..fe4b2ad227 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java @@ -13,11 +13,7 @@ import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; +import org.mockito.*; import org.mockito.junit.jupiter.MockitoExtension; import com.baeldung.mockito.MyDictionary; @@ -127,4 +123,14 @@ class MockitoAnnotationUnitTest { assertEquals("aMeaning", dic.getMeaning("aWord")); } + + @DoNotMock(reason = "Use a real instance instead") + public abstract class NotToMock { + // Class implementation + } + @Test + public void testOperation() { + // This will cause an error due to @DoNotMock annotation + //NotToMock noToMock = mock(NotToMock.class); + } } diff --git a/testing-modules/spring-mockito/pom.xml b/testing-modules/spring-mockito/pom.xml index 8e13f511d2..4deaffe125 100644 --- a/testing-modules/spring-mockito/pom.xml +++ b/testing-modules/spring-mockito/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -33,4 +33,8 @@ + + com.baeldung.Main + + \ No newline at end of file diff --git a/vaadin/pom.xml b/vaadin/pom.xml index aa37a2392a..e3786471f5 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -32,6 +32,7 @@ javax.servlet javax.servlet-api + 4.0.1 provided diff --git a/vaadin/src/main/java/com/baeldung/Employee.java b/vaadin/src/main/java/com/baeldung/Employee.java index 726f0838b6..75a0dc84b3 100644 --- a/vaadin/src/main/java/com/baeldung/Employee.java +++ b/vaadin/src/main/java/com/baeldung/Employee.java @@ -1,8 +1,8 @@ package com.baeldung; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; @Entity public class Employee { diff --git a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java index 22ce19f5e0..05a8340bde 100644 --- a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java +++ b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java @@ -8,8 +8,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import javax.servlet.annotation.WebServlet; - import com.vaadin.annotations.Push; import com.vaadin.annotations.Theme; import com.vaadin.annotations.VaadinServletConfiguration; @@ -41,6 +39,7 @@ import com.vaadin.ui.TextField; import com.vaadin.ui.TwinColSelect; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; +import jakarta.servlet.annotation.WebServlet; @SuppressWarnings("serial") @Push diff --git a/web-modules/jersey/pom.xml b/web-modules/jersey/pom.xml index 779403e8c1..cf7d4eadb5 100644 --- a/web-modules/jersey/pom.xml +++ b/web-modules/jersey/pom.xml @@ -104,7 +104,7 @@ - 3.1.1 + 3.1.5 diff --git a/web-modules/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java b/web-modules/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java index 92f2e77670..432a8f2eb6 100644 --- a/web-modules/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java +++ b/web-modules/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java @@ -41,6 +41,7 @@ public class StocksResourceIntegrationTest extends JerseyTest { resourceConfig.register(IllegalArgumentExceptionMapper.class); resourceConfig.register(ServerExceptionMapper.class); resourceConfig.packages("com.baeldung.jersey.exceptionhandling.rest"); + forceSet(TestProperties.CONTAINER_PORT, "0"); return resourceConfig; } diff --git a/web-modules/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java b/web-modules/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java index 5f23209c16..47736f90d7 100644 --- a/web-modules/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java +++ b/web-modules/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; import org.junit.Test; import jakarta.ws.rs.core.Application; @@ -15,6 +16,7 @@ public class GreetingsResourceIntegrationTest extends JerseyTest { @Override protected Application configure() { + forceSet(TestProperties.CONTAINER_PORT, "0"); return new ResourceConfig(Greetings.class); }