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/algorithms-modules/algorithms-miscellaneous-1/pom.xml b/algorithms-modules/algorithms-miscellaneous-1/pom.xml index a1ac607c29..b8c900ab98 100644 --- a/algorithms-modules/algorithms-miscellaneous-1/pom.xml +++ b/algorithms-modules/algorithms-miscellaneous-1/pom.xml @@ -19,11 +19,6 @@ commons-math3 ${commons-math3.version} - - com.google.guava - guava - ${guava.version} - commons-codec commons-codec diff --git a/algorithms-modules/algorithms-miscellaneous-5/pom.xml b/algorithms-modules/algorithms-miscellaneous-5/pom.xml index 92b8e7d1f5..c1739e3690 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/pom.xml +++ b/algorithms-modules/algorithms-miscellaneous-5/pom.xml @@ -29,11 +29,7 @@ tradukisto ${tradukisto.version} - - com.google.guava - guava - ${guava.version} - + jakarta.xml.bind diff --git a/algorithms-modules/algorithms-miscellaneous-7/README.md b/algorithms-modules/algorithms-miscellaneous-7/README.md index f22194e183..1d53235990 100644 --- a/algorithms-modules/algorithms-miscellaneous-7/README.md +++ b/algorithms-modules/algorithms-miscellaneous-7/README.md @@ -11,4 +11,5 @@ - [Find the Largest Prime Under the Given Number in Java](https://www.baeldung.com/java-largest-prime-lower-threshold) - [Count the Number of Unique Digits in an Integer using Java](https://www.baeldung.com/java-int-count-unique-digits) - [Generate Juggler Sequence in Java](https://www.baeldung.com/java-generate-juggler-sequence) +- [Finding the Parent of a Node in a Binary Search Tree with Java](https://www.baeldung.com/java-find-parent-node-binary-search-tree) - More articles: [[<-- prev]](/algorithms-miscellaneous-6) diff --git a/algorithms-modules/algorithms-miscellaneous-8/pom.xml b/algorithms-modules/algorithms-miscellaneous-8/pom.xml new file mode 100644 index 0000000000..29163c5de7 --- /dev/null +++ b/algorithms-modules/algorithms-miscellaneous-8/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + algorithms-miscellaneous-8 + 0.0.1-SNAPSHOT + algorithms-miscellaneous-8 + + + com.baeldung + algorithms-modules + 1.0.0-SNAPSHOT + + + diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipher.java b/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipher.java similarity index 100% rename from algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipher.java rename to algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipher.java diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipherUnitTest.java b/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipherUnitTest.java similarity index 68% rename from algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipherUnitTest.java rename to algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipherUnitTest.java index 0e61e9c42e..ea463caa08 100644 --- a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipherUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-8/src/test/java/com/baeldung/algorithms/vigenere/VigenereCipherUnitTest.java @@ -24,17 +24,17 @@ public class VigenereCipherUnitTest { @Test void encodeArticleTitle() { VigenereCipher cipher = new VigenereCipher(); - String output = cipher.encode("VEGENERE CIPHER IN JAVA", "BAELDUNG"); + String output = cipher.encode("VIGENERE CIPHER IN JAVA", "BAELDUNG"); - Assertions.assertEquals("XFLQRZFL EJUTIM WU LBAM", output); + Assertions.assertEquals("XJLQRZFL EJUTIM WU LBAM", output); } @Test void encodeArticleTitleMoreCharacters() { VigenereCipher cipher = new VigenereCipher("ABCDEFGHIJKLMNOPQRSTUVWXYZ "); - String output = cipher.encode("VEGENERE CIPHER IN JAVA", "BAELDUNG"); + String output = cipher.encode("VIGENERE CIPHER IN JAVA", "BAELDUNG"); - Assertions.assertEquals("XFLQRZELBDNALZEGKOEVEPO", output); + Assertions.assertEquals("XJLQRZELBDNALZEGKOEVEPO", output); } @Test @@ -56,8 +56,21 @@ public class VigenereCipherUnitTest { @Test void decodeArticleTitleMoreCharacters() { VigenereCipher cipher = new VigenereCipher("ABCDEFGHIJKLMNOPQRSTUVWXYZ "); - String output = cipher.decode("XFLQRZELBDNALZEGKOEVEPO", "BAELDUNG"); + String output = cipher.decode("XJLQRZELBDNALZEGKOEVEPO", "BAELDUNG"); - Assertions.assertEquals("VEGENERE CIPHER IN JAVA", output); + Assertions.assertEquals("VIGENERE CIPHER IN JAVA", output); + } + + @Test + void encodeDecodeBaeldung() { + VigenereCipher cipher = new VigenereCipher(); + + String input = "BAELDUNG"; + String key = "HELLO"; + + String encoded = cipher.encode(input, key); + String decoded = cipher.decode(encoded, key); + + Assertions.assertEquals(input, decoded); } } diff --git a/algorithms-modules/pom.xml b/algorithms-modules/pom.xml index fda8eea0e7..d3f27f4fa8 100644 --- a/algorithms-modules/pom.xml +++ b/algorithms-modules/pom.xml @@ -22,6 +22,7 @@ algorithms-miscellaneous-5 algorithms-miscellaneous-6 algorithms-miscellaneous-7 + algorithms-miscellaneous-8 algorithms-searching algorithms-sorting algorithms-sorting-2 @@ -34,4 +35,4 @@ 1.0.1 - \ No newline at end of file + 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 2647f977e4..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 @@ -176,12 +176,6 @@ ${jstl.version} runtime - - - com.google.guava - guava - ${guava.version} - org.springframework @@ -199,7 +193,6 @@ true - diff --git a/apache-kafka-2/README.md b/apache-kafka-2/README.md index bc3a8885bf..c938e70f6b 100644 --- a/apache-kafka-2/README.md +++ b/apache-kafka-2/README.md @@ -16,3 +16,4 @@ You can build the project from the command line using: *mvn clean install*, or i - [Introduction to Apache Kafka](https://www.baeldung.com/apache-kafka) - [Ensuring Message Ordering in Kafka: Strategies and Configurations](https://www.baeldung.com/kafka-message-ordering) - [Read Multiple Messages with Apache Kafka](https://www.baeldung.com/kafka-read-multiple-messages) +- [Creating a Kafka Listener Using the Consumer API](https://www.baeldung.com/kafka-create-listener-consumer-api) diff --git a/apache-kafka-3/README.md b/apache-kafka-3/README.md new file mode 100644 index 0000000000..0b96e55385 --- /dev/null +++ b/apache-kafka-3/README.md @@ -0,0 +1,9 @@ +## Apache Kafka + +This module contains articles about Apache Kafka. + +##### Building the project +You can build the project from the command line using: *mvn clean install*, or in an IDE. + +### Relevant Articles: + diff --git a/apache-kafka-3/pom.xml b/apache-kafka-3/pom.xml new file mode 100644 index 0000000000..ad51e1de44 --- /dev/null +++ b/apache-kafka-3/pom.xml @@ -0,0 +1,48 @@ + + + 4.0.0 + apache-kafka-3 + apache-kafka-3 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.apache.kafka + kafka-clients + ${kafka.version} + + + org.slf4j + slf4j-api + ${org.slf4j.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.databind.version} + + + + + 3.6.1 + 2.15.2 + + + + integration-jdk9-and-above + + + \ No newline at end of file diff --git a/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/AsyncCommit.java b/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/AsyncCommit.java new file mode 100644 index 0000000000..6b6e615d65 --- /dev/null +++ b/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/AsyncCommit.java @@ -0,0 +1,23 @@ +package com.baeldung.kafka.commitoffset; + +import com.baeldung.kafka.commitoffset.config.KafkaConfigProperties; + +import java.time.Duration; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; + +public class AsyncCommit { + + public static void main(String[] args) { + + KafkaConsumer consumer = new KafkaConsumer<>(KafkaConfigProperties.getProperties()); + consumer.subscribe(KafkaConfigProperties.getTopic()); + ConsumerRecords messages = consumer.poll(Duration.ofSeconds(10)); + for (ConsumerRecord message : messages) { + // processed message + consumer.commitAsync(); + } + } +} diff --git a/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/AutomaticCommit.java b/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/AutomaticCommit.java new file mode 100644 index 0000000000..6fca7db43a --- /dev/null +++ b/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/AutomaticCommit.java @@ -0,0 +1,26 @@ +package com.baeldung.kafka.commitoffset; + +import com.baeldung.kafka.commitoffset.config.KafkaConfigProperties; + +import java.time.Duration; +import java.util.Properties; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; + +public class AutomaticCommit { + + public static void main(String[] args) { + + Properties properties = KafkaConfigProperties.getProperties(); + properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true"); + KafkaConsumer consumer = new KafkaConsumer<>(properties); + consumer.subscribe(KafkaConfigProperties.getTopic()); + ConsumerRecords messages = consumer.poll(Duration.ofSeconds(10)); + for (ConsumerRecord message : messages) { + // processed message + } + } +} diff --git a/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/SpecificOffsetCommit.java b/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/SpecificOffsetCommit.java new file mode 100644 index 0000000000..07f099a844 --- /dev/null +++ b/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/SpecificOffsetCommit.java @@ -0,0 +1,34 @@ +package com.baeldung.kafka.commitoffset; + +import com.baeldung.kafka.commitoffset.config.KafkaConfigProperties; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.clients.consumer.OffsetAndMetadata; +import org.apache.kafka.common.TopicPartition; + +public class SpecificOffsetCommit { + public static void main(String[] args) { + + KafkaConsumer consumer = new KafkaConsumer<>(KafkaConfigProperties.getProperties()); + consumer.subscribe(KafkaConfigProperties.getTopic()); + Map currentOffsets = new HashMap<>(); + int messageProcessed = 0; + while (true) { + ConsumerRecords messages = consumer.poll(Duration.ofSeconds(10)); + for (ConsumerRecord message : messages) { + // processed message + messageProcessed++; + currentOffsets.put(new TopicPartition(message.topic(), message.partition()), new OffsetAndMetadata(message.offset() + 1)); + if (messageProcessed % 50 == 0) { + consumer.commitSync(currentOffsets); + } + } + } + } +} diff --git a/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/SyncCommit.java b/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/SyncCommit.java new file mode 100644 index 0000000000..54f6b5f826 --- /dev/null +++ b/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/SyncCommit.java @@ -0,0 +1,23 @@ +package com.baeldung.kafka.commitoffset; + +import com.baeldung.kafka.commitoffset.config.KafkaConfigProperties; + +import java.time.Duration; + +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; + +public class SyncCommit { + + public static void main(String[] args) { + + KafkaConsumer consumer = new KafkaConsumer<>(KafkaConfigProperties.getProperties()); + consumer.subscribe(KafkaConfigProperties.getTopic()); + ConsumerRecords messages = consumer.poll(Duration.ofSeconds(10)); + for (ConsumerRecord message : messages) { + // processed message + consumer.commitSync(); + } + } +} diff --git a/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/config/KafkaConfigProperties.java b/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/config/KafkaConfigProperties.java new file mode 100644 index 0000000000..9b2096a610 --- /dev/null +++ b/apache-kafka-3/src/main/java/com/baeldung/kafka/commitoffset/config/KafkaConfigProperties.java @@ -0,0 +1,31 @@ +package com.baeldung.kafka.commitoffset.config; + +import java.util.ArrayList; +import java.util.Properties; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; + +/** + * @author amitkumar + */ +public class KafkaConfigProperties { + public static final String MY_TOPIC = "my-topic"; + + public static Properties getProperties() { + + Properties props = new Properties(); + props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false"); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092"); + props.put(ConsumerConfig.GROUP_ID_CONFIG, "MyFirstConsumer"); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + return props; + } + + public static ArrayList getTopic() { + ArrayList topics = new ArrayList<>(); + topics.add(MY_TOPIC); + return topics; + } +} diff --git a/apache-kafka-3/src/test/resources/logback.xml b/apache-kafka-3/src/test/resources/logback.xml new file mode 100644 index 0000000000..6156c2188e --- /dev/null +++ b/apache-kafka-3/src/test/resources/logback.xml @@ -0,0 +1,11 @@ + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + \ No newline at end of file diff --git a/apache-kafka/pom.xml b/apache-kafka/pom.xml index 6aa5fb894a..8bdcd30ebd 100644 --- a/apache-kafka/pom.xml +++ b/apache-kafka/pom.xml @@ -71,11 +71,6 @@ ${flink.version} test - - com.google.guava - guava - ${guava.version} - org.awaitility awaitility diff --git a/apache-libraries-2/README.md b/apache-libraries-2/README.md index c80677a4bc..0933653be0 100644 --- a/apache-libraries-2/README.md +++ b/apache-libraries-2/README.md @@ -1,3 +1,5 @@ ## Relevant Articles - [Understanding XSLT Processing in Java](https://www.baeldung.com/java-extensible-stylesheet-language-transformations) - [Add Camel Route at Runtime in Java](https://www.baeldung.com/java-camel-dynamic-route) + +- More articles: [[<-- prev]](../apache-libraries) 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-libraries/README.md b/apache-libraries/README.md index 6fe09008dc..410c0a2b36 100644 --- a/apache-libraries/README.md +++ b/apache-libraries/README.md @@ -13,3 +13,5 @@ This module contains articles about various Apache libraries and utilities - [Introduction to Apache Curator](https://www.baeldung.com/apache-curator) - [A Quick Guide to Apache Geode](https://www.baeldung.com/apache-geode) - [Guide To Solr in Java With Apache SolrJ](https://www.baeldung.com/apache-solrj) + +- More articles: [[next -->]](../apache-libraries-2) \ No newline at end of file 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 f4b6de8872..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 @@ -28,7 +28,7 @@ org.apache.httpcomponents httpclient - ${org.apache.httpcomponents.version} + ${httpclient.version} test @@ -60,7 +60,7 @@ - 4.5.2 + 4.5.2 1.7 2.0 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/README.md b/aws-modules/aws-s3/README.md index f3b34b584e..36dd1b4bfd 100644 --- a/aws-modules/aws-s3/README.md +++ b/aws-modules/aws-s3/README.md @@ -12,3 +12,4 @@ This module contains articles about Simple Storage Service (S3) on AWS - [Update an Existing Amazon S3 Object Using Java](https://www.baeldung.com/java-update-amazon-s3-object) - [How To Rename Files and Folders in Amazon S3](https://www.baeldung.com/java-amazon-s3-rename-files-folders) - [Update an Existing Amazon S3 Object Using Java](https://www.baeldung.com/java-update-amazon-s3-object) +- [How to Mock Amazon S3 for Integration Test](https://www.baeldung.com/java-amazon-simple-storage-service-mock-testing) 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/checker-framework/pom.xml b/checker-framework/pom.xml index dd3a9fd28b..4fbeb73631 100644 --- a/checker-framework/pom.xml +++ b/checker-framework/pom.xml @@ -5,8 +5,8 @@ 4.0.0 checker-framework 1.0-SNAPSHOT - checker-framework jar + checker-framework com.baeldung diff --git a/core-java-modules/core-java-10/pom.xml b/core-java-modules/core-java-10/pom.xml index 40fd75ee02..2551b1aa96 100644 --- a/core-java-modules/core-java-10/pom.xml +++ b/core-java-modules/core-java-10/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 core-java-10 - core-java-10 jar + core-java-10 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-11-2/pom.xml b/core-java-modules/core-java-11-2/pom.xml index 4647814048..6de1fc5586 100644 --- a/core-java-modules/core-java-11-2/pom.xml +++ b/core-java-modules/core-java-11-2/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 core-java-11-2 - core-java-11-2 jar + core-java-11-2 com.baeldung @@ -15,11 +15,6 @@ - - com.google.guava - guava - ${guava.version} - org.mock-server mockserver-junit-jupiter diff --git a/core-java-modules/core-java-11-3/pom.xml b/core-java-modules/core-java-11-3/pom.xml index 9d21958cff..cbe980d881 100644 --- a/core-java-modules/core-java-11-3/pom.xml +++ b/core-java-modules/core-java-11-3/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 core-java-11-3 - core-java-11-3 jar + core-java-11-3 com.baeldung diff --git a/core-java-modules/core-java-11/pom.xml b/core-java-modules/core-java-11/pom.xml index 7092f4e53d..b3b0e440ca 100644 --- a/core-java-modules/core-java-11/pom.xml +++ b/core-java-modules/core-java-11/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 core-java-11 - core-java-11 jar + core-java-11 com.baeldung @@ -15,11 +15,6 @@ - - com.google.guava - guava - ${guava.version} - org.openjdk.jmh jmh-core diff --git a/core-java-modules/core-java-12/pom.xml b/core-java-modules/core-java-12/pom.xml index ae61bdfad0..c5496c2c29 100644 --- a/core-java-modules/core-java-12/pom.xml +++ b/core-java-modules/core-java-12/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 core-java-12 - core-java-12 jar + core-java-12 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-13/pom.xml b/core-java-modules/core-java-13/pom.xml index b8ec8cfdb9..dbbf3a8329 100644 --- a/core-java-modules/core-java-13/pom.xml +++ b/core-java-modules/core-java-13/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 core-java-13 - core-java-13 jar + core-java-13 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-14/pom.xml b/core-java-modules/core-java-14/pom.xml index 38f640762f..669d6587dc 100644 --- a/core-java-modules/core-java-14/pom.xml +++ b/core-java-modules/core-java-14/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 core-java-14 - core-java-14 jar + core-java-14 com.baeldung diff --git a/core-java-modules/core-java-15/pom.xml b/core-java-modules/core-java-15/pom.xml index 5f1ff1bbca..27f3f4019b 100644 --- a/core-java-modules/core-java-15/pom.xml +++ b/core-java-modules/core-java-15/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 core-java-15 - core-java-15 jar + core-java-15 com.baeldung.core-java-modules @@ -13,7 +13,6 @@ 0.0.1-SNAPSHOT - org.apache.commons diff --git a/core-java-modules/core-java-16/pom.xml b/core-java-modules/core-java-16/pom.xml index c439a5bf12..8afd6f3dc7 100644 --- a/core-java-modules/core-java-16/pom.xml +++ b/core-java-modules/core-java-16/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 core-java-16 - core-java-16 jar + core-java-16 com.baeldung diff --git a/core-java-modules/core-java-17/pom.xml b/core-java-modules/core-java-17/pom.xml index aae19ff85e..f8ed207f6c 100644 --- a/core-java-modules/core-java-17/pom.xml +++ b/core-java-modules/core-java-17/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 core-java-17 - core-java-17 jar + core-java-17 com.baeldung diff --git a/core-java-modules/core-java-18/pom.xml b/core-java-modules/core-java-18/pom.xml index 78552d2c70..b9bd8982ab 100644 --- a/core-java-modules/core-java-18/pom.xml +++ b/core-java-modules/core-java-18/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 core-java-18 - core-java-18 jar + core-java-18 com.baeldung diff --git a/core-java-modules/core-java-8-datetime-2/pom.xml b/core-java-modules/core-java-8-datetime-2/pom.xml index 168177c87a..727ae91573 100644 --- a/core-java-modules/core-java-8-datetime-2/pom.xml +++ b/core-java-modules/core-java-8-datetime-2/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 core-java-8-datetime-2 - core-java-8-datetime-2 jar + core-java-8-datetime-2 com.baeldung.core-java-modules 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-8-datetime/pom.xml b/core-java-modules/core-java-8-datetime/pom.xml index cff27c9d44..8cf48fd467 100644 --- a/core-java-modules/core-java-8-datetime/pom.xml +++ b/core-java-modules/core-java-8-datetime/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 core-java-8-datetime - core-java-8-datetime jar + core-java-8-datetime com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-9-jigsaw/README.md b/core-java-modules/core-java-9-jigsaw/README.md index 73905e6033..b1630f04fc 100644 --- a/core-java-modules/core-java-9-jigsaw/README.md +++ b/core-java-modules/core-java-9-jigsaw/README.md @@ -5,7 +5,7 @@ This module contains articles about Project Jigsaw and the Java Platform Module ### Relevant Articles: - [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity) -- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity) +- [A Guide to Java Modularity](https://www.baeldung.com/java-modularity) - [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api) - [Java 9 Illegal Reflective Access Warning](https://www.baeldung.com/java-illegal-reflective-access) - [Java Modularity and Unit Testing](https://www.baeldung.com/java-modularity-unit-testing) diff --git a/core-java-modules/core-java-9-jigsaw/library-core/pom.xml b/core-java-modules/core-java-9-jigsaw/library-core/pom.xml index 415c7fb053..d1be46fd63 100644 --- a/core-java-modules/core-java-9-jigsaw/library-core/pom.xml +++ b/core-java-modules/core-java-9-jigsaw/library-core/pom.xml @@ -3,20 +3,14 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + library-core + com.baeldung.core-java-modules core-java-9-jigsaw 0.0.1-SNAPSHOT - library-core - - - 19 - 19 - UTF-8 - - org.junit.jupiter @@ -52,4 +46,11 @@ + + + 19 + 19 + UTF-8 + + \ No newline at end of file diff --git a/core-java-modules/core-java-9-jigsaw/pom.xml b/core-java-modules/core-java-9-jigsaw/pom.xml index 4afe2ae31a..6bbafeabae 100644 --- a/core-java-modules/core-java-9-jigsaw/pom.xml +++ b/core-java-modules/core-java-9-jigsaw/pom.xml @@ -4,8 +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 core-java-9-jigsaw - core-java-9-jigsaw pom + core-java-9-jigsaw + library-core diff --git a/core-java-modules/core-java-9-streams/pom.xml b/core-java-modules/core-java-9-streams/pom.xml index 903194b3b3..c8a6a22797 100644 --- a/core-java-modules/core-java-9-streams/pom.xml +++ b/core-java-modules/core-java-9-streams/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 core-java-9-streams - core-java-9-streams jar + core-java-9-streams com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-annotations/pom.xml b/core-java-modules/core-java-annotations/pom.xml index 6b1b9d802f..8796717310 100644 --- a/core-java-modules/core-java-annotations/pom.xml +++ b/core-java-modules/core-java-annotations/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 core-java-annotations - core-java-annotations jar + core-java-annotations com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-arrays-convert/pom.xml b/core-java-modules/core-java-arrays-convert/pom.xml index 480e1b3f07..eeabd1e360 100644 --- a/core-java-modules/core-java-arrays-convert/pom.xml +++ b/core-java-modules/core-java-arrays-convert/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 core-java-arrays-convert - core-java-arrays-convert jar + core-java-arrays-convert core-java-modules @@ -20,4 +20,5 @@ ${commons-lang3.version} + \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-guides/pom.xml b/core-java-modules/core-java-arrays-guides/pom.xml index 12da6b2145..a79d3a59e7 100644 --- a/core-java-modules/core-java-arrays-guides/pom.xml +++ b/core-java-modules/core-java-arrays-guides/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 core-java-arrays-guides - core-java-arrays-guides jar + core-java-arrays-guides core-java-modules diff --git a/core-java-modules/core-java-arrays-multidimensional/pom.xml b/core-java-modules/core-java-arrays-multidimensional/pom.xml index d314b07d85..bb37cd3f16 100644 --- a/core-java-modules/core-java-arrays-multidimensional/pom.xml +++ b/core-java-modules/core-java-arrays-multidimensional/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 core-java-arrays-multidimensional - core-java-arrays-multidimensional jar + core-java-arrays-multidimensional core-java-modules diff --git a/core-java-modules/core-java-arrays-operations-advanced-2/pom.xml b/core-java-modules/core-java-arrays-operations-advanced-2/pom.xml index a0ae2398a4..20bdb928ec 100644 --- a/core-java-modules/core-java-arrays-operations-advanced-2/pom.xml +++ b/core-java-modules/core-java-arrays-operations-advanced-2/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 core-java-arrays-operations-advanced-2 - core-java-arrays-operations-advanced-2 jar + core-java-arrays-operations-advanced-2 core-java-modules diff --git a/core-java-modules/core-java-arrays-operations-advanced/pom.xml b/core-java-modules/core-java-arrays-operations-advanced/pom.xml index 265577f75e..fad94672a1 100644 --- a/core-java-modules/core-java-arrays-operations-advanced/pom.xml +++ b/core-java-modules/core-java-arrays-operations-advanced/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 core-java-arrays-operations-advanced - core-java-arrays-operations-advanced jar + core-java-arrays-operations-advanced core-java-modules diff --git a/core-java-modules/core-java-arrays-operations-basic-2/pom.xml b/core-java-modules/core-java-arrays-operations-basic-2/pom.xml index 7257a39462..354da6d7ff 100644 --- a/core-java-modules/core-java-arrays-operations-basic-2/pom.xml +++ b/core-java-modules/core-java-arrays-operations-basic-2/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 core-java-arrays-operations-basic-2 - core-java-arrays-operations-basic-2 jar + core-java-arrays-operations-basic-2 core-java-modules diff --git a/core-java-modules/core-java-arrays-operations-basic/pom.xml b/core-java-modules/core-java-arrays-operations-basic/pom.xml index 6517b2efb9..6ce807ddc4 100644 --- a/core-java-modules/core-java-arrays-operations-basic/pom.xml +++ b/core-java-modules/core-java-arrays-operations-basic/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 core-java-arrays-operations-basic - core-java-arrays-operations-basic jar + core-java-arrays-operations-basic core-java-modules diff --git a/core-java-modules/core-java-arrays-sorting/pom.xml b/core-java-modules/core-java-arrays-sorting/pom.xml index 82e3f659fc..a67cd7b751 100644 --- a/core-java-modules/core-java-arrays-sorting/pom.xml +++ b/core-java-modules/core-java-arrays-sorting/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 core-java-arrays-sorting - core-java-arrays-sorting jar + core-java-arrays-sorting core-java-modules diff --git a/core-java-modules/core-java-booleans/pom.xml b/core-java-modules/core-java-booleans/pom.xml index 3b0c28208f..6ca2a6b1a2 100644 --- a/core-java-modules/core-java-booleans/pom.xml +++ b/core-java-modules/core-java-booleans/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 core-java-booleans - core-java-booleans jar + core-java-booleans com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-char/pom.xml b/core-java-modules/core-java-char/pom.xml index eb6cbee952..86d50436d2 100644 --- a/core-java-modules/core-java-char/pom.xml +++ b/core-java-modules/core-java-char/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 core-java-char - core-java-char jar + core-java-char com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-2/pom.xml b/core-java-modules/core-java-collections-2/pom.xml index e78f7b5dda..b06a9e5c8c 100644 --- a/core-java-modules/core-java-collections-2/pom.xml +++ b/core-java-modules/core-java-collections-2/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 core-java-collections-2 - core-java-collections-2 jar + core-java-collections-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-3/pom.xml b/core-java-modules/core-java-collections-3/pom.xml index 373dc9db14..e24b58d62b 100644 --- a/core-java-modules/core-java-collections-3/pom.xml +++ b/core-java-modules/core-java-collections-3/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 core-java-collections-3 - core-java-collections-3 jar + core-java-collections-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-4/pom.xml b/core-java-modules/core-java-collections-4/pom.xml index 1e54d65e35..696bc52335 100644 --- a/core-java-modules/core-java-collections-4/pom.xml +++ b/core-java-modules/core-java-collections-4/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 core-java-collections-4 - core-java-collections-4 jar + core-java-collections-4 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-5/pom.xml b/core-java-modules/core-java-collections-5/pom.xml index 06d872ec37..939e479ba1 100644 --- a/core-java-modules/core-java-collections-5/pom.xml +++ b/core-java-modules/core-java-collections-5/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 core-java-collections-5 - core-java-collections-5 jar + core-java-collections-5 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-array-list-2/pom.xml b/core-java-modules/core-java-collections-array-list-2/pom.xml index 901a4f5c75..b436324dca 100644 --- a/core-java-modules/core-java-collections-array-list-2/pom.xml +++ b/core-java-modules/core-java-collections-array-list-2/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-collections-array-list-2 - core-java-collections-array-list-2 jar + core-java-collections-array-list-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/MultiplePeakFinder.java b/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/MultiplePeakFinder.java new file mode 100644 index 0000000000..f8e13ee86e --- /dev/null +++ b/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/MultiplePeakFinder.java @@ -0,0 +1,40 @@ +package com.baeldung.peakelements; + +import java.util.ArrayList; +import java.util.List; + +public class MultiplePeakFinder { + + public static List findPeaks(int[] arr) { + + List peaks = new ArrayList<>(); + + if (arr == null || arr.length == 0) { + return peaks; + } + findPeakElements(arr, 0, arr.length - 1, peaks, arr.length); + return peaks; + } + + private static void findPeakElements(int[] arr, int low, int high, List peaks, int length) { + + if (low > high) { + return; + } + + int mid = low + (high - low) / 2; + + boolean isPeak = (mid == 0 || arr[mid] > arr[mid - 1]) && (mid == length - 1 || arr[mid] > arr[mid + 1]); + boolean isFirstInSequence = mid > 0 && arr[mid] == arr[mid - 1] && arr[mid] > arr[mid + 1]; + + if (isPeak || isFirstInSequence) { + + if (!peaks.contains(arr[mid])) { + peaks.add(arr[mid]); + } + } + + findPeakElements(arr, low, mid - 1, peaks, length); + findPeakElements(arr, mid + 1, high, peaks, length); + } +} diff --git a/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/PeakElementFinder.java b/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/PeakElementFinder.java new file mode 100644 index 0000000000..857ae3b1b2 --- /dev/null +++ b/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/PeakElementFinder.java @@ -0,0 +1,44 @@ +package com.baeldung.peakelements; + +import java.util.ArrayList; +import java.util.List; + +public class PeakElementFinder { + public List findPeakElements(int[] arr) { + int n = arr.length; + List peaks = new ArrayList<>(); + + if (n == 0) { + return peaks; + } + + for (int i = 0; i < n; i++) { + if (isPeak(arr, i, n)) { + peaks.add(arr[i]); + } + + while (i < n - 1 && arr[i] == arr[i + 1]) { + i++; + } + } + + return peaks; + } + + private boolean isPeak(int[] arr, int index, int n) { + if (index == 0) { + return n > 1 ? arr[index] >= arr[index + 1] : true; + } else if (index == n - 1) { + return arr[index] >= arr[index - 1]; + } else if (arr[index] == arr[index + 1] && arr[index] > arr[index - 1]) { + int i = index; + + while (i < n - 1 && arr[i] == arr[i + 1]) { + i++; + } + return i == n - 1 || arr[i] > arr[i + 1]; + } else { + return arr[index] >= arr[index - 1] && arr[index] >= arr[index + 1]; + } + } +} diff --git a/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/SinglePeakFinder.java b/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/SinglePeakFinder.java new file mode 100644 index 0000000000..f7b7cfc72b --- /dev/null +++ b/core-java-modules/core-java-collections-array-list-2/src/main/java/com/baeldung/peakelements/SinglePeakFinder.java @@ -0,0 +1,30 @@ +package com.baeldung.peakelements; + +import java.util.OptionalInt; + +public class SinglePeakFinder { + public static OptionalInt findSinglePeak(int[] arr) { + int n = arr.length; + + if (n < 2) { + return n == 0 ? OptionalInt.empty() : OptionalInt.of(arr[0]); + } + + if (arr[0] >= arr[1]) { + return OptionalInt.of(arr[0]); + } + + for (int i = 1; i < n - 1; i++) { + if (arr[i] >= arr[i - 1] && arr[i] >= arr[i + 1]) { + return OptionalInt.of(arr[i]); + } + } + + if (arr[n - 1] >= arr[n - 2]) { + return OptionalInt.of(arr[n - 1]); + } + + return OptionalInt.empty(); + } +} + diff --git a/core-java-modules/core-java-collections-array-list-2/src/test/java/com/baeldung/peakelements/MultiplePeakFinderUnitTest.java b/core-java-modules/core-java-collections-array-list-2/src/test/java/com/baeldung/peakelements/MultiplePeakFinderUnitTest.java new file mode 100644 index 0000000000..bc145c654d --- /dev/null +++ b/core-java-modules/core-java-collections-array-list-2/src/test/java/com/baeldung/peakelements/MultiplePeakFinderUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.peakelements; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +public class MultiplePeakFinderUnitTest { + + @Test + void findPeaks_givenArrayOfIntegers_whenValidInput_thenReturnsCorrectPeaks() { + MultiplePeakFinder finder = new MultiplePeakFinder(); + int[] array = {1, 13, 7, 0, 4, 1, 4, 45, 50}; + List peaks = finder.findPeaks(array); + + assertEquals(3, peaks.size()); + assertTrue(peaks.contains(4)); + assertTrue(peaks.contains(13)); + assertTrue(peaks.contains(50)); + } +} + diff --git a/core-java-modules/core-java-collections-array-list-2/src/test/java/com/baeldung/peakelements/PeakElementFinderUnitTest.java b/core-java-modules/core-java-collections-array-list-2/src/test/java/com/baeldung/peakelements/PeakElementFinderUnitTest.java new file mode 100644 index 0000000000..fc521272b4 --- /dev/null +++ b/core-java-modules/core-java-collections-array-list-2/src/test/java/com/baeldung/peakelements/PeakElementFinderUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.peakelements; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +public class PeakElementFinderUnitTest { + + @Test + void findPeakElement_givenArrayOfIntegers_whenValidInput_thenReturnsCorrectPeak() { + PeakElementFinder finder = new PeakElementFinder(); + int[] array = {1, 2, 3, 2, 1}; + List peaks = finder.findPeakElements(array); + assertEquals(1, peaks.size()); + assertTrue(peaks.contains(3)); + } + + @Test + void findPeakElement_givenArrayOfIntegers_whenNoPeaks_thenReturnsEmptyList() { + PeakElementFinder finder = new PeakElementFinder(); + int[] array = {}; + List peaks = finder.findPeakElements(array); + assertEquals(0, peaks.size()); + } + + @Test + void findPeakElement_givenArrayOfIntegers_whenPeaksAtExtremes_thenReturnsCorrectPeak() { + PeakElementFinder finder = new PeakElementFinder(); + int[] array = {5, 2, 1, 3, 4}; + List peaks = finder.findPeakElements(array); + assertEquals(2, peaks.size()); + assertTrue(peaks.contains(5)); + assertTrue(peaks.contains(4)); + } + + @Test + void findPeakElement_givenArrayOfIntegers_whenPlateaus_thenReturnsCorrectPeak() { + PeakElementFinder finder = new PeakElementFinder(); + int[] array = {1, 2, 2, 2, 3, 4, 5}; + List peaks = finder.findPeakElements(array); + assertEquals(1, peaks.size()); + assertTrue(peaks.contains(5)); + } +} diff --git a/core-java-modules/core-java-collections-array-list-2/src/test/java/com/baeldung/peakelements/SinglePeakFinderUnitTest.java b/core-java-modules/core-java-collections-array-list-2/src/test/java/com/baeldung/peakelements/SinglePeakFinderUnitTest.java new file mode 100644 index 0000000000..9e4cea2c0e --- /dev/null +++ b/core-java-modules/core-java-collections-array-list-2/src/test/java/com/baeldung/peakelements/SinglePeakFinderUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.peakelements; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.OptionalInt; + +public class SinglePeakFinderUnitTest { + + @Test + void findSinglePeak_givenArrayOfIntegers_whenValidInput_thenReturnsCorrectPeak() { + int[] arr = {0, 10, 2, 4, 5, 1}; + OptionalInt peak = SinglePeakFinder.findSinglePeak(arr); + assertTrue(peak.isPresent()); + assertEquals(10, peak.getAsInt()); + } + + @Test + void findSinglePeak_givenEmptyArray_thenReturnsEmptyOptional() { + int[] arr = {}; + OptionalInt peak = SinglePeakFinder.findSinglePeak(arr); + assertTrue(peak.isEmpty()); + } + + @Test + void findSinglePeak_givenEqualElementArray_thenReturnsCorrectPeak() { + int[] arr = {-2, -2, -2, -2, -2}; + OptionalInt peak = SinglePeakFinder.findSinglePeak(arr); + assertTrue(peak.isPresent()); + assertEquals(-2, peak.getAsInt()); + } +} diff --git a/core-java-modules/core-java-collections-array-list/pom.xml b/core-java-modules/core-java-collections-array-list/pom.xml index 034b2d820d..384808af07 100644 --- a/core-java-modules/core-java-collections-array-list/pom.xml +++ b/core-java-modules/core-java-collections-array-list/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 core-java-collections-array-list - core-java-collections-array-list jar + core-java-collections-array-list com.baeldung.core-java-modules @@ -19,12 +19,6 @@ commons-collections4 ${commons-collections4.version} - - com.google.guava - guava - ${guava.version} - test - diff --git a/core-java-modules/core-java-collections-conversions-2/pom.xml b/core-java-modules/core-java-collections-conversions-2/pom.xml index 7723daa6db..bb88cbebd1 100644 --- a/core-java-modules/core-java-collections-conversions-2/pom.xml +++ b/core-java-modules/core-java-collections-conversions-2/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 core-java-collections-conversions-2 - core-java-collections-conversions-2 jar + core-java-collections-conversions-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-conversions-3/pom.xml b/core-java-modules/core-java-collections-conversions-3/pom.xml index 4813d33713..d55a1aecdf 100644 --- a/core-java-modules/core-java-collections-conversions-3/pom.xml +++ b/core-java-modules/core-java-collections-conversions-3/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 core-java-collections-conversions-3 - core-java-collections-conversions-3 jar + core-java-collections-conversions-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-conversions/pom.xml b/core-java-modules/core-java-collections-conversions/pom.xml index 78e9847c0a..d01eae043f 100644 --- a/core-java-modules/core-java-collections-conversions/pom.xml +++ b/core-java-modules/core-java-collections-conversions/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 core-java-collections-conversions - core-java-collections-conversions jar + core-java-collections-conversions com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-list-2/pom.xml b/core-java-modules/core-java-collections-list-2/pom.xml index a305cdffc8..2b3c00601e 100644 --- a/core-java-modules/core-java-collections-list-2/pom.xml +++ b/core-java-modules/core-java-collections-list-2/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 core-java-collections-list-2 - core-java-collections-list-2 jar + core-java-collections-list-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-list-3/pom.xml b/core-java-modules/core-java-collections-list-3/pom.xml index f01fe1f3b9..8d40210cfd 100644 --- a/core-java-modules/core-java-collections-list-3/pom.xml +++ b/core-java-modules/core-java-collections-list-3/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 core-java-collections-list-3 - core-java-collections-list-3 jar + core-java-collections-list-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-list-4/pom.xml b/core-java-modules/core-java-collections-list-4/pom.xml index 0f170b0b85..067808d2d1 100644 --- a/core-java-modules/core-java-collections-list-4/pom.xml +++ b/core-java-modules/core-java-collections-list-4/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 core-java-collections-list-4 - core-java-collections-list-4 jar + core-java-collections-list-4 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-list-5/pom.xml b/core-java-modules/core-java-collections-list-5/pom.xml index 8fc5062ac0..d370b14858 100644 --- a/core-java-modules/core-java-collections-list-5/pom.xml +++ b/core-java-modules/core-java-collections-list-5/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 core-java-collections-list-5 - core-java-collections-list-5 jar + core-java-collections-list-5 com.baeldung.core-java-modules @@ -60,6 +60,5 @@ 1.21 2.10.1 - 20230618 \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-6/pom.xml b/core-java-modules/core-java-collections-list-6/pom.xml index 06e00e8dce..a560417f9e 100644 --- a/core-java-modules/core-java-collections-list-6/pom.xml +++ b/core-java-modules/core-java-collections-list-6/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 core-java-collections-list-6 - core-java-collections-list-6 jar + core-java-collections-list-6 com.baeldung.core-java-modules @@ -14,11 +14,6 @@ - - com.google.guava - guava - ${guava.version} - io.vavr vavr diff --git a/core-java-modules/core-java-collections-list/pom.xml b/core-java-modules/core-java-collections-list/pom.xml index 94abb334e0..1516123c47 100644 --- a/core-java-modules/core-java-collections-list/pom.xml +++ b/core-java-modules/core-java-collections-list/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 core-java-collections-list - core-java-collections-list jar + core-java-collections-list com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-maps-2/pom.xml b/core-java-modules/core-java-collections-maps-2/pom.xml index 15ca688ad2..c5fd5f637a 100644 --- a/core-java-modules/core-java-collections-maps-2/pom.xml +++ b/core-java-modules/core-java-collections-maps-2/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 core-java-collections-maps-2 - core-java-collections-maps-2 jar + core-java-collections-maps-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-maps-3/pom.xml b/core-java-modules/core-java-collections-maps-3/pom.xml index 98a0d18fe9..9f67d588ca 100644 --- a/core-java-modules/core-java-collections-maps-3/pom.xml +++ b/core-java-modules/core-java-collections-maps-3/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 core-java-collections-maps-3 - core-java-collections-maps-3 jar + core-java-collections-maps-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-maps-4/pom.xml b/core-java-modules/core-java-collections-maps-4/pom.xml index 5f7b40fbf6..1ba50187fe 100644 --- a/core-java-modules/core-java-collections-maps-4/pom.xml +++ b/core-java-modules/core-java-collections-maps-4/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 core-java-collections-maps-4 - core-java-collections-maps-4 jar + core-java-collections-maps-4 com.baeldung.core-java-modules @@ -24,11 +24,6 @@ commons-collections4 ${commons-collections4.version} - - com.google.guava - guava - ${guava.version} - junit junit diff --git a/core-java-modules/core-java-collections-maps-5/pom.xml b/core-java-modules/core-java-collections-maps-5/pom.xml index 593ec5a8f6..11c3e5e3e4 100644 --- a/core-java-modules/core-java-collections-maps-5/pom.xml +++ b/core-java-modules/core-java-collections-maps-5/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 core-java-collections-maps-5 - core-java-collections-maps-5 jar + core-java-collections-maps-5 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-maps-6/pom.xml b/core-java-modules/core-java-collections-maps-6/pom.xml index 6d10115d31..88c82623d0 100644 --- a/core-java-modules/core-java-collections-maps-6/pom.xml +++ b/core-java-modules/core-java-collections-maps-6/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 core-java-collections-maps-6 - core-java-collections-maps-6 jar + core-java-collections-maps-6 core-java-modules @@ -32,7 +32,7 @@ org.json json - 20230227 + ${org.json.version} junit diff --git a/core-java-modules/core-java-collections-maps-7/README.md b/core-java-modules/core-java-collections-maps-7/README.md index da777d72c3..b8e4454c61 100644 --- a/core-java-modules/core-java-collections-maps-7/README.md +++ b/core-java-modules/core-java-collections-maps-7/README.md @@ -1,6 +1,5 @@ ## Relevant Articles: - [Difference Between putIfAbsent() and computeIfAbsent() in Java’s Map](https://www.baeldung.com/java-map-putifabsent-computeifabsent) -- [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/how-to-write-and-read-a-file-with-a-java-hashmap/) - [How to Write Hashmap to CSV File](https://www.baeldung.com/java-write-hashmap-csv) - [How to Get First or Last Entry From a LinkedHashMap in Java](https://www.baeldung.com/java-linkedhashmap-first-last-key-value-pair) - [How to Write and Read a File with a Java HashMap](https://www.baeldung.com/java-hashmap-write-read-file) diff --git a/core-java-modules/core-java-collections-maps-7/pom.xml b/core-java-modules/core-java-collections-maps-7/pom.xml index b0f0d55c18..186096fe77 100644 --- a/core-java-modules/core-java-collections-maps-7/pom.xml +++ b/core-java-modules/core-java-collections-maps-7/pom.xml @@ -29,11 +29,7 @@ commons-csv ${csv.version} - - com.google.guava - guava - ${guava.version} - + org.openjdk.jmh jmh-core diff --git a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/writehashmaptocsvfile/WriteHashmaptoCVSFileUnitTest.java b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/writehashmaptocsvfile/WriteHashmaptoCVSFileUnitTest.java index e23a5da8ff..ace19bb00c 100644 --- a/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/writehashmaptocsvfile/WriteHashmaptoCVSFileUnitTest.java +++ b/core-java-modules/core-java-collections-maps-7/src/test/java/com/baeldung/map/writehashmaptocsvfile/WriteHashmaptoCVSFileUnitTest.java @@ -1,5 +1,6 @@ package com.baeldung.writehashmaptocsvfile; +import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import java.io.File; @@ -63,4 +64,16 @@ public class WriteHashmaptoCVSFileUnitTest { // Ensure the CSV file exists assertTrue(new File("employee_data2.csv").exists()); } + + @AfterAll + public static void cleanUp() { + final File employeeData = new File("employee_data.csv"); + if (employeeData.exists()) { + employeeData.deleteOnExit(); + } + final File employeeData2 = new File("employee_data2.csv"); + if (employeeData2.exists()) { + employeeData2.deleteOnExit(); + } + } } diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml index 5e19117e08..7f0f617df0 100644 --- a/core-java-modules/core-java-collections-maps/pom.xml +++ b/core-java-modules/core-java-collections-maps/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 core-java-collections-maps - core-java-collections-maps jar + core-java-collections-maps com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections-set-2/pom.xml b/core-java-modules/core-java-collections-set-2/pom.xml index 894bce86b7..ac4fd7dc73 100644 --- a/core-java-modules/core-java-collections-set-2/pom.xml +++ b/core-java-modules/core-java-collections-set-2/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 core-java-collections-set-2 - core-java-collections-set-2 jar + core-java-collections-set-2 com.baeldung.core-java-modules @@ -32,11 +32,6 @@ 7.7.0 test - - com.google.guava - guava - ${guava.version} - diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml index b3cd1ec90f..107ff0a22a 100644 --- a/core-java-modules/core-java-collections-set/pom.xml +++ b/core-java-modules/core-java-collections-set/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 core-java-collections-set - core-java-collections-set jar + core-java-collections-set com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections/pom.xml b/core-java-modules/core-java-collections/pom.xml index be91492d06..cb6f946cfd 100644 --- a/core-java-modules/core-java-collections/pom.xml +++ b/core-java-modules/core-java-collections/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 core-java-collections - core-java-collections jar + core-java-collections com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-collections/src/test/java/com/baeldung/listiteration/ListIterationUnitTest.java b/core-java-modules/core-java-collections/src/test/java/com/baeldung/listiteration/ListIterationUnitTest.java new file mode 100644 index 0000000000..2f1b2cc083 --- /dev/null +++ b/core-java-modules/core-java-collections/src/test/java/com/baeldung/listiteration/ListIterationUnitTest.java @@ -0,0 +1,71 @@ +package com.baeldung.listiteration; + +import org.junit.jupiter.api.Test; + +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertIterableEquals; + +public class ListIterationUnitTest { + + List programmingLanguages = new ArrayList<>(List.of("Java", "Python", "C++")); + List numbers = new ArrayList<>(List.of(1, 2, 3)); + + @Test + public void givenStringList_whenAddElementWithListIterator_thenModifiedList() { + ListIterator listIterator = programmingLanguages.listIterator(); + while (listIterator.hasNext()) { + String language = listIterator.next(); + if (language.equals("Python")) { + listIterator.add("JavaScript"); + } + } + + assertIterableEquals(Arrays.asList("Java", "Python", "JavaScript", "C++"), programmingLanguages); + } + + @Test + public void givenNumericalList_whenMultiplyElementWithListIterator_thenModifiedList() { + ListIterator listIterator = numbers.listIterator(); + while (listIterator.hasNext()) { + int num = listIterator.next(); + if (num == 2) { + listIterator.add(num * 10); + } + } + assertIterableEquals(Arrays.asList(1, 2, 20, 3), numbers); + } + + @Test + public void givenStringList_whenAddElementWithEnhancedForLoopAndCopy_thenModifiedList() { + List copyOfWords = new ArrayList<>(programmingLanguages); + for (String word : copyOfWords) { + programmingLanguages.add(word.toUpperCase()); // Modified: Convert to uppercase + } + assertIterableEquals(Arrays.asList("Java", "Python", "C++", "JAVA", "PYTHON", "C++"), programmingLanguages); + } + + @Test + public void givenNumericalList_whenMultiplyElementWithEnhancedForLoopAndCopy_thenModifiedList() { + List copyOfNumbers = new ArrayList<>(numbers); + for (int num : copyOfNumbers) { + numbers.add(num * 2); + } + assertIterableEquals(Arrays.asList(1, 2, 3, 2, 4, 6), numbers); + } + + @Test + public void givenStringList_whenConvertToUpperCaseWithJava8Stream_thenModifiedList() { + programmingLanguages = programmingLanguages.stream().map(String::toUpperCase).collect(Collectors.toList()); + assertIterableEquals(Arrays.asList("JAVA", "PYTHON", "C++"), programmingLanguages); + } + + @Test + public void givenNumericalList_whenMultiplyByThreeWithJava8Stream_thenModifiedList() { + numbers = numbers.stream().map(num -> num * 3).collect(Collectors.toList()); + assertIterableEquals(Arrays.asList(3, 6, 9), numbers); + } + +} diff --git a/core-java-modules/core-java-compiler/pom.xml b/core-java-modules/core-java-compiler/pom.xml index 8f2be3f142..86afbc1ca8 100644 --- a/core-java-modules/core-java-compiler/pom.xml +++ b/core-java-modules/core-java-compiler/pom.xml @@ -5,8 +5,8 @@ 4.0.0 core-java-compiler 0.1.0-SNAPSHOT - core-java-compiler jar + core-java-compiler com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-concurrency-2/pom.xml b/core-java-modules/core-java-concurrency-2/pom.xml index e373c829cc..593078a3b0 100644 --- a/core-java-modules/core-java-concurrency-2/pom.xml +++ b/core-java-modules/core-java-concurrency-2/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 core-java-concurrency-2 - core-java-concurrency-2 jar + core-java-concurrency-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-concurrency-advanced-2/pom.xml b/core-java-modules/core-java-concurrency-advanced-2/pom.xml index 5c96684311..8d8f259ca6 100644 --- a/core-java-modules/core-java-concurrency-advanced-2/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-2/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 core-java-concurrency-advanced-2 - core-java-concurrency-advanced-2 jar + core-java-concurrency-advanced-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-concurrency-advanced-3/pom.xml b/core-java-modules/core-java-concurrency-advanced-3/pom.xml index e3b399782e..cd3e9ed170 100644 --- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-3/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 core-java-concurrency-advanced-3 - core-java-concurrency-advanced-3 jar + core-java-concurrency-advanced-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-concurrency-advanced-4/pom.xml b/core-java-modules/core-java-concurrency-advanced-4/pom.xml index 2ffe19b13c..e79ecf8cc0 100644 --- a/core-java-modules/core-java-concurrency-advanced-4/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-4/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 core-java-concurrency-advanced-4 - core-java-concurrency-advanced-4 jar + core-java-concurrency-advanced-4 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-concurrency-advanced-5/README.md b/core-java-modules/core-java-concurrency-advanced-5/README.md index 718b5451dc..5a41310707 100644 --- a/core-java-modules/core-java-concurrency-advanced-5/README.md +++ b/core-java-modules/core-java-concurrency-advanced-5/README.md @@ -3,3 +3,4 @@ - [Why wait() Requires Synchronization?](https://www.baeldung.com/java-wait-necessary-synchronization) - [Working with Exceptions in Java CompletableFuture](https://www.baeldung.com/java-exceptions-completablefuture) - [CountDownLatch vs. Semaphore](https://www.baeldung.com/java-countdownlatch-vs-semaphore) +- [Callbacks in ListenableFuture and CompletableFuture](https://www.baeldung.com/java-callbacks-listenablefuture-completablefuture) diff --git a/core-java-modules/core-java-concurrency-advanced-5/pom.xml b/core-java-modules/core-java-concurrency-advanced-5/pom.xml index b84d3810bb..9caa943a57 100644 --- a/core-java-modules/core-java-concurrency-advanced-5/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-5/pom.xml @@ -2,11 +2,10 @@ - 4.0.0 core-java-concurrency-advanced-5 - core-java-concurrency-advanced-5 jar + core-java-concurrency-advanced-5 com.baeldung.core-java-modules @@ -29,8 +28,8 @@ - 1.8 - 1.8 + 9 + 9 \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/executorservicevscompletablefuture/CompletableFutureDemo.java b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/executorservicevscompletablefuture/CompletableFutureDemo.java new file mode 100644 index 0000000000..b45156db15 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/executorservicevscompletablefuture/CompletableFutureDemo.java @@ -0,0 +1,64 @@ +package com.baeldung.executorservicevscompletablefuture; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.TimeUnit; + +public class CompletableFutureDemo { + + public static void completableFutureMethod() { + CompletableFuture future = CompletableFuture.supplyAsync(() -> { + return 42; + }); + + System.out.println(future.join()); + } + + public static void chainingTaskExample() { + CompletableFuture firstTask = CompletableFuture.supplyAsync(() -> { + return 42; + }); + + CompletableFuture secondTask = firstTask.thenApply(result -> { + return "Result based on Task 1: " + result; + }); + + System.out.println(secondTask.join()); + } + + public static void exceptionHandlingExample() { + CompletableFuture future = CompletableFuture.supplyAsync(() -> { + // Simulate a task that might throw an exception + if (true) { + throw new RuntimeException("Something went wrong!"); + } + return "Success"; + }) + .exceptionally(ex -> { + System.err.println("Error in task: " + ex.getMessage()); + // Can optionally return a default value + return "Error occurred"; + }); + + future.thenAccept(result -> System.out.println("Result: " + result)); + } + + public static void timeoutExample() { + CompletableFuture future = CompletableFuture.supplyAsync(() -> { + try { + Thread.sleep(5000); + } catch (InterruptedException e) { + System.err.println("Task execution timed out!"); + } + return "Task completed"; + }); + + CompletableFuture timeoutFuture = future.completeOnTimeout("Timed out!", 2, TimeUnit.SECONDS); + String result = timeoutFuture.join(); + System.out.println("Result: " + result); + } + + public static void main(String[] args) { + timeoutExample(); + } +} diff --git a/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/executorservicevscompletablefuture/ExecutorServiceDemo.java b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/executorservicevscompletablefuture/ExecutorServiceDemo.java new file mode 100644 index 0000000000..99ddea9f2b --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/executorservicevscompletablefuture/ExecutorServiceDemo.java @@ -0,0 +1,98 @@ +package com.baeldung.executorservicevscompletablefuture; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +public class ExecutorServiceDemo { + + public static void executorServiceMethod() throws ExecutionException, InterruptedException { + ExecutorService executor = Executors.newFixedThreadPool(3); + Future future = executor.submit(() -> { + return 42; + }); + + System.out.println(future.get()); + } + + public static void chainingTaskExample() { + ExecutorService executor = Executors.newFixedThreadPool(2); + Future firstTask = executor.submit(() -> {return 42;}); + + Future secondTask = executor.submit(() -> { + try { + Integer result = firstTask.get(); + return "Result based on Task 1: " + result; + } catch (InterruptedException | ExecutionException e) { + // Handle exception + System.err.println("Error occured: " + e.getMessage()); + } + return null; + }); + executor.shutdown(); + + try { + // Wait for the second task to complete and retrieve the result + String result = secondTask.get(); + System.out.println(result); // Output: Result based on Task 1: 42 + } catch (InterruptedException | ExecutionException e) { + // Handle exception + System.err.println("Error occured: " + e.getMessage()); + } + } + + public static void exceptionHandlingExample() { + ExecutorService executor = Executors.newFixedThreadPool(2); + Future future = executor.submit(() -> { + // Simulate a task that might throw an exception + if (true) { + throw new RuntimeException("Something went wrong!"); + } + return "Success"; + }); + + try { + // This might block the main thread if the task throws an exception + String result = future.get(); + System.out.println("Result: " + result); + } catch (InterruptedException | ExecutionException e) { + // Handle exceptions thrown by the task or during retrieval + System.err.println("Error occured: " + e.getMessage()); + } finally { + executor.shutdown(); + } + } + + public static void timeoutExample() { + ExecutorService executor = Executors.newFixedThreadPool(2); + Future future = executor.submit(() -> { + try { + System.out.println("Start"); + Thread.sleep(5000); + System.out.println("End"); + } catch (InterruptedException e) { + System.err.println("Error occured: " + e.getMessage()); + } + return "Task completed"; + }); + + try { + String result = future.get(2, TimeUnit.SECONDS); + System.out.println("Result: " + result); + } catch (TimeoutException e) { + System.err.println("Task execution timed out!"); + future.cancel(true); + } catch (Exception e) { + System.err.println("Error occured: " + e.getMessage()); + } finally { + executor.shutdown(); + } + } + + public static void main(String[] args) throws ExecutionException, InterruptedException { + timeoutExample(); + } +} diff --git a/core-java-modules/core-java-concurrency-advanced/pom.xml b/core-java-modules/core-java-concurrency-advanced/pom.xml index 18cfc5371c..5a52bfe1fa 100644 --- a/core-java-modules/core-java-concurrency-advanced/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced/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 core-java-concurrency-advanced - core-java-concurrency-advanced jar + core-java-concurrency-advanced com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-concurrency-basic-2/pom.xml b/core-java-modules/core-java-concurrency-basic-2/pom.xml index 0cdfd68f03..524a944bcb 100644 --- a/core-java-modules/core-java-concurrency-basic-2/pom.xml +++ b/core-java-modules/core-java-concurrency-basic-2/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 core-java-concurrency-basic-2 - core-java-concurrency-basic-2 jar + core-java-concurrency-basic-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-concurrency-basic-3/pom.xml b/core-java-modules/core-java-concurrency-basic-3/pom.xml index 1983d3c163..30b601e083 100644 --- a/core-java-modules/core-java-concurrency-basic-3/pom.xml +++ b/core-java-modules/core-java-concurrency-basic-3/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 core-java-concurrency-basic-3 - core-java-concurrency-basic-3 jar + core-java-concurrency-basic-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-concurrency-basic/pom.xml b/core-java-modules/core-java-concurrency-basic/pom.xml index 6121cddc39..26bb64429d 100644 --- a/core-java-modules/core-java-concurrency-basic/pom.xml +++ b/core-java-modules/core-java-concurrency-basic/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 core-java-concurrency-basic - core-java-concurrency-basic jar + core-java-concurrency-basic com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-concurrency-collections-2/pom.xml b/core-java-modules/core-java-concurrency-collections-2/pom.xml index a85721e474..8f5f2f79ff 100644 --- a/core-java-modules/core-java-concurrency-collections-2/pom.xml +++ b/core-java-modules/core-java-concurrency-collections-2/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-concurrency-collections-2 - core-java-concurrency-collections-2 jar + core-java-concurrency-collections-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-concurrency-collections/pom.xml b/core-java-modules/core-java-concurrency-collections/pom.xml index a35da4ce49..6b24be095e 100644 --- a/core-java-modules/core-java-concurrency-collections/pom.xml +++ b/core-java-modules/core-java-concurrency-collections/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 core-java-concurrency-collections - core-java-concurrency-collections jar + core-java-concurrency-collections com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-concurrency-simple/pom.xml b/core-java-modules/core-java-concurrency-simple/pom.xml index eb196027aa..b36e16a667 100644 --- a/core-java-modules/core-java-concurrency-simple/pom.xml +++ b/core-java-modules/core-java-concurrency-simple/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-concurrency-simple - core-java-concurrency-simple jar + core-java-concurrency-simple com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-conditionals/pom.xml b/core-java-modules/core-java-conditionals/pom.xml index f2ad7df749..08ca6db2f7 100644 --- a/core-java-modules/core-java-conditionals/pom.xml +++ b/core-java-modules/core-java-conditionals/pom.xml @@ -5,8 +5,8 @@ 4.0.0 core-java-conditionals 0.1.0-SNAPSHOT - core-java-conditionals jar + core-java-conditionals com.baeldung diff --git a/core-java-modules/core-java-console/pom.xml b/core-java-modules/core-java-console/pom.xml index a761b2749e..e18f85e2d1 100644 --- a/core-java-modules/core-java-console/pom.xml +++ b/core-java-modules/core-java-console/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 core-java-console - core-java-console jar + core-java-console com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-date-operations-1/pom.xml b/core-java-modules/core-java-date-operations-1/pom.xml index 45a885db5e..1a824790b8 100644 --- a/core-java-modules/core-java-date-operations-1/pom.xml +++ b/core-java-modules/core-java-date-operations-1/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 core-java-date-operations-1 - core-java-date-operations-1 jar + core-java-date-operations-1 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-date-operations-2/pom.xml b/core-java-modules/core-java-date-operations-2/pom.xml index 86fbbf614e..cadc0e23fc 100644 --- a/core-java-modules/core-java-date-operations-2/pom.xml +++ b/core-java-modules/core-java-date-operations-2/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 core-java-date-operations-2 - core-java-date-operations-2 jar + core-java-date-operations-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-date-operations-3/pom.xml b/core-java-modules/core-java-date-operations-3/pom.xml index 8e4740785c..f0f1323c54 100644 --- a/core-java-modules/core-java-date-operations-3/pom.xml +++ b/core-java-modules/core-java-date-operations-3/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 core-java-date-operations-3 - core-java-date-operations-3 jar + core-java-date-operations-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-date-operations-4/pom.xml b/core-java-modules/core-java-date-operations-4/pom.xml index 317b2cb6e7..934a7ebb5f 100644 --- a/core-java-modules/core-java-date-operations-4/pom.xml +++ b/core-java-modules/core-java-date-operations-4/pom.xml @@ -4,8 +4,15 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-date-operations-4 + jar core-java-date-operations-4 + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + @@ -18,13 +25,6 @@ - jar - - - com.baeldung.core-java-modules - core-java-modules - 0.0.1-SNAPSHOT - diff --git a/core-java-modules/core-java-date-operations-4/src/test/java/com/baeldung/compareyesterday/CompareYesterdayUnitTest.java b/core-java-modules/core-java-date-operations-4/src/test/java/com/baeldung/compareyesterday/CompareYesterdayUnitTest.java new file mode 100644 index 0000000000..75f63317a7 --- /dev/null +++ b/core-java-modules/core-java-date-operations-4/src/test/java/com/baeldung/compareyesterday/CompareYesterdayUnitTest.java @@ -0,0 +1,116 @@ +package com.baeldung.compareyesterday; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.temporal.ChronoUnit; +import java.util.Calendar; +import java.util.Date; + +import org.joda.time.DateTime; +import org.junit.jupiter.api.Test; + +public class CompareYesterdayUnitTest { + + @Test + void givenYesterdayDate_whenCompareWithCalendar_returnTrue() { + // To simulate yesterday + Date date = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24)); + Calendar expectedCalendar = Calendar.getInstance(); + expectedCalendar.setTime(date); + + Calendar actualCalendar = Calendar.getInstance(); + actualCalendar.add(Calendar.DATE, -1); + + boolean isEqualToYesterday = expectedCalendar.get(Calendar.YEAR) == actualCalendar.get(Calendar.YEAR) && + expectedCalendar.get(Calendar.MONTH) == actualCalendar.get(Calendar.MONTH) && + expectedCalendar.get(Calendar.DAY_OF_MONTH) == actualCalendar.get(Calendar.DAY_OF_MONTH); + assertTrue(isEqualToYesterday); + } + + @Test + void givenTodayDate_whenCompareWithCalendar_returnFalse() { + Calendar expectedCalendar = Calendar.getInstance(); + + Calendar actualCalendar = Calendar.getInstance(); + actualCalendar.add(Calendar.DATE, -1); + + boolean isEqualToYesterday = expectedCalendar.get(Calendar.YEAR) == actualCalendar.get(Calendar.YEAR) && + expectedCalendar.get(Calendar.MONTH) == actualCalendar.get(Calendar.MONTH) && + expectedCalendar.get(Calendar.DAY_OF_MONTH) == actualCalendar.get(Calendar.DAY_OF_MONTH); + assertFalse(isEqualToYesterday); + } + + @Test + void givenYesterdayDate_whenCompareWithDateMilliseconds_returnTrue() { + // Create a Date object representing yesterday + Date expectedDate = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24)); + long yesterdayMidnightMillis = Instant.now() + .minus(1, ChronoUnit.DAYS) + .toEpochMilli(); + + boolean isEqualToYesterday = expectedDate.getTime() >= yesterdayMidnightMillis && expectedDate.getTime() < yesterdayMidnightMillis + 86_400_000; + assertTrue(isEqualToYesterday); + } + + @Test + void givenTodayDate_whenCompareWithDateMilliseconds_returnFalse() { + // Create a Date object representing yesterday + Date expectedDate = new Date(); + long yesterdayMidnightMillis = Instant.now() + .minus(1, ChronoUnit.DAYS) + .toEpochMilli(); + + boolean isEqualToYesterday = expectedDate.getTime() >= yesterdayMidnightMillis && expectedDate.getTime() < yesterdayMidnightMillis + 86_400_000; + assertFalse(isEqualToYesterday); + } + + @Test + void givenYesterdayDate_whenCompareWithLocalDate_returnTrue() { + // To simulate yesterday + Date date = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24)); + LocalDate expectedLocalDate = LocalDate.of(date.getYear() + 1900, date.getMonth() + 1, date.getDate()); + + LocalDate actualLocalDate = LocalDate.now() + .minusDays(1); + boolean isEqualToYesterday = expectedLocalDate.equals(actualLocalDate); + assertTrue(isEqualToYesterday); + } + + @Test + void givenTodayDate_whenCompareWithLocalDate_returnFalse() { + LocalDate expectedLocalDate = LocalDate.now(); + LocalDate actualLocalDate = LocalDate.now() + .minusDays(1); + boolean isEqualToYesterday = expectedLocalDate.equals(actualLocalDate); + assertFalse(isEqualToYesterday); + } + + @Test + void givenYesterdayDate_whenCompareWithJodaTime_returnTrue() { + // To simulate yesterday + Date date = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24)); + DateTime expectedDateTime = new DateTime(date).withTimeAtStartOfDay(); + + DateTime actualDateTime = DateTime.now() + .minusDays(1) + .withTimeAtStartOfDay(); + + boolean isEqualToYesterday = expectedDateTime.equals(actualDateTime); + assertTrue(isEqualToYesterday); + } + + @Test + void givenTodayDate_whenCompareWithJodaTime_returnFalse() { + DateTime expectedDateTime = DateTime.now() + .withTimeAtStartOfDay(); + DateTime actualDateTime = DateTime.now() + .minusDays(1) + .withTimeAtStartOfDay(); + + boolean isEqualToYesterday = expectedDateTime.equals(actualDateTime); + assertFalse(isEqualToYesterday); + } +} diff --git a/core-java-modules/core-java-datetime-conversion-2/pom.xml b/core-java-modules/core-java-datetime-conversion-2/pom.xml index 13849bc563..74819926d8 100644 --- a/core-java-modules/core-java-datetime-conversion-2/pom.xml +++ b/core-java-modules/core-java-datetime-conversion-2/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 core-java-datetime-conversion-2 - core-java-datetime-conversion-2 jar + core-java-datetime-conversion-2 com.baeldung.core-java-modules @@ -29,7 +29,6 @@ ummalqura-calendar ${ummalqura-calendar.version} - diff --git a/core-java-modules/core-java-datetime-conversion/pom.xml b/core-java-modules/core-java-datetime-conversion/pom.xml index 52ad29db5c..b0a9812d2a 100644 --- a/core-java-modules/core-java-datetime-conversion/pom.xml +++ b/core-java-modules/core-java-datetime-conversion/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 core-java-datetime-conversion - core-java-datetime-conversion jar + core-java-datetime-conversion com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-datetime-string-2/pom.xml b/core-java-modules/core-java-datetime-string-2/pom.xml index d37d4d69a4..c4210c8514 100644 --- a/core-java-modules/core-java-datetime-string-2/pom.xml +++ b/core-java-modules/core-java-datetime-string-2/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 core-java-datetime-string-2 - core-java-datetime-string-2 jar + core-java-datetime-string-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-datetime-string/pom.xml b/core-java-modules/core-java-datetime-string/pom.xml index 41c308aa6c..2bf5761907 100644 --- a/core-java-modules/core-java-datetime-string/pom.xml +++ b/core-java-modules/core-java-datetime-string/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 core-java-datetime-string - core-java-datetime-string jar + core-java-datetime-string com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-documentation/pom.xml b/core-java-modules/core-java-documentation/pom.xml index 23443dd5ea..da6f832fb1 100644 --- a/core-java-modules/core-java-documentation/pom.xml +++ b/core-java-modules/core-java-documentation/pom.xml @@ -5,8 +5,8 @@ 4.0.0 core-java-documentation 0.1.0-SNAPSHOT - core-java-documentation jar + core-java-documentation com.baeldung.core-java-modules @@ -14,9 +14,6 @@ 0.0.1-SNAPSHOT - - - diff --git a/core-java-modules/core-java-exceptions-2/pom.xml b/core-java-modules/core-java-exceptions-2/pom.xml index 8bf5605f09..bcb88446a5 100644 --- a/core-java-modules/core-java-exceptions-2/pom.xml +++ b/core-java-modules/core-java-exceptions-2/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-exceptions-2 - core-java-exceptions-2 jar + core-java-exceptions-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-exceptions-3/pom.xml b/core-java-modules/core-java-exceptions-3/pom.xml index 6ef979b54a..4ffe66f075 100644 --- a/core-java-modules/core-java-exceptions-3/pom.xml +++ b/core-java-modules/core-java-exceptions-3/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 core-java-exceptions-3 - core-java-exceptions-3 jar + core-java-exceptions-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-exceptions-4/pom.xml b/core-java-modules/core-java-exceptions-4/pom.xml index c41c782fcc..c57a87c107 100644 --- a/core-java-modules/core-java-exceptions-4/pom.xml +++ b/core-java-modules/core-java-exceptions-4/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 core-java-exceptions-4 - core-java-exceptions-4 jar + core-java-exceptions-4 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-exceptions/pom.xml b/core-java-modules/core-java-exceptions/pom.xml index 0bb6e86c76..111032c4b4 100644 --- a/core-java-modules/core-java-exceptions/pom.xml +++ b/core-java-modules/core-java-exceptions/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 core-java-exceptions - core-java-exceptions jar + core-java-exceptions com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-function/pom.xml b/core-java-modules/core-java-function/pom.xml index 4110b8f6d9..3da113da6a 100644 --- a/core-java-modules/core-java-function/pom.xml +++ b/core-java-modules/core-java-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 core-java-function - core-java-function jar + core-java-function com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-functional/pom.xml b/core-java-modules/core-java-functional/pom.xml index 3b21dd6e8a..ae912cee1f 100644 --- a/core-java-modules/core-java-functional/pom.xml +++ b/core-java-modules/core-java-functional/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 core-java-functional - core-java-functional jar + core-java-functional com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-hex/pom.xml b/core-java-modules/core-java-hex/pom.xml index 71e6b15b2e..3b45bdd85f 100644 --- a/core-java-modules/core-java-hex/pom.xml +++ b/core-java-modules/core-java-hex/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 core-java-hex - core-java-hex jar + core-java-hex com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-httpclient/pom.xml b/core-java-modules/core-java-httpclient/pom.xml index 593e73b5cb..a14a394908 100644 --- a/core-java-modules/core-java-httpclient/pom.xml +++ b/core-java-modules/core-java-httpclient/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 core-java-httpclient - core-java-httpclient jar + core-java-httpclient com.baeldung diff --git a/core-java-modules/core-java-io-2/pom.xml b/core-java-modules/core-java-io-2/pom.xml index 2892bb4a2e..0287d083b4 100644 --- a/core-java-modules/core-java-io-2/pom.xml +++ b/core-java-modules/core-java-io-2/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 core-java-io-2 - core-java-io-2 jar + core-java-io-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-io-3/pom.xml b/core-java-modules/core-java-io-3/pom.xml index d9e095ced2..f5e603bd32 100644 --- a/core-java-modules/core-java-io-3/pom.xml +++ b/core-java-modules/core-java-io-3/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 core-java-io-3 - core-java-io-3 jar + core-java-io-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-io-4/pom.xml b/core-java-modules/core-java-io-4/pom.xml index 78511b68bb..e2534ac714 100644 --- a/core-java-modules/core-java-io-4/pom.xml +++ b/core-java-modules/core-java-io-4/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 core-java-io-4 - core-java-io-4 jar + core-java-io-4 com.baeldung.core-java-modules @@ -25,11 +25,6 @@ commons-codec ${commons-codec.version} - - com.google.guava - guava - ${guava.version} - diff --git a/core-java-modules/core-java-io-5/README.md b/core-java-modules/core-java-io-5/README.md index ef7ea2d980..fb050ab2d2 100644 --- a/core-java-modules/core-java-io-5/README.md +++ b/core-java-modules/core-java-io-5/README.md @@ -9,5 +9,6 @@ This module contains articles about core Java input and output (IO) - [How to Write Strings to OutputStream in Java](https://www.baeldung.com/java-write-string-outputstream) - [Read a File and Split It Into Multiple Files in Java](https://www.baeldung.com/java-read-file-split-into-several) - [Read and Write Files in Java Using Separate Threads](https://www.baeldung.com/java-read-write-files-different-threads) +- [Convert an OutputStream to a Byte Array in Java](https://www.baeldung.com/java-outputstream-byte-array) - [[<-- Prev]](/core-java-modules/core-java-io-4) diff --git a/core-java-modules/core-java-io-5/pom.xml b/core-java-modules/core-java-io-5/pom.xml index 5c987a82e1..33a522c642 100644 --- a/core-java-modules/core-java-io-5/pom.xml +++ b/core-java-modules/core-java-io-5/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 core-java-io-5 - core-java-io-5 jar + core-java-io-5 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-io-apis-2/pom.xml b/core-java-modules/core-java-io-apis-2/pom.xml index 89ab6d163a..dc33e5338a 100644 --- a/core-java-modules/core-java-io-apis-2/pom.xml +++ b/core-java-modules/core-java-io-apis-2/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 core-java-io-apis-2 - core-java-io-apis-2 jar + core-java-io-apis-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-io-apis/pom.xml b/core-java-modules/core-java-io-apis/pom.xml index 688db146da..10ae4dc41d 100644 --- a/core-java-modules/core-java-io-apis/pom.xml +++ b/core-java-modules/core-java-io-apis/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 core-java-io-apis - core-java-io-apis jar + core-java-io-apis com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-io-conversions-2/pom.xml b/core-java-modules/core-java-io-conversions-2/pom.xml index 9be165eaff..a7087672d2 100644 --- a/core-java-modules/core-java-io-conversions-2/pom.xml +++ b/core-java-modules/core-java-io-conversions-2/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 core-java-io-conversions-2 - core-java-io-conversions-2 jar + core-java-io-conversions-2 com.baeldung.core-java-modules @@ -22,7 +22,7 @@ org.json json - ${json.version} + ${org.json.version} com.opencsv @@ -55,7 +55,6 @@ 11 11 - 20200518 5.8 diff --git a/core-java-modules/core-java-io-conversions/pom.xml b/core-java-modules/core-java-io-conversions/pom.xml index a44c352df2..002c282ea3 100644 --- a/core-java-modules/core-java-io-conversions/pom.xml +++ b/core-java-modules/core-java-io-conversions/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 core-java-io-conversions - core-java-io-conversions jar + core-java-io-conversions com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml index 93c9289fdd..4aa4c71e3a 100644 --- a/core-java-modules/core-java-io/pom.xml +++ b/core-java-modules/core-java-io/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 core-java-io - core-java-io jar + core-java-io com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-ipc/pom.xml b/core-java-modules/core-java-ipc/pom.xml index b7b37afb1d..a48970bd80 100644 --- a/core-java-modules/core-java-ipc/pom.xml +++ b/core-java-modules/core-java-ipc/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 core-java-ipc - core-java-ipc jar + core-java-ipc com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-jar/pom.xml b/core-java-modules/core-java-jar/pom.xml index b3376a503d..460adf45e7 100644 --- a/core-java-modules/core-java-jar/pom.xml +++ b/core-java-modules/core-java-jar/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 core-java-jar - core-java-jar jar + core-java-jar com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-jpms/pom.xml b/core-java-modules/core-java-jpms/pom.xml index 3cfa0e3f45..88b912ca55 100644 --- a/core-java-modules/core-java-jpms/pom.xml +++ b/core-java-modules/core-java-jpms/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 core-java-jpms - core-java-jpms pom + core-java-jpms com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-jvm-2/pom.xml b/core-java-modules/core-java-jvm-2/pom.xml index a2e553eacf..7ee6891d8d 100644 --- a/core-java-modules/core-java-jvm-2/pom.xml +++ b/core-java-modules/core-java-jvm-2/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 core-java-jvm-2 - core-java-jvm-2 jar + core-java-jvm-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-jvm-3/pom.xml b/core-java-modules/core-java-jvm-3/pom.xml index 78f4201c94..1e09403960 100644 --- a/core-java-modules/core-java-jvm-3/pom.xml +++ b/core-java-modules/core-java-jvm-3/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 core-java-jvm-3 - core-java-jvm-3 jar + core-java-jvm-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml index 97d8f49be5..be93be5909 100644 --- a/core-java-modules/core-java-jvm/pom.xml +++ b/core-java-modules/core-java-jvm/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 core-java-jvm - core-java-jvm jar + core-java-jvm com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-lambdas/pom.xml b/core-java-modules/core-java-lambdas/pom.xml index a7fc5355d7..b95308ba1b 100644 --- a/core-java-modules/core-java-lambdas/pom.xml +++ b/core-java-modules/core-java-lambdas/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 core-java-lambdas - core-java-lambdas jar + core-java-lambdas com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-lang-2/pom.xml b/core-java-modules/core-java-lang-2/pom.xml index 22055cf252..b85c8ce75a 100644 --- a/core-java-modules/core-java-lang-2/pom.xml +++ b/core-java-modules/core-java-lang-2/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 core-java-lang-2 - core-java-lang-2 jar + core-java-lang-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-lang-3/pom.xml b/core-java-modules/core-java-lang-3/pom.xml index f29fa6494a..4771b99f4b 100644 --- a/core-java-modules/core-java-lang-3/pom.xml +++ b/core-java-modules/core-java-lang-3/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 core-java-lang-3 - core-java-lang-3 jar + core-java-lang-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-lang-4/pom.xml b/core-java-modules/core-java-lang-4/pom.xml index 6977621a0e..900cfbe903 100644 --- a/core-java-modules/core-java-lang-4/pom.xml +++ b/core-java-modules/core-java-lang-4/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 core-java-lang-4 - core-java-lang-4 jar + core-java-lang-4 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-lang-5/pom.xml b/core-java-modules/core-java-lang-5/pom.xml index b65f061fc7..de06a67b3c 100644 --- a/core-java-modules/core-java-lang-5/pom.xml +++ b/core-java-modules/core-java-lang-5/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 core-java-lang-5 - core-java-lang-5 jar + core-java-lang-5 com.baeldung.core-java-modules 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-math/pom.xml b/core-java-modules/core-java-lang-math/pom.xml index 85e653930c..c8d261818a 100644 --- a/core-java-modules/core-java-lang-math/pom.xml +++ b/core-java-modules/core-java-lang-math/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 core-java-lang-math - core-java-lang-math jar + core-java-lang-math com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-lang-oop-constructors-2/pom.xml b/core-java-modules/core-java-lang-oop-constructors-2/pom.xml index c6d9d84774..d1a1288cc9 100644 --- a/core-java-modules/core-java-lang-oop-constructors-2/pom.xml +++ b/core-java-modules/core-java-lang-oop-constructors-2/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 core-java-lang-oop-constructors-2 - core-java-lang-oop-constructors-2 jar + core-java-lang-oop-constructors-2 core-java-modules diff --git a/core-java-modules/core-java-lang-oop-constructors/pom.xml b/core-java-modules/core-java-lang-oop-constructors/pom.xml index 061b3c08de..39e6c86821 100644 --- a/core-java-modules/core-java-lang-oop-constructors/pom.xml +++ b/core-java-modules/core-java-lang-oop-constructors/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 core-java-lang-oop-constructors - core-java-lang-oop-constructors jar + core-java-lang-oop-constructors core-java-modules diff --git a/core-java-modules/core-java-lang-oop-generics/pom.xml b/core-java-modules/core-java-lang-oop-generics/pom.xml index 9c453cae10..035c82324a 100644 --- a/core-java-modules/core-java-lang-oop-generics/pom.xml +++ b/core-java-modules/core-java-lang-oop-generics/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 core-java-lang-oop-generics - core-java-lang-oop-generics jar + core-java-lang-oop-generics core-java-modules diff --git a/core-java-modules/core-java-lang-oop-inheritance/pom.xml b/core-java-modules/core-java-lang-oop-inheritance/pom.xml index 4fc7e14d84..fe467545eb 100644 --- a/core-java-modules/core-java-lang-oop-inheritance/pom.xml +++ b/core-java-modules/core-java-lang-oop-inheritance/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 core-java-lang-oop-inheritance - core-java-lang-oop-inheritance jar + core-java-lang-oop-inheritance core-java-modules diff --git a/core-java-modules/core-java-lang-oop-methods/pom.xml b/core-java-modules/core-java-lang-oop-methods/pom.xml index 5597cff0ae..39207d71ed 100644 --- a/core-java-modules/core-java-lang-oop-methods/pom.xml +++ b/core-java-modules/core-java-lang-oop-methods/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 core-java-lang-oop-methods - core-java-lang-oop-methods jar + core-java-lang-oop-methods core-java-modules diff --git a/core-java-modules/core-java-lang-oop-modifiers/pom.xml b/core-java-modules/core-java-lang-oop-modifiers/pom.xml index 459aa21721..c1b3c7d308 100644 --- a/core-java-modules/core-java-lang-oop-modifiers/pom.xml +++ b/core-java-modules/core-java-lang-oop-modifiers/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 core-java-lang-oop-modifiers - core-java-lang-oop-modifiers jar + core-java-lang-oop-modifiers core-java-modules diff --git a/core-java-modules/core-java-lang-oop-others/pom.xml b/core-java-modules/core-java-lang-oop-others/pom.xml index dea92067f2..9e208a077b 100644 --- a/core-java-modules/core-java-lang-oop-others/pom.xml +++ b/core-java-modules/core-java-lang-oop-others/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 core-java-lang-oop-others - core-java-lang-oop-others jar + core-java-lang-oop-others core-java-modules diff --git a/core-java-modules/core-java-lang-oop-patterns/pom.xml b/core-java-modules/core-java-lang-oop-patterns/pom.xml index f0a714e911..3c1f94954a 100644 --- a/core-java-modules/core-java-lang-oop-patterns/pom.xml +++ b/core-java-modules/core-java-lang-oop-patterns/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 core-java-lang-oop-patterns - core-java-lang-oop-patterns jar + core-java-lang-oop-patterns core-java-modules diff --git a/core-java-modules/core-java-lang-oop-types/pom.xml b/core-java-modules/core-java-lang-oop-types/pom.xml index a9909598eb..9d36beb13e 100644 --- a/core-java-modules/core-java-lang-oop-types/pom.xml +++ b/core-java-modules/core-java-lang-oop-types/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 core-java-lang-oop-types - core-java-lang-oop-types jar + core-java-lang-oop-types core-java-modules diff --git a/core-java-modules/core-java-lang-operators-2/pom.xml b/core-java-modules/core-java-lang-operators-2/pom.xml index 4170f9f6a0..301f549011 100644 --- a/core-java-modules/core-java-lang-operators-2/pom.xml +++ b/core-java-modules/core-java-lang-operators-2/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 core-java-lang-operators-2 - core-java-lang-operators-2 jar + core-java-lang-operators-2 com.baeldung.core-java-modules 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-lang-operators/pom.xml b/core-java-modules/core-java-lang-operators/pom.xml index 1815d01dcc..1ea35da281 100644 --- a/core-java-modules/core-java-lang-operators/pom.xml +++ b/core-java-modules/core-java-lang-operators/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 core-java-lang-operators - core-java-lang-operators jar + core-java-lang-operators com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-lang-syntax-2/pom.xml b/core-java-modules/core-java-lang-syntax-2/pom.xml index bae5f0b6bd..b5d41958b7 100644 --- a/core-java-modules/core-java-lang-syntax-2/pom.xml +++ b/core-java-modules/core-java-lang-syntax-2/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 core-java-lang-syntax-2 - core-java-lang-syntax-2 jar + core-java-lang-syntax-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-lang-syntax/pom.xml b/core-java-modules/core-java-lang-syntax/pom.xml index 4e1b534110..5d366194de 100644 --- a/core-java-modules/core-java-lang-syntax/pom.xml +++ b/core-java-modules/core-java-lang-syntax/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 core-java-lang-syntax - core-java-lang-syntax jar + core-java-lang-syntax com.baeldung.core-java-modules @@ -13,9 +13,6 @@ 0.0.1-SNAPSHOT - - - core-java-lang-syntax diff --git a/core-java-modules/core-java-lang/pom.xml b/core-java-modules/core-java-lang/pom.xml index 27cf0ac276..7e0606b47f 100644 --- a/core-java-modules/core-java-lang/pom.xml +++ b/core-java-modules/core-java-lang/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 core-java-lang - core-java-lang jar + core-java-lang com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-locale/pom.xml b/core-java-modules/core-java-locale/pom.xml index f4fd823444..9f3368c659 100644 --- a/core-java-modules/core-java-locale/pom.xml +++ b/core-java-modules/core-java-locale/pom.xml @@ -5,8 +5,8 @@ 4.0.0 core-java-locale 0.1.0-SNAPSHOT - core-java-locale jar + core-java-locale com.baeldung.core-java-modules @@ -14,7 +14,4 @@ 0.0.1-SNAPSHOT - - - \ No newline at end of file diff --git a/core-java-modules/core-java-loops/pom.xml b/core-java-modules/core-java-loops/pom.xml index c9ce86f54b..a4969aaa0a 100644 --- a/core-java-modules/core-java-loops/pom.xml +++ b/core-java-modules/core-java-loops/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 core-java-loops - core-java-loops jar + core-java-loops com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-methods/pom.xml b/core-java-modules/core-java-methods/pom.xml index 5502cc6733..58b2ad6ebe 100644 --- a/core-java-modules/core-java-methods/pom.xml +++ b/core-java-modules/core-java-methods/pom.xml @@ -5,8 +5,8 @@ 4.0.0 core-java-methods 0.1.0-SNAPSHOT - core-java-methods jar + core-java-methods com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-networking-2/pom.xml b/core-java-modules/core-java-networking-2/pom.xml index 388e439e37..77ddd94fdc 100644 --- a/core-java-modules/core-java-networking-2/pom.xml +++ b/core-java-modules/core-java-networking-2/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 core-java-networking-2 - core-java-networking-2 jar + core-java-networking-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-networking-3/pom.xml b/core-java-modules/core-java-networking-3/pom.xml index 6d0374c598..26cfd206c0 100644 --- a/core-java-modules/core-java-networking-3/pom.xml +++ b/core-java-modules/core-java-networking-3/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 core-java-networking-3 - core-java-networking-3 jar + core-java-networking-3 com.baeldung.core-java-modules @@ -52,12 +52,6 @@ java-ipv6 ${googlecode.ipv6.version} - - - com.google.guava - guava - ${guava.version} - commons-validator diff --git a/core-java-modules/core-java-networking-4/pom.xml b/core-java-modules/core-java-networking-4/pom.xml index acdbf37c63..2ae1ea9068 100644 --- a/core-java-modules/core-java-networking-4/pom.xml +++ b/core-java-modules/core-java-networking-4/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 core-java-networking-4 - core-java-networking-4 jar + core-java-networking-4 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-networking/pom.xml b/core-java-modules/core-java-networking/pom.xml index 5c959c62be..2028d9b218 100644 --- a/core-java-modules/core-java-networking/pom.xml +++ b/core-java-modules/core-java-networking/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 core-java-networking - core-java-networking jar + core-java-networking com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-nio-2/pom.xml b/core-java-modules/core-java-nio-2/pom.xml index dde708c10d..f1360247b3 100644 --- a/core-java-modules/core-java-nio-2/pom.xml +++ b/core-java-modules/core-java-nio-2/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 core-java-nio-2 - core-java-nio-2 jar + core-java-nio-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-nio/pom.xml b/core-java-modules/core-java-nio/pom.xml index 35fef82df5..55dff63230 100644 --- a/core-java-modules/core-java-nio/pom.xml +++ b/core-java-modules/core-java-nio/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 core-java-nio - core-java-nio jar + core-java-nio com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-numbers-2/pom.xml b/core-java-modules/core-java-numbers-2/pom.xml index 46e0fa47b4..987f140c67 100644 --- a/core-java-modules/core-java-numbers-2/pom.xml +++ b/core-java-modules/core-java-numbers-2/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 core-java-numbers-2 - core-java-numbers-2 jar + core-java-numbers-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-numbers-3/pom.xml b/core-java-modules/core-java-numbers-3/pom.xml index 8acdaa6be4..28036faf5e 100644 --- a/core-java-modules/core-java-numbers-3/pom.xml +++ b/core-java-modules/core-java-numbers-3/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-numbers-3 - core-java-numbers-3 jar + core-java-numbers-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-numbers-4/pom.xml b/core-java-modules/core-java-numbers-4/pom.xml index 4fe8b292da..8633b06f3d 100644 --- a/core-java-modules/core-java-numbers-4/pom.xml +++ b/core-java-modules/core-java-numbers-4/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-numbers-4 - core-java-numbers-4 jar + core-java-numbers-4 com.baeldung.core-java-modules @@ -23,11 +23,6 @@ commons-lang3 ${commons-lang3.version} - - com.google.guava - guava - ${guava.version} - diff --git a/core-java-modules/core-java-numbers-5/pom.xml b/core-java-modules/core-java-numbers-5/pom.xml index c72ba66bff..e2bd67896f 100644 --- a/core-java-modules/core-java-numbers-5/pom.xml +++ b/core-java-modules/core-java-numbers-5/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-numbers-5 - core-java-numbers-5 jar + core-java-numbers-5 com.baeldung.core-java-modules @@ -24,11 +24,6 @@ commons-lang3 ${commons-lang3.version} - - com.google.guava - guava - ${guava.version} - diff --git a/core-java-modules/core-java-numbers-6/pom.xml b/core-java-modules/core-java-numbers-6/pom.xml index a5ddcfc0ee..95d01648a3 100644 --- a/core-java-modules/core-java-numbers-6/pom.xml +++ b/core-java-modules/core-java-numbers-6/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-numbers-6 - core-java-numbers-6 jar + core-java-numbers-6 com.baeldung.core-java-modules @@ -25,11 +25,6 @@ ${commons-codec} test - - com.google.guava - guava - ${guava.version} - diff --git a/core-java-modules/core-java-numbers-7/README.md b/core-java-modules/core-java-numbers-7/README.md index 271f4833e3..ab3532fc20 100644 --- a/core-java-modules/core-java-numbers-7/README.md +++ b/core-java-modules/core-java-numbers-7/README.md @@ -3,3 +3,4 @@ - [Print a Double Value Without Scientific Notation in Java](https://www.baeldung.com/java-print-double-number-no-scientific-notation) - [Check if a Float Value is Equivalent to an Integer Value in Java](https://www.baeldung.com/java-float-integer-equal) - [Generating Unique Positive Long Using SecureRandom in Java](https://www.baeldung.com/java-securerandom-generate-positive-long) +- [BigDecimal.ZERO vs. new BigDecimal(0)](https://www.baeldung.com/java-bigdecimal-zero-vs-new) diff --git a/core-java-modules/core-java-numbers-7/pom.xml b/core-java-modules/core-java-numbers-7/pom.xml index 3940a0b1d0..636113897e 100644 --- a/core-java-modules/core-java-numbers-7/pom.xml +++ b/core-java-modules/core-java-numbers-7/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-numbers-7 - core-java-numbers-7 jar + core-java-numbers-7 com.baeldung.core-java-modules @@ -19,11 +19,6 @@ ${junit-jupiter.version} test - - com.google.guava - guava - ${guava.version} - diff --git a/core-java-modules/core-java-numbers-conversions/README.md b/core-java-modules/core-java-numbers-conversions/README.md index 9f2a1d07b8..334d9c1f6e 100644 --- a/core-java-modules/core-java-numbers-conversions/README.md +++ b/core-java-modules/core-java-numbers-conversions/README.md @@ -6,5 +6,6 @@ - [Converting from float to BigDecimal in Java](https://www.baeldung.com/java-convert-float-bigdecimal) - [Convert Positive Integer to Negative and Vice Versa in Java](https://www.baeldung.com/java-negating-integer) - [Rounding Up a Number to Nearest Multiple of 5 in Java](https://www.baeldung.com/java-round-nearest-multiple-five) -- [Convert byte to int Type in Java](https://www.baeldung.com/java-byte-to-int-conversion) -- [Converting Integer to BigDecimal in Java](https://www.baeldung.com/java-integer-bigdecimal-conversion) +- [Convert byte to int Type in Java](https://www.baeldung.com/java-byte-integer-conversion) +- [Converting BigDecimal to Integer in Java](https://www.baeldung.com/java-integer-bigdecimal-conversion) +- [Converting Integer to BigDecimal in Java](https://www.baeldung.com/java-from-integer-to-bigdecimal) diff --git a/core-java-modules/core-java-numbers-conversions/pom.xml b/core-java-modules/core-java-numbers-conversions/pom.xml index 43809e8453..0cbd5823fe 100644 --- a/core-java-modules/core-java-numbers-conversions/pom.xml +++ b/core-java-modules/core-java-numbers-conversions/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-conversions.0.0.xsd"> 4.0.0 core-java-numbers-conversions - core-java-numbers-conversions jar + core-java-numbers-conversions com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-numbers/pom.xml b/core-java-modules/core-java-numbers/pom.xml index 1240245ba3..debc90638e 100644 --- a/core-java-modules/core-java-numbers/pom.xml +++ b/core-java-modules/core-java-numbers/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 core-java-numbers - core-java-numbers jar + core-java-numbers com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml index c676827427..7c1d873b46 100644 --- a/core-java-modules/core-java-optional/pom.xml +++ b/core-java-modules/core-java-optional/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 core-java-optional - core-java-optional jar + core-java-optional com.baeldung.core-java-modules @@ -54,7 +54,7 @@ 6.4.2.Final - 5.3.2 + 5.4.0 \ No newline at end of file diff --git a/core-java-modules/core-java-os-2/pom.xml b/core-java-modules/core-java-os-2/pom.xml index 27dc8a0c8b..9827ee2b47 100644 --- a/core-java-modules/core-java-os-2/pom.xml +++ b/core-java-modules/core-java-os-2/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 core-java-os-2 - core-java-os-2 jar + core-java-os-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-os/pom.xml b/core-java-modules/core-java-os/pom.xml index 17b0d1a058..58ccaea4c9 100644 --- a/core-java-modules/core-java-os/pom.xml +++ b/core-java-modules/core-java-os/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 core-java-os - core-java-os jar + core-java-os com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-perf-2/pom.xml b/core-java-modules/core-java-perf-2/pom.xml index a44f6aa8c1..a17180edbe 100644 --- a/core-java-modules/core-java-perf-2/pom.xml +++ b/core-java-modules/core-java-perf-2/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 core-java-perf-2 - core-java-perf-2 jar + core-java-perf-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-perf/pom.xml b/core-java-modules/core-java-perf/pom.xml index c21fc94ec1..026e0692d1 100644 --- a/core-java-modules/core-java-perf/pom.xml +++ b/core-java-modules/core-java-perf/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 core-java-perf - core-java-perf jar + core-java-perf com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-properties/pom.xml b/core-java-modules/core-java-properties/pom.xml index 9beacabdd5..67e0204c6e 100644 --- a/core-java-modules/core-java-properties/pom.xml +++ b/core-java-modules/core-java-properties/pom.xml @@ -5,8 +5,8 @@ 4.0.0 core-java-properties 0.1.0-SNAPSHOT - core-java-properties jar + core-java-properties com.baeldung.core-java-modules @@ -14,10 +14,4 @@ 0.0.1-SNAPSHOT - - - - - - \ No newline at end of file diff --git a/core-java-modules/core-java-reflection-2/pom.xml b/core-java-modules/core-java-reflection-2/pom.xml index c7a4981533..69cf4f5f37 100644 --- a/core-java-modules/core-java-reflection-2/pom.xml +++ b/core-java-modules/core-java-reflection-2/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 core-java-reflection-2 - core-java-reflection-2 jar + core-java-reflection-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-reflection-3/pom.xml b/core-java-modules/core-java-reflection-3/pom.xml index e60652f1f2..e4111b8dda 100644 --- a/core-java-modules/core-java-reflection-3/pom.xml +++ b/core-java-modules/core-java-reflection-3/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 core-java-reflection-3 - core-java-reflection-3 jar + core-java-reflection-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-reflection/pom.xml b/core-java-modules/core-java-reflection/pom.xml index f77c791936..a58d18c03f 100644 --- a/core-java-modules/core-java-reflection/pom.xml +++ b/core-java-modules/core-java-reflection/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 core-java-reflection - core-java-reflection jar + core-java-reflection com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-regex-2/pom.xml b/core-java-modules/core-java-regex-2/pom.xml index ddfba35cb2..83280bd310 100644 --- a/core-java-modules/core-java-regex-2/pom.xml +++ b/core-java-modules/core-java-regex-2/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 core-java-regex-2 - core-java-regex-2 jar + core-java-regex-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-regex-3/pom.xml b/core-java-modules/core-java-regex-3/pom.xml index 143b615246..b3e1019119 100644 --- a/core-java-modules/core-java-regex-3/pom.xml +++ b/core-java-modules/core-java-regex-3/pom.xml @@ -4,7 +4,15 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-regex-3 + jar core-java-regex-3 + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + org.junit.jupiter @@ -13,12 +21,5 @@ test - jar - - - com.baeldung.core-java-modules - core-java-modules - 0.0.1-SNAPSHOT - \ No newline at end of file diff --git a/core-java-modules/core-java-regex/pom.xml b/core-java-modules/core-java-regex/pom.xml index 00b8107c57..ca7fb38634 100644 --- a/core-java-modules/core-java-regex/pom.xml +++ b/core-java-modules/core-java-regex/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 core-java-regex - core-java-regex jar + core-java-regex com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-scanner/pom.xml b/core-java-modules/core-java-scanner/pom.xml index bb5c7dca78..9fb9d4ee05 100644 --- a/core-java-modules/core-java-scanner/pom.xml +++ b/core-java-modules/core-java-scanner/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 core-java-scanner - core-java-scanner jar + core-java-scanner com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-security-2/pom.xml b/core-java-modules/core-java-security-2/pom.xml index b54afc31d8..a7f47d2ff5 100644 --- a/core-java-modules/core-java-security-2/pom.xml +++ b/core-java-modules/core-java-security-2/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 core-java-security-2 - core-java-security-2 jar + core-java-security-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-security-3/pom.xml b/core-java-modules/core-java-security-3/pom.xml index dae570e51d..3ca0cf62aa 100644 --- a/core-java-modules/core-java-security-3/pom.xml +++ b/core-java-modules/core-java-security-3/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 core-java-security-3 - core-java-security-3 jar + core-java-security-3 com.baeldung.core-java-modules @@ -30,11 +30,6 @@ jaxb-api ${jaxb-api.version} - - com.google.guava - guava - ${guava.version} - org.springframework.security spring-security-crypto diff --git a/core-java-modules/core-java-security-4/pom.xml b/core-java-modules/core-java-security-4/pom.xml index 5bbf505079..e59ee0b5eb 100644 --- a/core-java-modules/core-java-security-4/pom.xml +++ b/core-java-modules/core-java-security-4/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 core-java-security-4 - core-java-security-4 jar + core-java-security-4 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-security-algorithms/README.md b/core-java-modules/core-java-security-algorithms/README.md index a1ce244ab8..c31e859e60 100644 --- a/core-java-modules/core-java-security-algorithms/README.md +++ b/core-java-modules/core-java-security-algorithms/README.md @@ -9,3 +9,4 @@ This module contains articles about core Java Security Algorithms such as AES, D - [InvalidAlgorithmParameterException: Wrong IV Length](https://www.baeldung.com/java-invalidalgorithmparameter-exception) - [RSA in Java](https://www.baeldung.com/java-rsa) - [3DES in Java](https://www.baeldung.com/java-3des) +- [Blowfish Encryption Algorithm](https://www.baeldung.com/java-jca-blowfish-implementation) diff --git a/core-java-modules/core-java-security-algorithms/pom.xml b/core-java-modules/core-java-security-algorithms/pom.xml index 0204203fd7..006000565d 100644 --- a/core-java-modules/core-java-security-algorithms/pom.xml +++ b/core-java-modules/core-java-security-algorithms/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 core-java-security-algorithms - core-java-security-algorithms jar + core-java-security-algorithms com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-security/pom.xml b/core-java-modules/core-java-security/pom.xml index 921017b080..0fd3f37ef1 100644 --- a/core-java-modules/core-java-security/pom.xml +++ b/core-java-modules/core-java-security/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 core-java-security - core-java-security jar + core-java-security com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-serialization/pom.xml b/core-java-modules/core-java-serialization/pom.xml index 5989dbf870..51011244b0 100644 --- a/core-java-modules/core-java-serialization/pom.xml +++ b/core-java-modules/core-java-serialization/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 core-java-serialization - core-java-serialization jar + core-java-serialization com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-streams-2/pom.xml b/core-java-modules/core-java-streams-2/pom.xml index d35dfa45b0..d61f94cbaa 100644 --- a/core-java-modules/core-java-streams-2/pom.xml +++ b/core-java-modules/core-java-streams-2/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 core-java-streams-2 - core-java-streams-2 jar + core-java-streams-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-streams-3/pom.xml b/core-java-modules/core-java-streams-3/pom.xml index 9c657119b5..95b1038653 100644 --- a/core-java-modules/core-java-streams-3/pom.xml +++ b/core-java-modules/core-java-streams-3/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 core-java-streams-3 - core-java-streams-3 jar + core-java-streams-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-streams-4/pom.xml b/core-java-modules/core-java-streams-4/pom.xml index 79b07d0482..972b47ce80 100644 --- a/core-java-modules/core-java-streams-4/pom.xml +++ b/core-java-modules/core-java-streams-4/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 core-java-streams-4 - core-java-streams-4 jar + core-java-streams-4 com.baeldung.core-java-modules @@ -73,11 +73,6 @@ commons-collections4 ${apache.commons.collection4.version} - - com.google.guava - guava - ${guava.version} - com.oath.cyclops cyclops diff --git a/core-java-modules/core-java-streams-5/pom.xml b/core-java-modules/core-java-streams-5/pom.xml index 3e439145cb..a991043bc2 100644 --- a/core-java-modules/core-java-streams-5/pom.xml +++ b/core-java-modules/core-java-streams-5/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 core-java-streams-5 - core-java-streams-5 jar + core-java-streams-5 com.baeldung.core-java-modules @@ -38,11 +38,7 @@ vavr ${vavr.version} - - com.google.guava - guava - ${guava.version} - + org.apache.commons commons-collections4 diff --git a/core-java-modules/core-java-streams-6/README.md b/core-java-modules/core-java-streams-6/README.md new file mode 100644 index 0000000000..415fa9b991 --- /dev/null +++ b/core-java-modules/core-java-streams-6/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [Java 8 Stream Operation on the Empty List](https://www.baeldung.com/java-empty-list-stream-ops) diff --git a/core-java-modules/core-java-streams-6/pom.xml b/core-java-modules/core-java-streams-6/pom.xml index c8cff002e4..5d13429c36 100644 --- a/core-java-modules/core-java-streams-6/pom.xml +++ b/core-java-modules/core-java-streams-6/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 core-java-streams-6 - core-java-streams-6 jar + core-java-streams-6 com.baeldung.core-java-modules @@ -43,11 +43,6 @@ vavr ${vavr.version} - - com.google.guava - guava - ${guava.version} - org.apache.commons commons-collections4 diff --git a/core-java-modules/core-java-streams-collect/pom.xml b/core-java-modules/core-java-streams-collect/pom.xml index ce35e66d91..a73789d499 100644 --- a/core-java-modules/core-java-streams-collect/pom.xml +++ b/core-java-modules/core-java-streams-collect/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 core-java-streams-collect - core-java-streams-collect jar + core-java-streams-collect com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-streams-maps/pom.xml b/core-java-modules/core-java-streams-maps/pom.xml index 0d231728c7..b04780b38b 100644 --- a/core-java-modules/core-java-streams-maps/pom.xml +++ b/core-java-modules/core-java-streams-maps/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 core-java-streams-maps - core-java-streams-maps jar + core-java-streams-maps com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-streams-simple/pom.xml b/core-java-modules/core-java-streams-simple/pom.xml index 30a5b3f568..a3855e20c5 100644 --- a/core-java-modules/core-java-streams-simple/pom.xml +++ b/core-java-modules/core-java-streams-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 core-java-streams-simple - core-java-streams-simple jar + core-java-streams-simple com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-streams/pom.xml b/core-java-modules/core-java-streams/pom.xml index e5e6adf3c0..5e1ad44c10 100644 --- a/core-java-modules/core-java-streams/pom.xml +++ b/core-java-modules/core-java-streams/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 core-java-streams - core-java-streams jar + core-java-streams com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-string-algorithms-2/pom.xml b/core-java-modules/core-java-string-algorithms-2/pom.xml index 3fdb022a4b..65400f017e 100644 --- a/core-java-modules/core-java-string-algorithms-2/pom.xml +++ b/core-java-modules/core-java-string-algorithms-2/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 core-java-string-algorithms-2 - core-java-string-algorithms-2 jar + core-java-string-algorithms-2 com.baeldung.core-java-modules 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 9d3b824df4..6e7264dcdd 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-string-algorithms-3 - core-java-string-algorithms-3 jar + core-java-string-algorithms-3 com.baeldung.core-java-modules @@ -55,7 +55,7 @@ - 1.7 + 1.8.0 5.1.1 1.10.0 diff --git a/core-java-modules/core-java-string-algorithms-4/pom.xml b/core-java-modules/core-java-string-algorithms-4/pom.xml index b374b48743..704c9f4018 100644 --- a/core-java-modules/core-java-string-algorithms-4/pom.xml +++ b/core-java-modules/core-java-string-algorithms-4/pom.xml @@ -3,12 +3,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-string-algorithms-4 - core-java-string-algorithms-4 jar + core-java-string-algorithms-4 com.baeldung.core-java-modules core-java-modules 0.0.1-SNAPSHOT + \ No newline at end of file diff --git a/core-java-modules/core-java-string-algorithms/pom.xml b/core-java-modules/core-java-string-algorithms/pom.xml index 10d28feb2f..1666d64ed3 100644 --- a/core-java-modules/core-java-string-algorithms/pom.xml +++ b/core-java-modules/core-java-string-algorithms/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 core-java-string-algorithms - core-java-string-algorithms jar + core-java-string-algorithms com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-string-apis-2/pom.xml b/core-java-modules/core-java-string-apis-2/pom.xml index c77ea7c64b..9375b92086 100644 --- a/core-java-modules/core-java-string-apis-2/pom.xml +++ b/core-java-modules/core-java-string-apis-2/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 core-java-string-apis-2 - core-java-string-apis-2 jar + core-java-string-apis-2 com.baeldung.core-java-modules @@ -14,11 +14,6 @@ - - com.google.guava - guava - ${guava.version} - org.apache.commons commons-lang3 diff --git a/core-java-modules/core-java-string-apis/pom.xml b/core-java-modules/core-java-string-apis/pom.xml index 5d7737228c..743c331ad2 100644 --- a/core-java-modules/core-java-string-apis/pom.xml +++ b/core-java-modules/core-java-string-apis/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 core-java-string-apis - core-java-string-apis jar + core-java-string-apis com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-string-conversions-2/pom.xml b/core-java-modules/core-java-string-conversions-2/pom.xml index 90463271b8..8a3719dc31 100644 --- a/core-java-modules/core-java-string-conversions-2/pom.xml +++ b/core-java-modules/core-java-string-conversions-2/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 core-java-string-conversions-2 - core-java-string-conversions-2 jar + core-java-string-conversions-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-string-conversions-3/README.md b/core-java-modules/core-java-string-conversions-3/README.md index 144773b7c3..5ef055b39b 100644 --- a/core-java-modules/core-java-string-conversions-3/README.md +++ b/core-java-modules/core-java-string-conversions-3/README.md @@ -3,6 +3,6 @@ - [Convert String to Int Using Encapsulation](https://www.baeldung.com/java-encapsulation-convert-string-to-int) - [HashMap with Multiple Values for the Same Key](https://www.baeldung.com/java-hashmap-multiple-values-per-key) - [Split Java String Into Key-Value Pairs](https://www.baeldung.com/java-split-string-map) -- [How to Center Text Output in Java](https://www.baeldung.com/java-center-text-output) - [How to Convert an Object to String](https://www.baeldung.com/java-object-string-representation) - [Convert String to long or Long in Java](https://www.baeldung.com/java-convert-string-long) +- [Convert a String to a List of Characters in Java](https://www.baeldung.com/java-convert-string-list-characters) diff --git a/core-java-modules/core-java-string-conversions-3/pom.xml b/core-java-modules/core-java-string-conversions-3/pom.xml index b494a03fa7..3ff28e7c7c 100644 --- a/core-java-modules/core-java-string-conversions-3/pom.xml +++ b/core-java-modules/core-java-string-conversions-3/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 core-java-string-conversions-3 - core-java-string-conversions-3 jar + core-java-string-conversions-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-string-conversions/pom.xml b/core-java-modules/core-java-string-conversions/pom.xml index b87431cd0b..676eec0c65 100644 --- a/core-java-modules/core-java-string-conversions/pom.xml +++ b/core-java-modules/core-java-string-conversions/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 core-java-string-conversions - core-java-string-conversions jar + core-java-string-conversions com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml index 76f21aa726..33ace9cb0a 100644 --- a/core-java-modules/core-java-string-operations-2/pom.xml +++ b/core-java-modules/core-java-string-operations-2/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 core-java-string-operations-2 - core-java-string-operations-2 jar + core-java-string-operations-2 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-string-operations-3/pom.xml b/core-java-modules/core-java-string-operations-3/pom.xml index a82a0d5b11..94fef545e9 100644 --- a/core-java-modules/core-java-string-operations-3/pom.xml +++ b/core-java-modules/core-java-string-operations-3/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 core-java-string-operations-3 - core-java-string-operations-3 jar + core-java-string-operations-3 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-string-operations-4/pom.xml b/core-java-modules/core-java-string-operations-4/pom.xml index 2537deb48b..a00d03670a 100644 --- a/core-java-modules/core-java-string-operations-4/pom.xml +++ b/core-java-modules/core-java-string-operations-4/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 core-java-string-operations-4 - core-java-string-operations-4 jar + core-java-string-operations-4 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-string-operations-5/pom.xml b/core-java-modules/core-java-string-operations-5/pom.xml index 768a04ba23..17a3c812ab 100644 --- a/core-java-modules/core-java-string-operations-5/pom.xml +++ b/core-java-modules/core-java-string-operations-5/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 core-java-string-operations-5 - core-java-string-operations-5 jar + core-java-string-operations-5 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-string-operations-6/pom.xml b/core-java-modules/core-java-string-operations-6/pom.xml index 2cd7c6ad3e..1df0c9a188 100644 --- a/core-java-modules/core-java-string-operations-6/pom.xml +++ b/core-java-modules/core-java-string-operations-6/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 core-java-string-operations-6 - core-java-string-operations-6 jar + core-java-string-operations-6 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-string-operations-7/pom.xml b/core-java-modules/core-java-string-operations-7/pom.xml index eb607fb901..19d9b39e3f 100644 --- a/core-java-modules/core-java-string-operations-7/pom.xml +++ b/core-java-modules/core-java-string-operations-7/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 core-java-string-operations-7 - core-java-string-operations-7 jar + core-java-string-operations-7 com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-string-operations-8/README.md b/core-java-modules/core-java-string-operations-8/README.md index 4847d4efc8..22407a5961 100644 --- a/core-java-modules/core-java-string-operations-8/README.md +++ b/core-java-modules/core-java-string-operations-8/README.md @@ -5,3 +5,4 @@ - [Find an Unique Email Address in a List](https://www.baeldung.com/java-find-unique-email-address) - [Get First n Characters in a String in Java](https://www.baeldung.com/get-first-n-characters-in-a-string-in-java) - [Remove Only Trailing Spaces or Whitespace From a String in Java](https://www.baeldung.com/java-string-remove-only-trailing-whitespace) +- [Get the Initials of a Name in Java](https://www.baeldung.com/java-shorten-name-initials) diff --git a/core-java-modules/core-java-string-operations-8/pom.xml b/core-java-modules/core-java-string-operations-8/pom.xml index 4e155a9851..0b6cdc6b2f 100644 --- a/core-java-modules/core-java-string-operations-8/pom.xml +++ b/core-java-modules/core-java-string-operations-8/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 core-java-string-operations-8 - core-java-string-operations-8 jar + core-java-string-operations-8 com.baeldung.core-java-modules @@ -20,9 +20,10 @@ ${apache.commons.lang3.version} - com.google.guava - guava - ${guava.version} + org.apache.storm + storm-core + 1.2.2 + test diff --git a/core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/EOLNormalizer/EOLNormalizerUnitTest.java b/core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/EOLNormalizer/EOLNormalizerUnitTest.java new file mode 100644 index 0000000000..caeea60da1 --- /dev/null +++ b/core-java-modules/core-java-string-operations-8/src/test/java/com/baeldung/EOLNormalizer/EOLNormalizerUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.EOLNormalizer; + +import org.apache.storm.shade.org.apache.commons.lang.StringUtils; +import org.junit.Test; + +import java.util.Arrays; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; + +public class EOLNormalizerUnitTest { + String originalText = "This is a text\rwith different\r\nEOL characters\n"; + String expectedText = "This is a text" + System.getProperty("line.separator") + "with different" + System.getProperty("line.separator") + + "EOL characters" + System.getProperty("line.separator"); + + @Test + public void givenText_whenUsingStringReplace_thenEOLNormalized() { + String normalizedText = originalText.replaceAll("\\r\\n|\\r|\\n", System.getProperty("line.separator")); + assertEquals(expectedText, normalizedText); + } + + @Test + public void givenText_whenUsingStringUtils_thenEOLNormalized() { + String normalizedText = StringUtils.replaceEach(originalText, new String[]{"\r\n", "\r", "\n"}, new String[]{System.getProperty("line.separator"), System.getProperty("line.separator"), System.getProperty("line.separator")}); + assertEquals(expectedText, normalizedText); + } + + @Test + public void givenText_whenUsingStreamAPI_thenEOLNormalized() { + String normalizedText = Arrays.stream(originalText.split("\\r\\n|\\r|\\n")) + .collect(Collectors.joining(System.getProperty("line.separator"))).trim(); + assertEquals(expectedText.trim(), normalizedText); + } +} diff --git a/core-java-modules/core-java-string-operations/pom.xml b/core-java-modules/core-java-string-operations/pom.xml index 7b91600a6b..b34c0081c3 100644 --- a/core-java-modules/core-java-string-operations/pom.xml +++ b/core-java-modules/core-java-string-operations/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 core-java-string-operations - core-java-string-operations jar + core-java-string-operations com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-strings/pom.xml b/core-java-modules/core-java-strings/pom.xml index b43e7bfe73..c52d293829 100644 --- a/core-java-modules/core-java-strings/pom.xml +++ b/core-java-modules/core-java-strings/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 core-java-strings - core-java-strings jar + core-java-strings com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-sun/pom.xml b/core-java-modules/core-java-sun/pom.xml index 7f1517e246..03a8cff885 100644 --- a/core-java-modules/core-java-sun/pom.xml +++ b/core-java-modules/core-java-sun/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 core-java-sun - core-java-sun jar + core-java-sun com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-swing/pom.xml b/core-java-modules/core-java-swing/pom.xml index b46fe0f65a..462e31e439 100644 --- a/core-java-modules/core-java-swing/pom.xml +++ b/core-java-modules/core-java-swing/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 core-java-swing - core-java-swing jar + core-java-swing com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-time-measurements/pom.xml b/core-java-modules/core-java-time-measurements/pom.xml index 2dd713efe8..fc45017dcd 100644 --- a/core-java-modules/core-java-time-measurements/pom.xml +++ b/core-java-modules/core-java-time-measurements/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 core-java-time-measurements - core-java-time-measurements jar + core-java-time-measurements com.baeldung.core-java-modules diff --git a/core-java-modules/core-java-uuid/pom.xml b/core-java-modules/core-java-uuid/pom.xml index 76154033c2..4ecb42952d 100644 --- a/core-java-modules/core-java-uuid/pom.xml +++ b/core-java-modules/core-java-uuid/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 core-java-uuid - core-java-uuid jar + core-java-uuid com.baeldung.core-java-modules diff --git a/core-java-modules/java-rmi/pom.xml b/core-java-modules/java-rmi/pom.xml index aa864b49c7..6d6593bb0b 100644 --- a/core-java-modules/java-rmi/pom.xml +++ b/core-java-modules/java-rmi/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.rmi java-rmi - java-rmi jar + java-rmi com.baeldung.core-java-modules diff --git a/core-java-modules/java-spi/exchange-rate-api/pom.xml b/core-java-modules/java-spi/exchange-rate-api/pom.xml index bb22c63de1..9e8abbc873 100644 --- a/core-java-modules/java-spi/exchange-rate-api/pom.xml +++ b/core-java-modules/java-spi/exchange-rate-api/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung exchange-rate-api - exchange-rate-api jar + exchange-rate-api com.baeldung diff --git a/core-java-modules/java-spi/exchange-rate-app/pom.xml b/core-java-modules/java-spi/exchange-rate-app/pom.xml index fbf87eb026..8b8e7f9c42 100644 --- a/core-java-modules/java-spi/exchange-rate-app/pom.xml +++ b/core-java-modules/java-spi/exchange-rate-app/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 exchange-rate-app - exchange-rate-app jar + exchange-rate-app com.baeldung diff --git a/core-java-modules/java-spi/exchange-rate-impl/pom.xml b/core-java-modules/java-spi/exchange-rate-impl/pom.xml index 7824bbc9e5..8a1c320dd9 100644 --- a/core-java-modules/java-spi/exchange-rate-impl/pom.xml +++ b/core-java-modules/java-spi/exchange-rate-impl/pom.xml @@ -5,8 +5,8 @@ 4.0.0 exchange-rate-impl com.baeldung - exchange-rate-impl jar + exchange-rate-impl com.baeldung diff --git a/core-java-modules/java-spi/pom.xml b/core-java-modules/java-spi/pom.xml index 837700103e..97aee9838f 100644 --- a/core-java-modules/java-spi/pom.xml +++ b/core-java-modules/java-spi/pom.xml @@ -5,9 +5,9 @@ 4.0.0 com.baeldung java-spi - java-spi 1.0.0-SNAPSHOT pom + java-spi com.baeldung.core-java-modules diff --git a/core-java-modules/java-websocket/pom.xml b/core-java-modules/java-websocket/pom.xml index 8d8e57b765..616f633960 100644 --- a/core-java-modules/java-websocket/pom.xml +++ b/core-java-modules/java-websocket/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 java-websocket - java-websocket war + java-websocket com.baeldung.core-java-modules diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 3d26d51a6a..85df51457c 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -5,9 +5,9 @@ 4.0.0 com.baeldung.core-java-modules core-java-modules - core-java-modules 0.0.1-SNAPSHOT pom + core-java-modules com.baeldung @@ -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 @@ -243,6 +244,7 @@ 17 17 + 20240303 diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml index 115ba7565c..1b5c3e6238 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -6,8 +6,8 @@ com.baeldung.pmd custom-pmd 0.0.1 - custom-pmd jar + custom-pmd com.baeldung 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/multi-module-caching/runner-module/pom.xml b/docker-modules/docker-caching/multi-module-caching/runner-module/pom.xml index e608706864..8d6bba9183 100644 --- a/docker-modules/docker-caching/multi-module-caching/runner-module/pom.xml +++ b/docker-modules/docker-caching/multi-module-caching/runner-module/pom.xml @@ -24,7 +24,7 @@ org.apache.maven.plugins maven-assembly-plugin - 3.3.0 + ${maven-assembly-plugin.version} jar-with-dependencies @@ -50,6 +50,7 @@ + 3.3.0 8 8 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-caching/single-module-caching/pom.xml b/docker-modules/docker-caching/single-module-caching/pom.xml index 1e90c7130e..3360360742 100644 --- a/docker-modules/docker-caching/single-module-caching/pom.xml +++ b/docker-modules/docker-caching/single-module-caching/pom.xml @@ -20,7 +20,7 @@ org.apache.maven.plugins maven-assembly-plugin - 3.3.0 + ${maven-assembly-plugin.version} jar-with-dependencies @@ -50,6 +50,7 @@ 8 UTF-8 33.0.0-jre + 3.3.0 \ No newline at end of file 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/docker-modules/docker-compose/README.md b/docker-modules/docker-compose/README.md index 4631630e6a..603debe6a1 100644 --- a/docker-modules/docker-compose/README.md +++ b/docker-modules/docker-compose/README.md @@ -5,6 +5,6 @@ - [Communication Between Multiple Docker Compose Projects](https://www.baeldung.com/ops/docker-compose-communication) - [Difference Between links and depends_on in Docker Compose](https://www.baeldung.com/ops/docker-compose-links-depends-on) - [Mounting Multiple Volumes on a Docker Container](https://www.baeldung.com/ops/docker-mounting-multiple-volumes) -- [Rebuild Docker Container in Docker Compose](https://www.baeldung.com/rebuild-docker-container-compose) +- [Rebuild Docker Container in Docker Compose](https://www.baeldung.com/ops/rebuild-docker-container-compose) - [Assign Static IP to Docker Container and Docker-Compose](https://www.baeldung.com/ops/docker-assign-static-ip-container) - [Exclude a Sub-Folder When Adding a Volume to Docker](https://www.baeldung.com/ops/docker-exclude-sub-folder-when-adding-volume) diff --git a/drools/pom.xml b/drools/pom.xml index 12aaf1318a..cb4f20d397 100644 --- a/drools/pom.xml +++ b/drools/pom.xml @@ -16,50 +16,50 @@ org.apache.httpcomponents httpcore - ${http-component-version} + ${httpcore.version} org.kie kie-ci - ${drools-version} + ${drools.version} org.drools drools-decisiontables - ${drools-version} + ${drools.version} org.drools drools-core - ${drools-version} + ${drools.version} org.drools drools-compiler - ${drools-version} + ${drools.version} org.apache.poi poi - ${apache-poi-version} + ${poi.version} org.apache.poi poi-ooxml - ${apache-poi-version} + ${poi.version} org.optaplanner optaplanner-core - ${opta-planner-version} + ${optaplanner-core.version} - 4.4.16 - 8.32.0.Final - 5.2.3 - 8.32.0.Final + 4.4.16 + 8.32.0.Final + 5.2.3 + 8.32.0.Final 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 e0488bf0b1..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 @@ -117,12 +117,7 @@ ${jstl.version} runtime - - - com.google.guava - guava - ${guava.version} - + diff --git a/jackson-modules/jackson-annotations/pom.xml b/jackson-modules/jackson-annotations/pom.xml index 59d7d3d197..158b5b189a 100644 --- a/jackson-modules/jackson-annotations/pom.xml +++ b/jackson-modules/jackson-annotations/pom.xml @@ -59,7 +59,7 @@ 2.1.214 - 5.3.2 + 5.4.0 2.5.0 diff --git a/jackson-modules/jackson-conversions-2/pom.xml b/jackson-modules/jackson-conversions-2/pom.xml index 457045b460..d87d4334f3 100644 --- a/jackson-modules/jackson-conversions-2/pom.xml +++ b/jackson-modules/jackson-conversions-2/pom.xml @@ -56,7 +56,7 @@ 5.13.2 - 20220320 + 20240303 \ No newline at end of file diff --git a/jackson-modules/jackson-conversions/pom.xml b/jackson-modules/jackson-conversions/pom.xml index e0990ed34f..6d6af97785 100644 --- a/jackson-modules/jackson-conversions/pom.xml +++ b/jackson-modules/jackson-conversions/pom.xml @@ -28,6 +28,11 @@ jackson-databind ${jackson.version} + + com.google.guava + guava + ${guava.version} + diff --git a/jackson-modules/jackson-core/pom.xml b/jackson-modules/jackson-core/pom.xml index 4eccd4d8f8..9fd0cc4ac4 100644 --- a/jackson-modules/jackson-core/pom.xml +++ b/jackson-modules/jackson-core/pom.xml @@ -61,7 +61,7 @@ - 3.1.1 + 5.4.0 \ No newline at end of file diff --git a/jackson-modules/jackson-custom-conversions/pom.xml b/jackson-modules/jackson-custom-conversions/pom.xml index 31e460511a..c3ae4ae675 100644 --- a/jackson-modules/jackson-custom-conversions/pom.xml +++ b/jackson-modules/jackson-custom-conversions/pom.xml @@ -28,6 +28,11 @@ jackson-core ${jackson.version} + + com.google.guava + guava + ${guava.version} + 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 e80340a4b9..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 @@ -31,11 +31,6 @@ com.fasterxml.jackson.dataformat jackson-dataformat-xml ${jackson.version} - - - com.google.guava - guava - ${guava.version} commons-io 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-numbers-2/src/main/java/com/baeldung/rbg/Rgb.java b/java-numbers-2/src/main/java/com/baeldung/rbg/Rgb.java new file mode 100644 index 0000000000..536dbdd2eb --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/rbg/Rgb.java @@ -0,0 +1,46 @@ +package com.baeldung.rbg; + +import java.util.Objects; + +public class Rgb { + private int alpha; + private int red; + private int green; + private int blue; + + public Rgb(int alpha, int red, int green, int blue) { + this.alpha = alpha; + this.red = red; + this.green = green; + this.blue = blue; + } + + public int getAlpha() { + return alpha; + } + + public int getRed() { + return red; + } + + public int getGreen() { + return green; + } + + public int getBlue() { + return blue; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Rgb rgb = (Rgb) o; + return alpha == rgb.alpha && red == rgb.red && green == rgb.green && blue == rgb.blue; + } + + @Override + public int hashCode() { + return Objects.hash(alpha, red, green, blue); + } +} diff --git a/java-numbers-2/src/main/java/com/baeldung/rbg/RgbConversions.java b/java-numbers-2/src/main/java/com/baeldung/rbg/RgbConversions.java new file mode 100644 index 0000000000..fbf7615378 --- /dev/null +++ b/java-numbers-2/src/main/java/com/baeldung/rbg/RgbConversions.java @@ -0,0 +1,31 @@ +package com.baeldung.rbg; + +public class RgbConversions { + + public static int rgbToInt(int alpha, int red, int green, int blue) { + alpha = clamp(alpha, 0, 255); + red = clamp(red, 0, 255); + green = clamp(green, 0, 255); + blue = clamp(blue, 0, 255); + + return (alpha << 24) | (red << 16) | (green << 8) | blue; + } + + public static int rgbToInt(Rgb rgb) { + return rgbToInt(rgb.getAlpha(), rgb.getRed(), rgb.getGreen(), rgb.getBlue()); + } + + public static Rgb intToRgb(int argb) { + int alpha = (argb >> 24) & 0xFF; + int red = (argb >> 16) & 0xFF; + int green = (argb >> 8) & 0xFF; + int blue = argb & 0xFF; + + return new Rgb(alpha, red, green, blue); + } + + private static int clamp(int value, int min, int max) { + return Math.max(min, Math.min(max, value)); + } +} + diff --git a/java-numbers-2/src/test/java/com/baeldung/rgb/RgbConversionUnitTest.java b/java-numbers-2/src/test/java/com/baeldung/rgb/RgbConversionUnitTest.java new file mode 100644 index 0000000000..6a52ab1d22 --- /dev/null +++ b/java-numbers-2/src/test/java/com/baeldung/rgb/RgbConversionUnitTest.java @@ -0,0 +1,118 @@ +package com.baeldung.rgb; + +import com.baeldung.rbg.Rgb; +import com.baeldung.rbg.RgbConversions; +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.assertEquals; + +public class RgbConversionUnitTest { + + @Test + public void whenBasicPackingAndUnpackingRgb_thenReturnInitialComponentsValues() { + int alpha = 255; + int red = 255; + int green = 0; + int blue = 0; + + int rgb = (alpha << 24) | (red << 16) | (green << 8) | blue; + + assertEquals(rgb, 0xFFFF0000); + + int alphaReconstructed = (rgb >> 24) & 0xFF; + int redReconstructed = (rgb >> 16) & 0xFF; + int greenReconstructed = (rgb >> 8) & 0xFF; + int blueReconstructed = rgb & 0xFF; + + assertEquals(alphaReconstructed, alpha); + assertEquals(redReconstructed, red); + assertEquals(greenReconstructed, green); + assertEquals(blueReconstructed, blue); + } + + @Test + public void whenRgbaToIntWithoutClamping_ReturnIntegerRepresentations() { + // Fully opaque red + assertEquals(0xFFFF0000, RgbConversions.rgbToInt(255, 255, 0, 0)); + // Fully transparent blue + assertEquals(0x000000FF, RgbConversions.rgbToInt(0, 0, 0, 255)); + // 50% transparent green + assertEquals(0x8000FF00, RgbConversions.rgbToInt(128, 0, 255, 0)); + } + + @Test + public void whenRgbaToIntWithClamping_ReturnIntegerRepresentations() { + // Clamping for values below 0 + assertEquals(0x00000000, RgbConversions.rgbToInt(-1, -1, -1, -1)); + // Clamping for values above 255 + assertEquals(0xFFFFFFFF, RgbConversions.rgbToInt(256, 256, 256, 256)); + } + + @Test + public void whenRgbaToIntBoundary_ReturnIntegerRepresentations() { + // Boundary values for each color component including alpha + assertEquals(0xFF000000, RgbConversions.rgbToInt(255, 0, 0, 0)); // Opaque black + assertEquals(0x00FFFFFF, RgbConversions.rgbToInt(0, 255, 255, 255)); // Transparent white + } + + @Test + public void whenRgbaToIntAndIntToRgb_ReturnTheSameValues() { + Rgb rgb = new Rgb(0, 125, 125, 100); + assertEquals(rgb, RgbConversions.intToRgb(RgbConversions.rgbToInt(rgb))); + } + + @Test + public void whenBrightnessAdjustment_ReturnChangedRgbIntegerValue() { + float scale = 0.8f; // darken by 20% + + // initial values + int alpha = 0; + int red = 100; + int green = 255; + int blue = 100; + + + int adjustedRed = (int)(red * scale); + int adjustedGreen = (int)(green * scale); + int adjustedBlue = (int)(blue * scale); + + int newArgb = (alpha << 24) | (adjustedRed << 16) | (adjustedGreen << 8) | adjustedBlue; + + assertEquals(newArgb, 0x50CC50); + } + + @Test + public void whenGrayscaleConversion_ReturnChangedRgbIntegerValue() { + float scale = 0.8f; // darken by 20% + + // initial values + int alpha = 0; + int red = 100; + int green = 255; + int blue = 100; + + int average = (int)(red * 0.299 + green * 0.587 + blue * 0.114); + int grayscaleArgb = (alpha << 24) | (average << 16) | (average << 8) | average; + + assertEquals(grayscaleArgb, 0xBEBEBE); + } + + @Test + public void whenInversion_ReturnChangedRgbIntegerValue() { + float scale = 0.8f; // darken by 20% + + // initial values + int alpha = 0; + int red = 100; + int green = 255; + int blue = 100; + + red = 255 - red; + green = 255 - green; + blue = 255 - blue; + + int invertedArgb = (alpha << 24) | (red << 16) | (green << 8) | blue; + + assertEquals(invertedArgb, 0x9B009B); + } +} 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 ]](../lombok-2) \ No newline at end of file +- More articles: [[next -->]](../lombok-2) diff --git a/lombok-modules/pom.xml b/lombok-modules/pom.xml index 620f0bf74c..fd5af67a22 100644 --- a/lombok-modules/pom.xml +++ b/lombok-modules/pom.xml @@ -5,8 +5,8 @@ 4.0.0 lombok-modules 1.0.0-SNAPSHOT - lombok-modules pom + lombok-modules com.baeldung diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml index 5332bcaeb3..277e4401d7 100644 --- a/mapstruct/pom.xml +++ b/mapstruct/pom.xml @@ -5,8 +5,8 @@ 4.0.0 mapstruct 1.0 - mapstruct jar + mapstruct com.baeldung diff --git a/maven-modules/animal-sniffer-mvn-plugin/pom.xml b/maven-modules/animal-sniffer-mvn-plugin/pom.xml index 0b508651af..04dbd722bb 100644 --- a/maven-modules/animal-sniffer-mvn-plugin/pom.xml +++ b/maven-modules/animal-sniffer-mvn-plugin/pom.xml @@ -5,8 +5,8 @@ 4.0.0 animal-sniffer-mvn-plugin 1.0-SNAPSHOT - animal-sniffer-mvn-plugin jar + animal-sniffer-mvn-plugin http://maven.apache.org diff --git a/maven-modules/dependency-exclusion/core-java-exclusions/pom.xml b/maven-modules/dependency-exclusion/core-java-exclusions/pom.xml index 9fd09f83e2..98fb78ddf3 100644 --- a/maven-modules/dependency-exclusion/core-java-exclusions/pom.xml +++ b/maven-modules/dependency-exclusion/core-java-exclusions/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 core-java-exclusions - core-java-exclusions jar + core-java-exclusions com.baeldung.dependency-exclusion @@ -19,7 +19,6 @@ junit test - diff --git a/maven-modules/dependency-exclusion/pom.xml b/maven-modules/dependency-exclusion/pom.xml index 93f7f3530e..2564058482 100644 --- a/maven-modules/dependency-exclusion/pom.xml +++ b/maven-modules/dependency-exclusion/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.dependency-exclusion dependency-exclusion - dependency-exclusion pom + dependency-exclusion com.baeldung @@ -35,10 +35,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.7.0 - 1.8 - 1.8 -parameters diff --git a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-aggregate-report/pom.xml b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-aggregate-report/pom.xml index 627a9f3206..052b07e8ea 100644 --- a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-aggregate-report/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-aggregate-report/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.jacoco-coverage-aggregation jacoco-coverage-aggregate-report - jacoco-coverage-aggregate-report pom + jacoco-coverage-aggregate-report com.baeldung @@ -17,12 +17,12 @@ com.baeldung.jacoco-coverage-aggregation - services + jacoco-coverage-services-example ${project.parent.version} com.baeldung.jacoco-coverage-aggregation - controllers + jacoco-coverage-controllers-example ${project.parent.version} diff --git a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/pom.xml b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/pom.xml index 886e931224..90c3980e63 100644 --- a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.jacoco-coverage-aggregation jacoco-coverage-controllers-example - jacoco-coverage-controllers-example jar + jacoco-coverage-controllers-example com.baeldung @@ -17,7 +17,7 @@ com.baeldung.jacoco-coverage-aggregation - services + jacoco-coverage-services-example ${project.parent.version} diff --git a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml index 223689f8ff..048511c1ad 100644 --- a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.jacoco-coverage-aggregation jacoco-coverage-services-example - jacoco-coverage-services-example jar + jacoco-coverage-services-example com.baeldung @@ -33,7 +33,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.1.2 + ${maven-surefire-plugin.version} **/*Test.java @@ -46,6 +46,7 @@ 5.9.2 6.0.11 + 3.1.2 \ No newline at end of file diff --git a/maven-modules/jacoco-coverage-aggregation/pom.xml b/maven-modules/jacoco-coverage-aggregation/pom.xml index 6d1aab3c3d..bc70c60b50 100644 --- a/maven-modules/jacoco-coverage-aggregation/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/pom.xml @@ -3,17 +3,15 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung jacoco-coverage-aggregation 1.0 - jacoco-coverage-aggregation pom + jacoco-coverage-aggregation com.baeldung - parent-modules - 1.0.0-SNAPSHOT - ../../ + maven-modules + 0.0.1-SNAPSHOT diff --git a/maven-modules/maven-archetype/pom.xml b/maven-modules/maven-archetype/pom.xml index 04247f622c..5fd0b0cbb9 100644 --- a/maven-modules/maven-archetype/pom.xml +++ b/maven-modules/maven-archetype/pom.xml @@ -6,8 +6,8 @@ com.baeldung.archetypes maven-archetype 1.0-SNAPSHOT - maven-archetype maven-archetype + maven-archetype Archetype used to generate rest application based on jaxrs 2.1 @@ -21,8 +21,6 @@ - 1.8 - 1.8 3.0.1 diff --git a/maven-modules/maven-build-lifecycle/pom.xml b/maven-modules/maven-build-lifecycle/pom.xml index 5cfb854200..f9025a9c46 100644 --- a/maven-modules/maven-build-lifecycle/pom.xml +++ b/maven-modules/maven-build-lifecycle/pom.xml @@ -1,24 +1,16 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + maven-build-lifecycle + com.baeldung maven-modules 0.0.1-SNAPSHOT - maven-build-lifecycle - - - 11 - 11 - 3.1.2 - 3.1.2 - 5.3.1 - UTF-8 - @@ -52,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-builder-plugin/pom.xml b/maven-modules/maven-builder-plugin/pom.xml index 338aafe85d..75211fda1a 100644 --- a/maven-modules/maven-builder-plugin/pom.xml +++ b/maven-modules/maven-builder-plugin/pom.xml @@ -7,6 +7,12 @@ maven-builder-plugin 1.0-SNAPSHOT + + com.baeldung + maven-modules + 0.0.1-SNAPSHOT + + @@ -32,10 +38,7 @@ - 3.2.0 - 1.8 - 1.8 - UTF-8 + 3.4.0 \ No newline at end of file diff --git a/maven-modules/maven-classifier/maven-classifier-example-consumer/pom.xml b/maven-modules/maven-classifier/maven-classifier-example-consumer/pom.xml index b64fe94e46..cb0583d6a0 100644 --- a/maven-modules/maven-classifier/maven-classifier-example-consumer/pom.xml +++ b/maven-modules/maven-classifier/maven-classifier-example-consumer/pom.xml @@ -45,9 +45,4 @@ - - 8 - 8 - - \ No newline at end of file diff --git a/maven-modules/maven-classifier/pom.xml b/maven-modules/maven-classifier/pom.xml index bcbbcdd49e..a61cd8b0c5 100644 --- a/maven-modules/maven-classifier/pom.xml +++ b/maven-modules/maven-classifier/pom.xml @@ -18,9 +18,4 @@ maven-classifier-example-provider - - 8 - 8 - - \ No newline at end of file diff --git a/maven-modules/maven-copy-files/pom.xml b/maven-modules/maven-copy-files/pom.xml index 57d0ddf647..90b40171a7 100644 --- a/maven-modules/maven-copy-files/pom.xml +++ b/maven-modules/maven-copy-files/pom.xml @@ -3,11 +3,10 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung maven-copy-files 1.0-SNAPSHOT - maven-copy-files pom + maven-copy-files http://www.example.com @@ -78,10 +77,4 @@ - - UTF-8 - 1.7 - 1.7 - - \ No newline at end of file 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 9648464102..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 @@ -56,6 +56,7 @@ org.apache.maven.plugins maven-plugin-plugin + ${maven-compiler-plugin.version} @@ -68,12 +69,13 @@ - 1.8 - 1.8 + 3.12.1 + 17 + 17 3.6.2 3.6.0 2.2.1 - 3.6.0 + 3.11.0 3.8.2 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-exec-plugin/pom.xml b/maven-modules/maven-exec-plugin/pom.xml index fc4d2d79f1..cddc693bf3 100644 --- a/maven-modules/maven-exec-plugin/pom.xml +++ b/maven-modules/maven-exec-plugin/pom.xml @@ -3,11 +3,16 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung maven-exec-plugin 0.0.1-SNAPSHOT maven-exec-plugin + + com.baeldung + maven-modules + 0.0.1-SNAPSHOT + + org.apache.maven.shared @@ -37,6 +42,17 @@ ${junit.jupiter.version} test + + org.junit.vintage + junit-vintage-engine + ${junit.jupiter.version} + + + org.junit.jupiter + junit-jupiter-params + ${junit.jupiter.version} + test + diff --git a/maven-modules/maven-generate-war/pom.xml b/maven-modules/maven-generate-war/pom.xml index 1d7c79aa81..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 @@ -59,10 +59,6 @@ org.apache.maven.plugins maven-compiler-plugin - - ${maven.compiler.source.version} - ${maven.compiler.target.version} - diff --git a/maven-modules/maven-integration-test/pom.xml b/maven-modules/maven-integration-test/pom.xml index 7c604b121b..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 @@ -273,7 +273,7 @@ 1.1 3.0.0 3.0.0 - 9.4.11.v20180605 + 10.0.20 2.27 diff --git a/maven-modules/maven-multi-source/pom.xml b/maven-modules/maven-multi-source/pom.xml index 96b390d75a..7de02c17de 100644 --- a/maven-modules/maven-multi-source/pom.xml +++ b/maven-modules/maven-multi-source/pom.xml @@ -20,8 +20,6 @@ maven-compiler-plugin ${maven-compiler-plugin.version} - ${java.version} - ${java.version} -Xlint:unchecked diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml index 28ea8b6359..7259ce4d20 100644 --- a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml @@ -3,7 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung.maven-parent-pom-resolution empty-phase 1.0.0-SNAPSHOT pom diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/phase-none/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/phase-none/pom.xml index 8870f28fd2..3da1de339e 100644 --- a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/phase-none/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/phase-none/pom.xml @@ -3,7 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung.maven-parent-pom-resolution phase-none 1.0.0-SNAPSHOT pom diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/pom.xml index e3ff22aaf7..fd62bf84c7 100644 --- a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/pom.xml @@ -3,7 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung.maven-parent-pom-resolution plugin-enabled 1.0.0-SNAPSHOT pom diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/pom.xml index 4d16a94838..92e5da680a 100644 --- a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/pom.xml @@ -26,7 +26,7 @@ org.apache.maven.plugins maven-enforcer-plugin - 3.0.0 + ${maven-enforcer-plugin.version} enforce-file-exists @@ -49,7 +49,7 @@ - UTF-8 + 3.0.0 \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/skip-parameter/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/skip-parameter/pom.xml index 31415bec24..57a608b043 100644 --- a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/skip-parameter/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/skip-parameter/pom.xml @@ -3,7 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung.maven-parent-pom-resolution skip-parameter 1.0.0-SNAPSHOT pom diff --git a/maven-modules/maven-plugins/pom.xml b/maven-modules/maven-plugins/pom.xml index 4aa295c8a8..e3d67d65ff 100644 --- a/maven-modules/maven-plugins/pom.xml +++ b/maven-modules/maven-plugins/pom.xml @@ -43,8 +43,6 @@ maven-compiler-plugin ${maven.compiler.version} - ${java.version} - ${java.version} -Xlint:unchecked 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-printing-plugins/pom.xml b/maven-modules/maven-printing-plugins/pom.xml index 683a99fef7..264185413a 100644 --- a/maven-modules/maven-printing-plugins/pom.xml +++ b/maven-modules/maven-printing-plugins/pom.xml @@ -17,7 +17,7 @@ maven-antrun-plugin - 3.0.0 + ${maven-antrun-plugin.version} antrun-plugin @@ -41,7 +41,7 @@ com.github.ekryd.echo-maven-plugin echo-maven-plugin - 1.3.2 + ${echo-maven-plugin.version} echo-maven-plugin-1 @@ -66,7 +66,7 @@ org.codehaus.gmaven groovy-maven-plugin - 2.1.1 + ${groovy-maven-plugin.version} validate @@ -87,4 +87,10 @@ + + 3.0.0 + 1.3.2 + 2.1.1 + + \ No newline at end of file diff --git a/maven-modules/maven-properties/pom.xml b/maven-modules/maven-properties/pom.xml index f28c353074..f3ed102f4d 100644 --- a/maven-modules/maven-properties/pom.xml +++ b/maven-modules/maven-properties/pom.xml @@ -61,7 +61,6 @@ - UTF-8 UTF-8 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/maven-modules/multimodulemavenproject/maven-userdaomodule/pom.xml b/maven-modules/multimodulemavenproject/maven-userdaomodule/pom.xml index c7ceada17d..d5fe513e09 100644 --- a/maven-modules/multimodulemavenproject/maven-userdaomodule/pom.xml +++ b/maven-modules/multimodulemavenproject/maven-userdaomodule/pom.xml @@ -17,12 +17,12 @@ com.baeldung.entitymodule - entitymodule + maven-entitymodule ${entitymodule.version} com.baeldung.daomodule - daomodule + maven-daomodule ${daomodule.version} @@ -41,8 +41,6 @@ - 9 - 9 1.0 1.0 diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml index 5e293fdb02..2be1309c25 100644 --- a/maven-modules/pom.xml +++ b/maven-modules/pom.xml @@ -27,7 +27,7 @@ maven-classifier maven-copy-files maven-custom-plugin - maven-exec-plugin + maven-generate-war maven-integration-test maven-multi-source diff --git a/maven-modules/versions-maven-plugin/pom.xml b/maven-modules/versions-maven-plugin/pom.xml index ec1e0ceaba..39a345a506 100644 --- a/maven-modules/versions-maven-plugin/pom.xml +++ b/maven-modules/versions-maven-plugin/pom.xml @@ -3,7 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung versions-maven-plugin 0.0.1-SNAPSHOT versions-maven-plugin diff --git a/messaging-modules/java-redpanda/pom.xml b/messaging-modules/java-redpanda/pom.xml new file mode 100644 index 0000000000..a9a9e2f4ea --- /dev/null +++ b/messaging-modules/java-redpanda/pom.xml @@ -0,0 +1,61 @@ + + + 4.0.0 + java-redpanda + java-redpanda + + com.baeldung + messaging-modules + 0.0.1-SNAPSHOT + + + + + org.apache.kafka + kafka-clients + ${kafka.version} + + + + org.testcontainers + junit-jupiter + ${testcontainers-jupiter.version} + test + + + + org.testcontainers + testcontainers + test + + + + org.testcontainers + redpanda + ${redpanda.version} + + + + + + + + org.testcontainers + testcontainers-bom + 1.19.3 + pom + import + + + + + + 1.19.4 + 3.6.1 + 1.15.3 + UTF-8 + + + diff --git a/messaging-modules/java-redpanda/src/main/java/com/baeldung/redpanda/Application.java b/messaging-modules/java-redpanda/src/main/java/com/baeldung/redpanda/Application.java new file mode 100644 index 0000000000..15026a7b4c --- /dev/null +++ b/messaging-modules/java-redpanda/src/main/java/com/baeldung/redpanda/Application.java @@ -0,0 +1,7 @@ +package com.baeldung.redpanda; + + +public class Application { + public static void main(String[] args) { + } +} \ No newline at end of file diff --git a/messaging-modules/java-redpanda/src/test/java/com/baeldung/redpanda/RedpandaLiveTest.java b/messaging-modules/java-redpanda/src/test/java/com/baeldung/redpanda/RedpandaLiveTest.java new file mode 100644 index 0000000000..0dcbc4d2b2 --- /dev/null +++ b/messaging-modules/java-redpanda/src/test/java/com/baeldung/redpanda/RedpandaLiveTest.java @@ -0,0 +1,151 @@ +package com.baeldung.redpanda; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.Duration; +import java.util.Collections; +import java.util.Properties; +import java.util.concurrent.ExecutionException; + +import org.apache.kafka.clients.admin.AdminClient; +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.clients.admin.KafkaAdminClient; +import org.apache.kafka.clients.admin.NewTopic; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.ConsumerRecords; +import org.apache.kafka.clients.consumer.KafkaConsumer; +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.common.serialization.StringDeserializer; +import org.apache.kafka.common.serialization.StringSerializer; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testcontainers.containers.Network; +import org.testcontainers.redpanda.RedpandaContainer; + +public class RedpandaLiveTest { + private static final Logger LOGGER = LoggerFactory.getLogger(RedpandaLiveTest.class); + + private static RedpandaContainer redpandaContainer = null; + + private static final String TOPIC_NAME = "baeldung"; + + private static final Integer BROKER_PORT = 9092; + + @BeforeAll + static void setup() throws ExecutionException, InterruptedException { + installRedpanda(); + + createTopic(TOPIC_NAME); + + publishMessages(TOPIC_NAME); + } + + @AfterAll + static void cleanup() { + redpandaContainer.stop(); + } + + private static void publishMessages(String topic) throws ExecutionException, InterruptedException { + try (final KafkaProducer producer = createProducer()) { + for (int i = 0; i < 10; i++) { + publishMessage("test_msg_key_1_" + i, "How are you redpanda:" + i, topic, producer); + } + } + } + + private static void installRedpanda() { + final String DOCKER_IMAGE = "docker.redpanda.com/redpandadata/redpanda:v23.1.2"; + Network network = Network.newNetwork(); + redpandaContainer = new RedpandaContainer(DOCKER_IMAGE).withNetwork(network) + .withNetworkAliases("redpanda") + .withExposedPorts(BROKER_PORT); + redpandaContainer.start(); + } + + private static AdminClient createAdminClient() { + Properties adminProps = new Properties(); + adminProps.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, getBrokerUrl()); + return KafkaAdminClient.create(adminProps); + } + + private static void createTopic(String topicName) { + + try (AdminClient adminClient = createAdminClient()) { + NewTopic topic = new NewTopic(topicName, 1, (short) 1); + adminClient.createTopics(Collections.singleton(topic)); + } catch (Exception e) { + LOGGER.error("Error occurred during topic creation:", e); + } + } + + private static KafkaProducer createProducer() { + Properties producerProps = new Properties(); + producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, getBrokerUrl()); + producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + + return new KafkaProducer(producerProps); + } + + private static KafkaConsumer createConsumer() { + Properties consumerProps = new Properties(); + consumerProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, getBrokerUrl()); + consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "test-consumer-group"); + consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + + return new KafkaConsumer(consumerProps); + } + + private static void publishMessage(String msgKey, String msg, String topic, KafkaProducer producer) + throws ExecutionException, InterruptedException { + ProducerRecord record = new ProducerRecord<>(topic, msgKey, msg); + producer.send(record).get(); + } + + private static String getBrokerUrl() { + return redpandaContainer.getHost() + ":" + redpandaContainer.getMappedPort(BROKER_PORT); + } + + @Test + void whenCreateTopic_thenSuccess() throws ExecutionException, InterruptedException { + String topic = "test-topic"; + createTopic(topic); + try(AdminClient adminClient = createAdminClient()) { + assertTrue(adminClient.listTopics() + .names() + .get() + .contains(topic)); + } + } + + @Test + void givenTopic_whenPublishMsg_thenSuccess() { + try (final KafkaProducer producer = createProducer()) { + assertDoesNotThrow(() -> publishMessage("test_msg_key_2", "Hello Redpanda!", "baeldung-topic", producer)); + } + } + + @Test + void givenTopic_whenConsumeMessage_thenSuccess() { + try (KafkaConsumer kafkaConsumer = createConsumer()) { + kafkaConsumer.subscribe(Collections.singletonList(TOPIC_NAME)); + + while(true) { + ConsumerRecords records = kafkaConsumer.poll(Duration.ofMillis(1000)); + if(records.count() == 0) { + continue; + } + assertTrue(records.count() >= 1); + break; + } + } + } +} diff --git a/messaging-modules/pom.xml b/messaging-modules/pom.xml index 3642eb4260..3c70c66c20 100644 --- a/messaging-modules/pom.xml +++ b/messaging-modules/pom.xml @@ -18,6 +18,7 @@ apache-camel apache-rocketmq jgroups + java-redpanda rabbitmq spring-amqp spring-apache-camel 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/core-java-persistence-2/pom.xml b/persistence-modules/core-java-persistence-2/pom.xml index dea261adca..d785bc0452 100644 --- a/persistence-modules/core-java-persistence-2/pom.xml +++ b/persistence-modules/core-java-persistence-2/pom.xml @@ -87,7 +87,7 @@ 10.2.0.4.0 8.2.0 3.11.11 - 20220320 + 20240303 07.00.00-MS-GA 2.1.214 5.3.29 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/java-calcite/src/main/resources/logback.xml b/persistence-modules/java-calcite/src/main/resources/logback.xml new file mode 100644 index 0000000000..929cde67ec --- /dev/null +++ b/persistence-modules/java-calcite/src/main/resources/logback.xml @@ -0,0 +1,14 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 6d60340128..188ea132c6 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -82,7 +82,6 @@ spring-data-jpa-annotations spring-data-jpa-annotations-2 spring-data-jpa-crud - spring-data-jpa-crud-2 spring-data-jpa-enterprise spring-data-jpa-enterprise-2 spring-data-jpa-filtering @@ -93,6 +92,7 @@ spring-data-jpa-repo-2 spring-data-jpa-repo-4 spring-data-jdbc + spring-data-jpa-simple spring-data-keyvalue spring-data-mongodb spring-data-mongodb-2 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/persistence-modules/spring-boot-persistence-3/src/main/resources/application.yml b/persistence-modules/spring-boot-persistence-3/src/main/resources/application.yml index bb9e377c34..c805ac963b 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/resources/application.yml +++ b/persistence-modules/spring-boot-persistence-3/src/main/resources/application.yml @@ -1,4 +1,3 @@ - logging.level.org.hibernate: - SQL: DEBUG - type.descriptor.sql.BasicBinder: TRACE \ No newline at end of file + SQL: INFO + type.descriptor.sql.BasicBinder: INFO \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/README.md b/persistence-modules/spring-boot-persistence-mongodb/README.md index 8e9399f076..5453eb0052 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/README.md +++ b/persistence-modules/spring-boot-persistence-mongodb/README.md @@ -7,4 +7,5 @@ - [ZonedDateTime with Spring Data MongoDB](https://www.baeldung.com/spring-data-mongodb-zoneddatetime) - [A Guide to @DBRef in MongoDB](https://www.baeldung.com/spring-mongodb-dbref-annotation) - [Import Data to MongoDB From JSON File Using Java](https://www.baeldung.com/java-import-json-mongodb) +- [Spring Data MongoDB – Configure Connection](https://www.baeldung.com/spring-data-mongodb-connection) - More articles: [[next-->]](../spring-boot-persistence-mongodb-2) diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties index 65e65cc96c..2b37be6e57 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties +++ b/persistence-modules/spring-boot-persistence-mongodb/src/main/resources/application.properties @@ -10,4 +10,5 @@ spring.thymeleaf.cache=false spring.servlet.multipart.max-file-size=256MB spring.servlet.multipart.max-request-size=256MB -spring.servlet.multipart.enabled=true \ No newline at end of file +spring.servlet.multipart.enabled=true +spring.data.mongodb.uri=mongodb://localhost \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/MongoDbAutoGeneratedFieldIntegrationTest.java b/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/MongoDbAutoGeneratedFieldIntegrationTest.java index e20a229f36..9be3c7e171 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/MongoDbAutoGeneratedFieldIntegrationTest.java +++ b/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/mongodb/MongoDbAutoGeneratedFieldIntegrationTest.java @@ -2,30 +2,31 @@ package com.baeldung.mongodb; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringExtension; import com.baeldung.mongodb.daos.UserRepository; import com.baeldung.mongodb.models.User; - -@RunWith(SpringRunner.class) -@SpringBootTest +@ExtendWith(SpringExtension.class) @DirtiesContext -public class MongoDbAutoGeneratedFieldIntegrationTest { +@DataMongoTest +class MongoDbAutoGeneratedFieldIntegrationTest { @Autowired UserRepository userRepository; @Test - public void contextLoads() {} + void contextLoads() { + // Verifies the context is loaded correctly + } @Test - public void givenUserObject_whenSave_thenCreateNewUser() { + void givenUserObject_whenSave_thenCreateNewUser() { User user = new User(); user.setFirstName("John"); @@ -33,8 +34,8 @@ public class MongoDbAutoGeneratedFieldIntegrationTest { user.setEmail("john.doe@example.com"); userRepository.save(user); - assertThat(userRepository.findAll().size()).isGreaterThan(0); + assertThat(userRepository.findAll() + .size()).isPositive(); } - } diff --git a/persistence-modules/spring-data-jpa-crud-2/README.md b/persistence-modules/spring-data-jpa-crud-2/README.md deleted file mode 100644 index c912e1d5aa..0000000000 --- a/persistence-modules/spring-data-jpa-crud-2/README.md +++ /dev/null @@ -1,16 +0,0 @@ -## Spring Data JPA - CRUD - -This module contains articles about CRUD operations in Spring Data JPA - -### Relevant Articles: -- [Generate Database Schema with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-generate-db-schema) -- More articles: [[<--prev]](/persistence-modules/spring-data-jpa-crud) - -### Eclipse Config -After importing the project into Eclipse, you may see the following error: -"No persistence xml file found in project" - -This can be ignored: -- Project -> Properties -> Java Persistance -> JPA -> Error/Warnings -> Select Ignore on "No persistence xml file found in project" -Or: -- Eclipse -> Preferences - Validation - disable the "Build" execution of the JPA Validator diff --git a/persistence-modules/spring-data-jpa-crud-2/pom.xml b/persistence-modules/spring-data-jpa-crud-2/pom.xml deleted file mode 100644 index ff90d0ed8b..0000000000 --- a/persistence-modules/spring-data-jpa-crud-2/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - 4.0.0 - spring-data-jpa-crud-2 - spring-data-jpa-crud-2 - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.springframework.boot - spring-boot-starter-web - - - com.h2database - h2 - runtime - - - - \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-crud-2/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-crud-2/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java deleted file mode 100644 index 86a7671fe4..0000000000 --- a/persistence-modules/spring-data-jpa-crud-2/src/test/java/com/baeldung/schemageneration/AccountRepositoryIntegrationTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.baeldung.schemageneration; - -import com.baeldung.schemageneration.model.Account; -import com.baeldung.schemageneration.model.AccountSetting; -import com.baeldung.schemageneration.repository.AccountRepository; -import com.baeldung.schemageneration.repository.AccountSettingRepository; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AccountApplication.class) -public class AccountRepositoryIntegrationTest { - - private static final String USER_NAME = "Eduard"; - private static final String USER_EMAIL_ADDRESS = "eduard@gmx.com"; - private static final String ACCOUNT_SETTING_NAME = "Timezone"; - private static final String ACCOUNT_SETTING_VALUE = "UTC+02"; - - @Autowired - private AccountRepository accountRepository; - - @Autowired - private AccountSettingRepository accountSettingRepository; - - @After - public void tearDown() { - accountRepository.deleteAll(); - } - - @Test - public void givenNewAccount_whenSave_thenSuccess() { - Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); - accountRepository.save(account); - - assertEquals(1, accountRepository.count()); - } - - @Test - public void givenSavedAccount_whenFindByName_thenFound() { - Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); - accountRepository.save(account); - - Account accountFound = accountRepository.findByName(USER_NAME); - - assertNotNull(accountFound); - assertEquals(USER_NAME, accountFound.getName()); - assertEquals(USER_EMAIL_ADDRESS, accountFound.getEmailAddress()); - } - - @Test - public void givenSavedAccount_whenAccountSettingIsAdded_thenPersisted() { - Account account = new Account(USER_NAME, USER_EMAIL_ADDRESS); - account.addAccountSetting(new AccountSetting(ACCOUNT_SETTING_NAME, ACCOUNT_SETTING_VALUE)); - accountRepository.save(account); - - Account accountFound = accountRepository.findByName(USER_NAME); - assertNotNull(accountFound); - AccountSetting accountSetting = accountSettingRepository.findByAccountId(accountFound.getId()); - - assertNotNull(accountSetting); - assertEquals(ACCOUNT_SETTING_NAME, accountSetting.getSettingName()); - assertEquals(ACCOUNT_SETTING_VALUE, accountSetting.getSettingValue()); - } - -} diff --git a/persistence-modules/spring-data-jpa-enterprise/README.md b/persistence-modules/spring-data-jpa-enterprise/README.md index c48a519a87..de29532dfc 100644 --- a/persistence-modules/spring-data-jpa-enterprise/README.md +++ b/persistence-modules/spring-data-jpa-enterprise/README.md @@ -8,9 +8,7 @@ This module contains articles about Spring Data JPA used in enterprise applicati - [DB Integration Tests with Spring Boot and Testcontainers](https://www.baeldung.com/spring-boot-testcontainers-integration-test) - [A Guide to Spring’s Open Session in View](https://www.baeldung.com/spring-open-session-in-view) - [Partial Data Update With Spring Data](https://www.baeldung.com/spring-data-partial-update) -- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation) - [Spring JPA – Multiple Databases](https://www.baeldung.com/spring-data-jpa-multiple-databases) -- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-data-jpa-filtering/README.md b/persistence-modules/spring-data-jpa-filtering/README.md index fe2f181154..b29c0b9e7b 100644 --- a/persistence-modules/spring-data-jpa-filtering/README.md +++ b/persistence-modules/spring-data-jpa-filtering/README.md @@ -6,7 +6,6 @@ This module contains articles about filtering data using Spring Data JPA - [An Advanced Tagging Implementation with JPA](https://www.baeldung.com/jpa-tagging-advanced) - [A Simple Tagging Implementation with JPA](https://www.baeldung.com/jpa-tagging) - [Spring Data JPA and Null Parameters](https://www.baeldung.com/spring-data-jpa-null-parameters) -- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections) ### Eclipse Config After importing the project into Eclipse, you may see the following error: diff --git a/persistence-modules/spring-data-jpa-query-2/README.md b/persistence-modules/spring-data-jpa-query-2/README.md index e091bc1d99..db1d0cd4c7 100644 --- a/persistence-modules/spring-data-jpa-query-2/README.md +++ b/persistence-modules/spring-data-jpa-query-2/README.md @@ -4,7 +4,6 @@ This module contains articles about querying data using Spring Data JPA . ### Relevant Articles: -- [Spring Data JPA @Query](https://www.baeldung.com/spring-data-jpa-query) - [Use Criteria Queries in a Spring Data Application](https://www.baeldung.com/spring-data-criteria-queries) - [Hibernate Pagination](https://www.baeldung.com/hibernate-pagination) - [Sorting with Hibernate](https://www.baeldung.com/hibernate-sort) diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/QueryApplication.java b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/QueryApplication.java similarity index 88% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/QueryApplication.java rename to persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/QueryApplication.java index d7a1950305..a7d029b54d 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/QueryApplication.java +++ b/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/QueryApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.derivedquery; +package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @@ -10,4 +10,4 @@ public class QueryApplication { SpringApplication.run(QueryApplication.class, args); } -} +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/README.md b/persistence-modules/spring-data-jpa-query/README.md index 27e7087592..db923dd56a 100644 --- a/persistence-modules/spring-data-jpa-query/README.md +++ b/persistence-modules/spring-data-jpa-query/README.md @@ -4,7 +4,6 @@ This module contains articles about querying data using Spring Data JPA ### Relevant Articles: - [The Exists Query in Spring Data](https://www.baeldung.com/spring-data-exists-query) -- [Customizing the Result of JPA Queries with Aggregation Functions](https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions) - [Limiting Query Results With JPA and Spring Data JPA](https://www.baeldung.com/jpa-limit-query-results) - [Sorting Query Results with Spring Data](https://www.baeldung.com/spring-data-sorting) - [Spring Data JPA Query by Example](https://www.baeldung.com/spring-data-query-by-example) diff --git a/persistence-modules/spring-data-jpa-repo-3/README.md b/persistence-modules/spring-data-jpa-repo-3/README.md index 03b0e7f76b..ff219a1d78 100644 --- a/persistence-modules/spring-data-jpa-repo-3/README.md +++ b/persistence-modules/spring-data-jpa-repo-3/README.md @@ -3,7 +3,6 @@ This module contains articles about Spring Data JPA. ### Relevant Articles: -- [New CRUD Repository Interfaces in Spring Data 3](https://www.baeldung.com/spring-data-3-crud-repository-interfaces) - [How to Persist a List of String in JPA?](https://www.baeldung.com/java-jpa-persist-string-list) - [Hibernate Natural IDs in Spring Boot](https://www.baeldung.com/spring-boot-hibernate-natural-ids) - [Correct Use of flush() in JPA](https://www.baeldung.com/spring-jpa-flush) diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/fetchandrefresh/Order.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/fetchandrefresh/Order.java new file mode 100644 index 0000000000..f25513dc12 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/fetchandrefresh/Order.java @@ -0,0 +1,79 @@ +package com.baeldung.fetchandrefresh; + +import java.time.LocalDate; +import java.util.List; + +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Version; + +@Entity +public class Order { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + @OneToMany(mappedBy = "order", fetch = FetchType.EAGER) + private List orderItems; + + private LocalDate orderDate; + + private String name; + + private String customerName; + + @Version + private Long version; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public List getOrderItems() { + return orderItems; + } + + public void setOrderItems(List orderItems) { + this.orderItems = orderItems; + } + + public LocalDate getOrderDate() { + return orderDate; + } + + public void setOrderDate(LocalDate orderDate) { + this.orderDate = orderDate; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getCustomerName() { + return customerName; + } + + public void setCustomerName(String customerName) { + this.customerName = customerName; + } + + public Long getVersion() { + return version; + } + + public void setVersion(Long version) { + this.version = version; + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/fetchandrefresh/OrderItem.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/fetchandrefresh/OrderItem.java new file mode 100644 index 0000000000..c3c59987a8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/fetchandrefresh/OrderItem.java @@ -0,0 +1,63 @@ +package com.baeldung.fetchandrefresh; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; + +@Entity +public class OrderItem { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String name; + private int quantity; + private double price; + + @JoinColumn(name = "order_id") + private Order order; + + // Getters and setters + + 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 int getQuantity() { + return quantity; + } + + public void setQuantity(int quantity) { + this.quantity = quantity; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + public Order getOrder() { + return order; + } + + public void setOrder(Order order) { + this.order = order; + } +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/fetchandrefresh/OrderRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/fetchandrefresh/OrderRepository.java new file mode 100644 index 0000000000..9de20d9184 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/fetchandrefresh/OrderRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.fetchandrefresh; + +import java.time.LocalDate; +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; + +@Repository +public interface OrderRepository extends JpaRepository { + + @Query("SELECT o FROM Order o WHERE o.customerName = :customerName AND o.orderDate BETWEEN :startDate AND :endDate") + List findOrdersByCustomerAndDateRange(@Param("customerName") String customerName, @Param("startDate") LocalDate startDate, + @Param("endDate") LocalDate endDate); +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/fetchandrefresh/OrderService.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/fetchandrefresh/OrderService.java new file mode 100644 index 0000000000..1f1665fa79 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/fetchandrefresh/OrderService.java @@ -0,0 +1,62 @@ +package com.baeldung.fetchandrefresh; + +import java.time.LocalDate; +import java.util.List; +import java.util.Optional; + +import org.aspectj.weaver.ast.Or; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityNotFoundException; +import jakarta.persistence.OptimisticLockException; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; + +@Service +public class OrderService { + + @Autowired + private EntityManager entityManager; + + @Autowired + private OrderRepository orderRepository; + + public List findOrdersByCustomerAndDateRangeUsingCriteriaAPI(String customerName, LocalDate startDate, LocalDate endDate) { + CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Order.class); + Root root = criteriaQuery.from(Order.class); + + Predicate customerPredicate = criteriaBuilder.equal(root.get("customerName"), customerName); + Predicate dateRangePredicate = criteriaBuilder.between(root.get("orderDate"), startDate, endDate); + + criteriaQuery.where(customerPredicate, dateRangePredicate); + + return entityManager.createQuery(criteriaQuery) + .getResultList(); + } + + public void updateOrderName(long orderId, String newName) { + Order order = orderRepository.findById(orderId) + .map(existingOrder -> { + existingOrder.setName(newName); + return existingOrder; + }) + .orElseGet(() -> { + return null; + }); + + if (order != null) { + try { + orderRepository.save(order); + } catch (OptimisticLockException e) { + // Refresh the entity and potentially retry the update + entityManager.refresh(order); + // Consider adding logic to handle retries or notify the user about the conflict + } + } + } +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryIntegrationTest.java index 7bd1b90407..5b1b51adc5 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryIntegrationTest.java @@ -10,14 +10,14 @@ import org.springframework.boot.test.context.SpringBootTest; import java.util.Arrays; @SpringBootTest -public class LibraryIntegrationTest { +class LibraryIntegrationTest { @Autowired private LibraryRepository libraryRepository; @Test @Transactional - public void givenLibrary_whenGetAddressesAndGetBooks_thenGetListOfItems(){ + void givenLibrary_whenGetAddressesAndGetBooks_thenGetListOfItems(){ Library library = new Library(); library.setAddresses(Arrays.asList("Address 1", "Address 2")); library.setBooks(Arrays.asList("Book 1", "Book 2")); diff --git a/persistence-modules/spring-data-jpa-repo/README.md b/persistence-modules/spring-data-jpa-repo/README.md index ef3442929e..f404263159 100644 --- a/persistence-modules/spring-data-jpa-repo/README.md +++ b/persistence-modules/spring-data-jpa-repo/README.md @@ -2,10 +2,8 @@ This module contains articles about repositories in Spring Data JPA -### Relevant Articles: -- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) +### Relevant Articles: - [Case Insensitive Queries with Spring Data Repository](https://www.baeldung.com/spring-data-case-insensitive-queries) -- [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) - [Spring Data – CrudRepository save() Method](https://www.baeldung.com/spring-data-crud-repository-save) - [Spring Data JPA – Adding a Method in All Repositories](https://www.baeldung.com/spring-data-jpa-method-in-all-repositories) - [Spring Data Composable Repositories](https://www.baeldung.com/spring-data-composable-repositories) diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java deleted file mode 100644 index cf479780a1..0000000000 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/derivedquery/repository/UserRepositoryIntegrationTest.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.baeldung.derivedquery.repository; - -import com.baeldung.derivedquery.QueryApplication; -import com.baeldung.derivedquery.entity.User; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import java.time.ZonedDateTime; -import java.util.Arrays; -import java.util.List; - -import static org.junit.Assert.assertEquals; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = QueryApplication.class) -public class UserRepositoryIntegrationTest { - - private static final String USER_NAME_ADAM = "Adam"; - private static final String USER_NAME_EVE = "Eve"; - private static final ZonedDateTime BIRTHDATE = ZonedDateTime.now(); - - @Autowired - private UserRepository userRepository; - - @Before - public void setUp() { - - User user1 = new User(USER_NAME_ADAM, 25, BIRTHDATE, true); - User user2 = new User(USER_NAME_ADAM, 20, BIRTHDATE, false); - User user3 = new User(USER_NAME_EVE, 20, BIRTHDATE, true); - User user4 = new User(null, 30, BIRTHDATE, false); - - userRepository.saveAll(Arrays.asList(user1, user2, user3, user4)); - } - - @After - public void tearDown() { - - userRepository.deleteAll(); - } - - @Test - public void whenFindByName_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByName(USER_NAME_ADAM).size()); - } - - @Test - public void whenFindByNameIsNull_thenReturnsCorrectResult() { - - assertEquals(1, userRepository.findByNameIsNull().size()); - } - - @Test - public void whenFindByNameNot_thenReturnsCorrectResult() { - - assertEquals(USER_NAME_EVE, userRepository.findByNameNot(USER_NAME_ADAM).get(0).getName()); - } - - @Test - public void whenFindByNameStartingWith_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByNameStartingWith("A").size()); - } - - @Test - public void whenFindByNameEndingWith_thenReturnsCorrectResult() { - - assertEquals(1, userRepository.findByNameEndingWith("e").size()); - } - - @Test - public void whenByNameContaining_thenReturnsCorrectResult() { - - assertEquals(1, userRepository.findByNameContaining("v").size()); - } - - - @Test - public void whenByNameLike_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByNameEndingWith("m").size()); - } - - @Test - public void whenByAgeLessThan_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByAgeLessThan(25).size()); - } - - - @Test - public void whenByAgeLessThanEqual_thenReturnsCorrectResult() { - - assertEquals(3, userRepository.findByAgeLessThanEqual(25).size()); - } - - @Test - public void whenByAgeGreaterThan_thenReturnsCorrectResult() { - - assertEquals(1, userRepository.findByAgeGreaterThan(25).size()); - } - - @Test - public void whenByAgeGreaterThanEqual_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByAgeGreaterThanEqual(25).size()); - } - - @Test - public void whenByAgeBetween_thenReturnsCorrectResult() { - - assertEquals(4, userRepository.findByAgeBetween(20, 30).size()); - } - - @Test - public void whenByBirthDateAfter_thenReturnsCorrectResult() { - - final ZonedDateTime yesterday = BIRTHDATE.minusDays(1); - assertEquals(4, userRepository.findByBirthDateAfter(yesterday).size()); - } - - @Test - public void whenByBirthDateBefore_thenReturnsCorrectResult() { - - final ZonedDateTime yesterday = BIRTHDATE.minusDays(1); - assertEquals(0, userRepository.findByBirthDateBefore(yesterday).size()); - } - - @Test - public void whenByActiveTrue_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByActiveTrue().size()); - } - - @Test - public void whenByActiveFalse_thenReturnsCorrectResult() { - - assertEquals(2, userRepository.findByActiveFalse().size()); - } - - - @Test - public void whenByAgeIn_thenReturnsCorrectResult() { - - final List ages = Arrays.asList(20, 25); - assertEquals(3, userRepository.findByAgeIn(ages).size()); - } - - @Test - public void whenByNameOrAge() { - - assertEquals(3, userRepository.findByNameOrAge(USER_NAME_ADAM, 20).size()); - } - - @Test - public void whenByNameOrAgeAndActive() { - - assertEquals(2, userRepository.findByNameOrAgeAndActive(USER_NAME_ADAM, 20, false).size()); - } - - @Test - public void whenByNameOrderByName() { - - assertEquals(2, userRepository.findByNameOrderByName(USER_NAME_ADAM).size()); - } -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-simple/README.md b/persistence-modules/spring-data-jpa-simple/README.md new file mode 100644 index 0000000000..4d96acb0f4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/README.md @@ -0,0 +1,20 @@ +### Spring Data JPA Articles that are also part of the e-book + +This module contains articles about Spring Data JPA that are also part of an Ebook. + + +### NOTE: + +Since this is a module tied to an e-book, it should **not** be moved or used to store the code for any further article. + +### Relevant Articles +- [Introduction to Spring Data JPA](https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa) +- [Customizing the Result of JPA Queries with Aggregation Functions](https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions) +- [CrudRepository, JpaRepository, and PagingAndSortingRepository in Spring Data](https://www.baeldung.com/spring-data-repositories) +- [New CRUD Repository Interfaces in Spring Data 3](https://www.baeldung.com/spring-data-3-crud-repository-interfaces) +- [Derived Query Methods in Spring Data JPA Repositories](https://www.baeldung.com/spring-data-derived-queries) +- [Spring Data JPA @Query](https://www.baeldung.com/spring-data-jpa-query) +- [Spring Data JPA Projections](https://www.baeldung.com/spring-data-jpa-projections) +- [Spring Data JPA @Modifying Annotation](https://www.baeldung.com/spring-data-jpa-modifying-annotation) +- [Generate Database Schema with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-generate-db-schema) +- [Pagination and Sorting using Spring Data JPA](https://www.baeldung.com/spring-data-jpa-pagination-sorting) \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-simple/pom.xml b/persistence-modules/spring-data-jpa-simple/pom.xml new file mode 100644 index 0000000000..dc59b1fd22 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/pom.xml @@ -0,0 +1,88 @@ + + + 4.0.0 + spring-data-jpa-simple + spring-data-jpa-simple + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-data-jdbc + + + com.mysql + mysql-connector-j + + + org.postgresql + postgresql + + + com.h2database + h2 + runtime + + + org.springframework + spring-oxm + + + com.google.guava + guava + ${guava.version} + + + jakarta.xml.bind + jakarta.xml.bind-api + ${jakarta.xml.bind.version} + + + org.hibernate.orm + hibernate-ant + ${hibernate.version} + + + + + 6.4.2.Final + 4.0.0 + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + repackage + + repackage + + + true + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/AggregationApplication.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/AggregationApplication.java new file mode 100644 index 0000000000..eebafa387c --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/AggregationApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.jpa.aggregation; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +@PropertySource("classpath:aggregation.properties") +@Configuration +public class AggregationApplication { + + public static void main(String[] args) { + SpringApplication.run(AggregationApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Comment.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/model/Comment.java similarity index 97% rename from persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Comment.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/model/Comment.java index 8b4872e05e..8d871fd3fa 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Comment.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/model/Comment.java @@ -1,9 +1,10 @@ -package com.baeldung.aggregation.model; +package com.baeldung.jpa.aggregation.model; + +import java.util.Objects; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.ManyToOne; -import java.util.Objects; @Entity public class Comment { diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Post.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/model/Post.java similarity index 96% rename from persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Post.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/model/Post.java index 25f48c386e..b0c4fc1523 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/Post.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/model/Post.java @@ -1,13 +1,15 @@ -package com.baeldung.aggregation.model; +package com.baeldung.jpa.aggregation.model; + +import java.util.List; +import java.util.Objects; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; -import java.util.List; -import java.util.Objects; @Entity public class Post { + @Id private Integer id; private String title; diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/model/custom/CommentCount.java similarity index 89% rename from persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/model/custom/CommentCount.java index 510b52a47c..f70157c514 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/CommentCount.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/model/custom/CommentCount.java @@ -1,4 +1,4 @@ -package com.baeldung.aggregation.model.custom; +package com.baeldung.jpa.aggregation.model.custom; public class CommentCount { private Integer year; diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/model/custom/ICommentCount.java similarity index 65% rename from persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/model/custom/ICommentCount.java index acb25cfd49..645cda8a35 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/model/custom/ICommentCount.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/model/custom/ICommentCount.java @@ -1,4 +1,4 @@ -package com.baeldung.aggregation.model.custom; +package com.baeldung.jpa.aggregation.model.custom; public interface ICommentCount { diff --git a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/repository/CommentRepository.java similarity index 70% rename from persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/repository/CommentRepository.java index 5309581638..f0312e0784 100644 --- a/persistence-modules/spring-data-jpa-query/src/main/java/com/baeldung/aggregation/repository/CommentRepository.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/aggregation/repository/CommentRepository.java @@ -1,13 +1,14 @@ -package com.baeldung.aggregation.repository; +package com.baeldung.jpa.aggregation.repository; + +import java.util.List; -import com.baeldung.aggregation.model.Comment; -import com.baeldung.aggregation.model.custom.CommentCount; -import com.baeldung.aggregation.model.custom.ICommentCount; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; -import java.util.List; +import com.baeldung.jpa.aggregation.model.Comment; +import com.baeldung.jpa.aggregation.model.custom.CommentCount; +import com.baeldung.jpa.aggregation.model.custom.ICommentCount; @Repository public interface CommentRepository extends JpaRepository { @@ -15,7 +16,7 @@ public interface CommentRepository extends JpaRepository { @Query("SELECT c.year, COUNT(c.year) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") List countTotalCommentsByYear(); - @Query("SELECT new com.baeldung.aggregation.model.custom.CommentCount(c.year, COUNT(c.year)) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") + @Query("SELECT new com.baeldung.jpa.aggregation.model.custom.CommentCount(c.year, COUNT(c.year)) FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") List countTotalCommentsByYearClass(); @Query("SELECT c.year AS yearComment, COUNT(c.year) AS totalComment FROM Comment AS c GROUP BY c.year ORDER BY c.year DESC") diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/modifying/ModifyingApplication.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/modifying/ModifyingApplication.java new file mode 100644 index 0000000000..8744220a0e --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/modifying/ModifyingApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.jpa.modifying; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +@EnableJpaRepositories("com.baeldung.jpa.modifying") +@EntityScan("com.baeldung.jpa.modifying") +public class ModifyingApplication { + + public static void main(String[] args) { + SpringApplication.run(ModifyingApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/modifying/dao/UserRepository.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/modifying/dao/UserRepository.java new file mode 100644 index 0000000000..34a88ae2da --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/modifying/dao/UserRepository.java @@ -0,0 +1,37 @@ +package com.baeldung.jpa.modifying.dao; + +import java.time.LocalDate; +import java.util.List; +import java.util.stream.Stream; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import com.baeldung.jpa.modifying.model.User; + +public interface UserRepository extends JpaRepository { + + Stream findAllByName(String name); + + void deleteAllByCreationDateAfter(LocalDate date); + + @Query("select u from User u where u.email like '%@gmail.com'") + List findUsersWithGmailAddress(); + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query("update User u set u.active = false where u.lastLoginDate < :date") + void deactivateUsersNotLoggedInSince(@Param("date") LocalDate date); + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query("delete User u where u.active = false") + int deleteDeactivatedUsers(); + + @Modifying(clearAutomatically = true, flushAutomatically = true) + @Query(value = "alter table USERS add column deleted int not null default 0", nativeQuery = true) + void addDeletedColumn(); + + @Query("delete User u where u.active = false") + int deleteDeactivatedUsersWithNoModifyingAnnotation(); +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/modifying/model/Possession.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/modifying/model/Possession.java new file mode 100644 index 0000000000..bc1077a3bf --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/modifying/model/Possession.java @@ -0,0 +1,86 @@ +package com.baeldung.jpa.modifying.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +@Entity +@Table +public class Possession { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + private String name; + + public Possession() { + super(); + } + + public Possession(final String name) { + super(); + + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = (prime * result) + (int) (id ^ (id >>> 32)); + result = (prime * result) + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final Possession other = (Possession) obj; + if (id != other.id) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Possesion [id=").append(id).append(", name=").append(name).append("]"); + return builder.toString(); + } + +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/modifying/model/User.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/modifying/model/User.java new file mode 100644 index 0000000000..651e94fef0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/modifying/model/User.java @@ -0,0 +1,138 @@ +package com.baeldung.jpa.modifying.model; + +import java.time.LocalDate; +import java.util.List; +import java.util.Objects; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private int id; + private String name; + private LocalDate creationDate; + private LocalDate lastLoginDate; + private boolean active; + private int age; + @Column(unique = true, nullable = false) + private String email; + private Integer status; + @OneToMany + List possessionList; + + public User() { + super(); + } + + public User(String name, LocalDate creationDate,String email, Integer status) { + this.name = name; + this.creationDate = creationDate; + this.email = email; + this.status = status; + this.active = true; + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(final String email) { + this.email = email; + } + + public Integer getStatus() { + return status; + } + + public void setStatus(Integer status) { + this.status = status; + } + + public int getAge() { + return age; + } + + public void setAge(final int age) { + this.age = age; + } + + public LocalDate getCreationDate() { + return creationDate; + } + + public List getPossessionList() { + return possessionList; + } + + public void setPossessionList(List possessionList) { + this.possessionList = possessionList; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("User [name=").append(name).append(", id=").append(id).append("]"); + return builder.toString(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + User user = (User) o; + return id == user.id && + age == user.age && + Objects.equals(name, user.name) && + Objects.equals(creationDate, user.creationDate) && + Objects.equals(email, user.email) && + Objects.equals(status, user.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, creationDate, age, email, status); + } + + public LocalDate getLastLoginDate() { + return lastLoginDate; + } + + public void setLastLoginDate(LocalDate lastLoginDate) { + this.lastLoginDate = lastLoginDate; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/paginationsorting/PaginationSortingApplication.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/paginationsorting/PaginationSortingApplication.java new file mode 100644 index 0000000000..6049bce07c --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/paginationsorting/PaginationSortingApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.jpa.paginationsorting; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication(scanBasePackages = "com.baeldung.jpa.paginationsorting") +public class PaginationSortingApplication { + + public static void main(String[] args) { + SpringApplication.run(PaginationSortingApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/paginationsorting/PersistenceProductConfiguration.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/paginationsorting/PersistenceProductConfiguration.java new file mode 100644 index 0000000000..a9702a3f54 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/paginationsorting/PersistenceProductConfiguration.java @@ -0,0 +1,63 @@ +package com.baeldung.jpa.paginationsorting; + +import java.util.HashMap; + +import javax.sql.DataSource; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; + +import com.google.common.base.Preconditions; + +@Configuration +@PropertySource({ "classpath:pagination-sorting-db.properties" }) +@EnableJpaRepositories(basePackages = "com.baeldung.jpa.paginationsorting", entityManagerFactoryRef = "productEntityManager", transactionManagerRef = "productTransactionManager") +public class PersistenceProductConfiguration { + private final Environment env; + + public PersistenceProductConfiguration(Environment env) { + this.env = env; + } + + @Bean + public LocalContainerEntityManagerFactoryBean productEntityManager() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(productDataSource()); + em.setPackagesToScan("com.baeldung.jpa.paginationsorting"); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + final HashMap properties = new HashMap(); + properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); + em.setJpaPropertyMap(properties); + + return em; + } + + @Bean + public DataSource productDataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("product.jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager productTransactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(productEntityManager().getObject()); + return transactionManager; + } +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/paginationsorting/model/Product.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/paginationsorting/model/Product.java new file mode 100644 index 0000000000..188ebcaf56 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/paginationsorting/model/Product.java @@ -0,0 +1,67 @@ +package com.baeldung.jpa.paginationsorting.model; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +@Entity +@Table(schema = "products") +public class Product { + + @Id + private int id; + + private String name; + + private double price; + + public Product() { + super(); + } + + private Product(int id, String name, double price) { + super(); + this.id = id; + this.name = name; + this.price = price; + } + + public static Product from(int id, String name, double price) { + return new Product(id, name, price); + } + + public int getId() { + return id; + } + + public void setId(final int id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(final double price) { + this.price = price; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Product [name=") + .append(name) + .append(", id=") + .append(id) + .append("]"); + return builder.toString(); + } +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/paginationsorting/repository/ProductRepository.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/paginationsorting/repository/ProductRepository.java new file mode 100644 index 0000000000..8c89d88ac8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/paginationsorting/repository/ProductRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.jpa.paginationsorting.repository; + +import java.util.List; + +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.PagingAndSortingRepository; + +import com.baeldung.jpa.paginationsorting.model.Product; + +public interface ProductRepository extends PagingAndSortingRepository, CrudRepository { + + List findAllByPrice(double price, Pageable pageable); + +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/ProjectionApplication.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/ProjectionApplication.java new file mode 100644 index 0000000000..469eeaff24 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/ProjectionApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.jpa.projection; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ProjectionApplication { + + public static void main(String[] args) { + SpringApplication.run(ProjectionApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Address.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/model/Address.java similarity index 85% rename from persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Address.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/model/Address.java index 0c5a3eac60..aa86e056bb 100644 --- a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Address.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/model/Address.java @@ -1,8 +1,8 @@ -package com.baeldung.projection.model; +package com.baeldung.jpa.projection.model; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; @Entity public class Address { diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Person.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/model/Person.java similarity index 83% rename from persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Person.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/model/Person.java index d18bd1c72d..daec08e703 100644 --- a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/model/Person.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/model/Person.java @@ -1,8 +1,8 @@ -package com.baeldung.projection.model; +package com.baeldung.jpa.projection.model; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToOne; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.OneToOne; @Entity public class Person { diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/AddressRepository.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/repository/AddressRepository.java similarity index 57% rename from persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/AddressRepository.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/repository/AddressRepository.java index c1053f4867..1e247f69d8 100644 --- a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/AddressRepository.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/repository/AddressRepository.java @@ -1,11 +1,12 @@ -package com.baeldung.projection.repository; - -import com.baeldung.projection.view.AddressView; -import com.baeldung.projection.model.Address; -import org.springframework.data.repository.Repository; +package com.baeldung.jpa.projection.repository; import java.util.List; +import org.springframework.data.repository.Repository; + +import com.baeldung.jpa.projection.model.Address; +import com.baeldung.jpa.projection.view.AddressView; + public interface AddressRepository extends Repository { List getAddressByState(String state); } diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/PersonRepository.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/repository/PersonRepository.java similarity index 58% rename from persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/PersonRepository.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/repository/PersonRepository.java index 64bc7471e6..cd76c97836 100644 --- a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/repository/PersonRepository.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/repository/PersonRepository.java @@ -1,10 +1,11 @@ -package com.baeldung.projection.repository; +package com.baeldung.jpa.projection.repository; -import com.baeldung.projection.model.Person; -import com.baeldung.projection.view.PersonDto; -import com.baeldung.projection.view.PersonView; import org.springframework.data.repository.Repository; +import com.baeldung.jpa.projection.model.Person; +import com.baeldung.jpa.projection.view.PersonDto; +import com.baeldung.jpa.projection.view.PersonView; + public interface PersonRepository extends Repository { PersonView findByLastName(String lastName); diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/AddressView.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/view/AddressView.java similarity index 67% rename from persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/AddressView.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/view/AddressView.java index 7a24a1e9b9..7ac593b059 100644 --- a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/AddressView.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/view/AddressView.java @@ -1,4 +1,4 @@ -package com.baeldung.projection.view; +package com.baeldung.jpa.projection.view; public interface AddressView { String getZipCode(); diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonDto.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/view/PersonDto.java similarity index 95% rename from persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonDto.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/view/PersonDto.java index 1fd924450b..9146e3008c 100644 --- a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonDto.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/view/PersonDto.java @@ -1,4 +1,4 @@ -package com.baeldung.projection.view; +package com.baeldung.jpa.projection.view; import java.util.Objects; diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonView.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/view/PersonView.java similarity index 84% rename from persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonView.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/view/PersonView.java index 36777ec26f..0772832223 100644 --- a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/projection/view/PersonView.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/projection/view/PersonView.java @@ -1,4 +1,4 @@ -package com.baeldung.projection.view; +package com.baeldung.jpa.projection.view; import org.springframework.beans.factory.annotation.Value; diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/QueryApplication.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/QueryApplication.java similarity index 69% rename from persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/QueryApplication.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/QueryApplication.java index 48c29eda23..fc00c7b4ac 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/QueryApplication.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/QueryApplication.java @@ -1,9 +1,11 @@ -package com.baeldung.spring.data.jpa.query; +package com.baeldung.jpa.query; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication +//@ComponentScan("com.baeldung.jpa.query") +//@EnableJpaRepositories("com.baeldung.jpa.query") public class QueryApplication { public static void main(String[] args) { diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/User.java similarity index 91% rename from persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/User.java index 648b06cf5f..68b66d0801 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/User.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/User.java @@ -1,10 +1,15 @@ -package com.baeldung.spring.data.jpa.query; +package com.baeldung.jpa.query; -import jakarta.persistence.*; import java.time.LocalDate; -import java.util.List; import java.util.Objects; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + @Entity @Table(name = "users") public class User { diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepository.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/UserRepository.java similarity index 96% rename from persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepository.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/UserRepository.java index 6547e0ef66..c70552e029 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepository.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/UserRepository.java @@ -1,4 +1,7 @@ -package com.baeldung.spring.data.jpa.query; +package com.baeldung.jpa.query; + +import java.util.Collection; +import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; @@ -7,10 +10,9 @@ import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; +import org.springframework.stereotype.Repository; -import java.util.Collection; -import java.util.List; - +@Repository public interface UserRepository extends JpaRepository, UserRepositoryCustom { @Query("SELECT u FROM User u WHERE u.status = 1") Collection findAllActiveUsers(); diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustom.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/UserRepositoryCustom.java similarity index 85% rename from persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustom.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/UserRepositoryCustom.java index a3e53528f7..22fbdab7f5 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustom.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/UserRepositoryCustom.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.jpa.query; +package com.baeldung.jpa.query; import java.util.Collection; import java.util.List; @@ -8,7 +8,7 @@ import java.util.function.Predicate; public interface UserRepositoryCustom { List findUserByEmails(Set emails); - + List findAllUsersByPredicates(Collection> predicates); } diff --git a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/UserRepositoryCustomImpl.java similarity index 85% rename from persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/UserRepositoryCustomImpl.java index 54cea74e04..4f7d8064b9 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/main/java/com/baeldung/spring/data/jpa/query/UserRepositoryCustomImpl.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/query/UserRepositoryCustomImpl.java @@ -1,8 +1,5 @@ -package com.baeldung.spring.data.jpa.query; +package com.baeldung.jpa.query; -import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; -import jakarta.persistence.criteria.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -10,6 +7,14 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Path; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; + public class UserRepositoryCustomImpl implements UserRepositoryCustom { @PersistenceContext private EntityManager entityManager; @@ -34,7 +39,7 @@ public class UserRepositoryCustomImpl implements UserRepositoryCustom { return entityManager.createQuery(query) .getResultList(); } - + @Override public List findAllUsersByPredicates(Collection> predicates) { List allUsers = entityManager.createQuery("select u from User u", User.class).getResultList(); diff --git a/persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/AccountApplication.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/AccountApplication.java similarity index 64% rename from persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/AccountApplication.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/AccountApplication.java index 547992a6c1..367e39507e 100644 --- a/persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/AccountApplication.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/AccountApplication.java @@ -1,9 +1,11 @@ -package com.baeldung.schemageneration; +package com.baeldung.jpa.schemageneration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; @SpringBootApplication +@PropertySource("classpath:schema-generation.properties") public class AccountApplication { public static void main(String[] args) { diff --git a/persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/HibernateUtil.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/HibernateUtil.java similarity index 86% rename from persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/HibernateUtil.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/HibernateUtil.java index 7d69d65705..910dad26a3 100644 --- a/persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/HibernateUtil.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/HibernateUtil.java @@ -1,7 +1,9 @@ -package com.baeldung.schemageneration; +package com.baeldung.jpa.schemageneration; + +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; -import com.baeldung.schemageneration.model.Account; -import com.baeldung.schemageneration.model.AccountSetting; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; @@ -10,9 +12,8 @@ import org.hibernate.cfg.Environment; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.schema.TargetType; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; +import com.baeldung.jpa.schemageneration.model.Account; +import com.baeldung.jpa.schemageneration.model.AccountSetting; public class HibernateUtil { @@ -21,7 +22,7 @@ public class HibernateUtil { * Creation commands are exported into the create.sql file. */ public static void generateSchema() { - Map settings = new HashMap<>(); + Map settings = new HashMap<>(); settings.put(Environment.URL, "jdbc:h2:mem:schema"); StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(settings).build(); diff --git a/persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/model/Account.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/model/Account.java similarity index 81% rename from persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/model/Account.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/model/Account.java index 785e275e26..e09605c552 100644 --- a/persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/model/Account.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/model/Account.java @@ -1,15 +1,16 @@ -package com.baeldung.schemageneration.model; +package com.baeldung.jpa.schemageneration.model; -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; import java.util.ArrayList; import java.util.List; +import jakarta.persistence.CascadeType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.OneToMany; +import jakarta.persistence.Table; + @Entity @Table(name = "accounts") public class Account { diff --git a/persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/model/AccountSetting.java similarity index 79% rename from persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/model/AccountSetting.java index 61e43894a8..a36a72f73d 100644 --- a/persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/model/AccountSetting.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/model/AccountSetting.java @@ -1,12 +1,12 @@ -package com.baeldung.schemageneration.model; +package com.baeldung.jpa.schemageneration.model; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; @Entity @Table(name = "account_settings") diff --git a/persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/repository/AccountRepository.java similarity index 61% rename from persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/repository/AccountRepository.java index dc57ffe6d3..929f3c6980 100644 --- a/persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/repository/AccountRepository.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/repository/AccountRepository.java @@ -1,8 +1,9 @@ -package com.baeldung.schemageneration.repository; +package com.baeldung.jpa.schemageneration.repository; -import com.baeldung.schemageneration.model.Account; import org.springframework.data.repository.CrudRepository; +import com.baeldung.jpa.schemageneration.model.Account; + public interface AccountRepository extends CrudRepository { Account findByName(String name); } diff --git a/persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/repository/AccountSettingRepository.java similarity index 63% rename from persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/repository/AccountSettingRepository.java index c2b8ff7398..f886bda704 100644 --- a/persistence-modules/spring-data-jpa-crud-2/src/main/java/com/baeldung/schemageneration/repository/AccountSettingRepository.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/schemageneration/repository/AccountSettingRepository.java @@ -1,8 +1,10 @@ -package com.baeldung.schemageneration.repository; +package com.baeldung.jpa.schemageneration.repository; -import com.baeldung.schemageneration.model.AccountSetting; import org.springframework.data.repository.CrudRepository; +import com.baeldung.jpa.schemageneration.model.AccountSetting; + public interface AccountSettingRepository extends CrudRepository { + AccountSetting findByAccountId(Long accountId); } diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/JpaApplication.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/JpaApplication.java new file mode 100644 index 0000000000..39efef714d --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/JpaApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.jpa.simple; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +@EnableJpaRepositories("com.baeldung.jpa.simple.repository") +public class JpaApplication { + + public static void main(String[] args) { + SpringApplication.run(JpaApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/config/PersistenceConfig.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/config/PersistenceConfig.java new file mode 100644 index 0000000000..36a1fa9389 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/config/PersistenceConfig.java @@ -0,0 +1,75 @@ +package com.baeldung.jpa.simple.config; + +import java.util.Properties; + +import javax.sql.DataSource; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.PropertySource; +import org.springframework.core.env.Environment; +import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.jpa.JpaTransactionManager; +import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; +import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import com.google.common.base.Preconditions; + +@Configuration +@PropertySource("classpath:persistence.properties") +@EnableTransactionManagement +//@ImportResource("classpath*:*springDataConfig.xml") +public class PersistenceConfig { + + @Autowired + private Environment env; + + @Bean + public LocalContainerEntityManagerFactoryBean entityManagerFactory() { + final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); + em.setDataSource(dataSource()); + em.setPackagesToScan("com.baeldung.jpa.simple.entity"); + + final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); + em.setJpaVendorAdapter(vendorAdapter); + em.setJpaProperties(additionalProperties()); + + return em; + } + + @Bean + public DataSource dataSource() { + final DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); + dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); + dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); + dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); + + return dataSource; + } + + @Bean + public PlatformTransactionManager transactionManager() { + final JpaTransactionManager transactionManager = new JpaTransactionManager(); + transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); + + return transactionManager; + } + + @Bean + public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { + return new PersistenceExceptionTranslationPostProcessor(); + } + + final Properties additionalProperties() { + final Properties hibernateProperties = new Properties(); + hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); + hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); + + return hibernateProperties; + } +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/entity/Book.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/entity/Book.java new file mode 100644 index 0000000000..0e01e983b5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/entity/Book.java @@ -0,0 +1,57 @@ +package com.baeldung.jpa.simple.entity; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; + +@Entity +public class Book { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String title; + private String author; + private String isbn; + + public Book() { + } + + public Book(String title, String author, String isbn) { + this.title = title; + this.author = author; + this.isbn = isbn; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getIsbn() { + return isbn; + } + + public void setIsbn(String isbn) { + this.isbn = isbn; + } +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/entity/Foo.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/entity/Foo.java new file mode 100644 index 0000000000..bf82ab61f7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/entity/Foo.java @@ -0,0 +1,77 @@ +package com.baeldung.jpa.simple.entity; + +import java.io.Serializable; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; + +@Entity +public class Foo implements Serializable { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + @Column(nullable = false) + private String name; + + public Foo() { + super(); + } + + public Foo(final String name) { + super(); + + this.name = name; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(final String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Foo other = (Foo) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + final StringBuilder builder = new StringBuilder(); + builder.append("Foo [name=").append(name).append("]"); + return builder.toString(); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/entity/User.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/entity/User.java similarity index 96% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/entity/User.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/entity/User.java index b5b5eb40b0..07759af0fb 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/entity/User.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/entity/User.java @@ -1,4 +1,4 @@ -package com.baeldung.derivedquery.entity; +package com.baeldung.jpa.simple.entity; import java.time.ZonedDateTime; diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookListRepository.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/BookListRepository.java similarity index 67% rename from persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookListRepository.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/BookListRepository.java index aec8347850..e1540c64bf 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookListRepository.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/BookListRepository.java @@ -1,10 +1,11 @@ -package com.baeldung.spring.data.jpa.listrepositories.repository; +package com.baeldung.jpa.simple.repository; + +import java.util.List; -import com.baeldung.spring.data.jpa.listrepositories.entity.Book; import org.springframework.data.repository.ListCrudRepository; import org.springframework.stereotype.Repository; -import java.util.List; +import com.baeldung.jpa.simple.entity.Book; @Repository public interface BookListRepository extends ListCrudRepository { diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepository.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/BookPagingAndSortingRepository.java similarity index 78% rename from persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepository.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/BookPagingAndSortingRepository.java index 1b37b0d1ef..cb519ed5ea 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepository.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/BookPagingAndSortingRepository.java @@ -1,12 +1,13 @@ -package com.baeldung.spring.data.jpa.listrepositories.repository; +package com.baeldung.jpa.simple.repository; + +import java.util.List; -import com.baeldung.spring.data.jpa.listrepositories.entity.Book; import org.springframework.data.domain.Pageable; import org.springframework.data.repository.ListCrudRepository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; -import java.util.List; +import com.baeldung.jpa.simple.entity.Book; @Repository public interface BookPagingAndSortingRepository extends PagingAndSortingRepository, ListCrudRepository { diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/IFooDAO.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/IFooDAO.java new file mode 100644 index 0000000000..d6d1d46122 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/IFooDAO.java @@ -0,0 +1,15 @@ +package com.baeldung.jpa.simple.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import com.baeldung.jpa.simple.entity.Foo; + +public interface IFooDAO extends JpaRepository { + + Foo findByName(String name); + + @Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)") + Foo retrieveByName(@Param("name") String name); +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/UserRepository.java similarity index 87% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java rename to persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/UserRepository.java index 7d4a208d26..cc13aac5db 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/derivedquery/repository/UserRepository.java +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/UserRepository.java @@ -1,15 +1,14 @@ -package com.baeldung.derivedquery.repository; - -import com.baeldung.derivedquery.entity.User; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; +package com.baeldung.jpa.simple.repository; import java.time.ZonedDateTime; import java.util.Collection; import java.util.List; -public interface UserRepository extends JpaRepository { +import org.springframework.data.jpa.repository.JpaRepository; + +import com.baeldung.jpa.simple.entity.User; + +public interface UserRepository extends JpaRepository, UserRepositoryCustom { List findByName(String name); @@ -58,9 +57,9 @@ public interface UserRepository extends JpaRepository { List findByNameOrderByName(String name); List findByNameOrderByNameDesc(String name); - + List findByNameIsNotNull(); - + List findByNameOrderByNameAsc(String name); } diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/UserRepositoryCustom.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/UserRepositoryCustom.java new file mode 100644 index 0000000000..8584f3f3bb --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/UserRepositoryCustom.java @@ -0,0 +1,16 @@ +package com.baeldung.jpa.simple.repository; + +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; + +import com.baeldung.jpa.simple.entity.User; + +public interface UserRepositoryCustom { + + List findUserByEmails(Set emails); + + List findAllUsersByPredicates(Collection> predicates); + +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/UserRepositoryCustomImpl.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/UserRepositoryCustomImpl.java new file mode 100644 index 0000000000..b60ca65d0a --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/repository/UserRepositoryCustomImpl.java @@ -0,0 +1,57 @@ +package com.baeldung.jpa.simple.repository; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import com.baeldung.jpa.simple.entity.User; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Path; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; + +public class UserRepositoryCustomImpl implements UserRepositoryCustom { + + @PersistenceContext + private EntityManager entityManager; + + @Override + public List findUserByEmails(Set emails) { + CriteriaBuilder cb = entityManager.getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(User.class); + Root user = query.from(User.class); + + Path emailPath = user.get("email"); + + List predicates = new ArrayList<>(); + for (String email : emails) { + + predicates.add(cb.like(emailPath, email)); + + } + query.select(user) + .where(cb.or(predicates.toArray(new Predicate[predicates.size()]))); + + return entityManager.createQuery(query) + .getResultList(); + } + + @Override + public List findAllUsersByPredicates(Collection> predicates) { + List allUsers = entityManager.createQuery("select u from User u", User.class) + .getResultList(); + Stream allUsersStream = allUsers.stream(); + for (java.util.function.Predicate predicate : predicates) { + allUsersStream = allUsersStream.filter(predicate); + } + + return allUsersStream.collect(Collectors.toList()); + } +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/service/FooService.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/service/FooService.java new file mode 100644 index 0000000000..f02c1eebad --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/service/FooService.java @@ -0,0 +1,19 @@ +package com.baeldung.jpa.simple.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.baeldung.jpa.simple.entity.Foo; +import com.baeldung.jpa.simple.repository.IFooDAO; + +@Service +public class FooService implements IFooService { + + @Autowired + private IFooDAO dao; + + @Override + public Foo create(Foo foo) { + return dao.save(foo); + } +} diff --git a/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/service/IFooService.java b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/service/IFooService.java new file mode 100644 index 0000000000..4fc56bde87 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/java/com/baeldung/jpa/simple/service/IFooService.java @@ -0,0 +1,7 @@ +package com.baeldung.jpa.simple.service; + +import com.baeldung.jpa.simple.entity.Foo; + +public interface IFooService { + Foo create(Foo foo); +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-simple/src/main/resources/aggregation.properties b/persistence-modules/spring-data-jpa-simple/src/main/resources/aggregation.properties new file mode 100644 index 0000000000..bb3bb903a4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/resources/aggregation.properties @@ -0,0 +1,3 @@ +spring.jpa.show-sql=false +spring.jpa.defer-datasource-initialization=true +spring.jpa.properties.hibernate.globally_quoted_identifiers=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-simple/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-simple/src/main/resources/application.properties new file mode 100644 index 0000000000..1a370121c5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/resources/application.properties @@ -0,0 +1,6 @@ +spring.jpa.show-sql=false +spring.jpa.defer-datasource-initialization=true +#MySql +#spring.datasource.url=jdbc:mysql://localhost:3306/baeldung +#spring.datasource.username=baeldung +#spring.datasource.password=baeldung \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-simple/src/main/resources/insert_users.sql b/persistence-modules/spring-data-jpa-simple/src/main/resources/insert_users.sql new file mode 100644 index 0000000000..e0aca9ac41 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/resources/insert_users.sql @@ -0,0 +1,8 @@ +insert into Users(name, creation_date, last_login_date, active, age, email, status) +values('John', PARSEDATETIME('01/01/2018', 'dd/MM/yyyy'), PARSEDATETIME('01/01/2020', 'dd/MM/yyyy'), 1, 23, 'john@email.com', 1); + +insert into Users(name, creation_date, last_login_date, active, age, email, status) +values('Bob', PARSEDATETIME('02/02/2019', 'dd/MM/yyyy'), PARSEDATETIME('02/02/2020', 'dd/MM/yyyy'), 1, 56, 'bob@email.com', 1); + +insert into Users(name, creation_date, last_login_date, active, age, email, status) +values('Cindy', PARSEDATETIME('02/02/2019', 'dd/MM/yyyy'), PARSEDATETIME('02/02/2020', 'dd/MM/yyyy'), 1, 18, 'cindy@email.com', 0); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-simple/src/main/resources/pagination-sorting-db.properties b/persistence-modules/spring-data-jpa-simple/src/main/resources/pagination-sorting-db.properties new file mode 100644 index 0000000000..82dd3b0025 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/resources/pagination-sorting-db.properties @@ -0,0 +1,6 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +product.jdbc.url=jdbc:h2:mem:spring_jpa_product;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS PRODUCTS +jdbc.user=sa +jdbc.pass=sa +hibernate.hbm2ddl.auto=create-drop diff --git a/persistence-modules/spring-data-jpa-simple/src/main/resources/persistence.properties b/persistence-modules/spring-data-jpa-simple/src/main/resources/persistence.properties new file mode 100644 index 0000000000..05cb7a13b9 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/resources/persistence.properties @@ -0,0 +1,9 @@ +# jdbc.X +jdbc.driverClassName=org.h2.Driver +jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1 +jdbc.user=sa +jdbc.pass=sa + +# hibernate.X +hibernate.hbm2ddl.auto=create-drop +hibernate.dialect=org.hibernate.dialect.H2Dialect diff --git a/persistence-modules/spring-data-jpa-crud-2/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-simple/src/main/resources/schema-generation.properties similarity index 98% rename from persistence-modules/spring-data-jpa-crud-2/src/main/resources/application.properties rename to persistence-modules/spring-data-jpa-simple/src/main/resources/schema-generation.properties index ead0df89a3..76ffe6932b 100644 --- a/persistence-modules/spring-data-jpa-crud-2/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa-simple/src/main/resources/schema-generation.properties @@ -1 +1 @@ -spring.jpa.properties.hibernate.globally_quoted_identifiers=true +spring.jpa.properties.hibernate.globally_quoted_identifiers=true \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-simple/src/main/resources/springDataConfig.xml b/persistence-modules/spring-data-jpa-simple/src/main/resources/springDataConfig.xml new file mode 100644 index 0000000000..12de60da73 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/main/resources/springDataConfig.xml @@ -0,0 +1,11 @@ + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/aggregation/SpringDataAggregateIntegrationTest.java similarity index 88% rename from persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java rename to persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/aggregation/SpringDataAggregateIntegrationTest.java index a73ad949db..0fbe94532a 100644 --- a/persistence-modules/spring-data-jpa-query/src/test/java/com/baeldung/aggregation/SpringDataAggregateIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/aggregation/SpringDataAggregateIntegrationTest.java @@ -1,23 +1,28 @@ -package com.baeldung.aggregation; - -import com.baeldung.aggregation.model.custom.CommentCount; -import com.baeldung.aggregation.model.custom.ICommentCount; -import com.baeldung.aggregation.repository.CommentRepository; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.List; +package com.baeldung.jpa.aggregation; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; +import java.util.List; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigurationPackage; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.jdbc.Sql; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.jpa.aggregation.model.custom.CommentCount; +import com.baeldung.jpa.aggregation.model.custom.ICommentCount; +import com.baeldung.jpa.aggregation.repository.CommentRepository; + @RunWith(SpringRunner.class) @DataJpaTest(showSql = false) @Sql(scripts = "/test-aggregation-data.sql") +@AutoConfigurationPackage(basePackages = "com.baeldung.jpa.aggregation") +@ContextConfiguration(classes = AggregationApplication.class) public class SpringDataAggregateIntegrationTest { @Autowired diff --git a/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/modifying/UserRepositoryCommonIntegrationTest.java b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/modifying/UserRepositoryCommonIntegrationTest.java new file mode 100644 index 0000000000..fd34d0116f --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/modifying/UserRepositoryCommonIntegrationTest.java @@ -0,0 +1,212 @@ +package com.baeldung.jpa.modifying; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.time.LocalDate; +import java.util.List; +import java.util.stream.Stream; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.data.domain.Sort; +import org.springframework.data.mapping.PropertyReferenceException; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.jpa.modifying.dao.UserRepository; +import com.baeldung.jpa.modifying.model.User; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.Query; + +@SpringBootTest(classes= ModifyingApplication.class) +class UserRepositoryCommonIntegrationTest { + + final String USER_EMAIL = "email@example.com"; + final String USER_EMAIL2 = "email2@example.com"; + final String USER_EMAIL3 = "email3@example.com"; + final String USER_EMAIL4 = "email4@example.com"; + final Integer INACTIVE_STATUS = 0; + final Integer ACTIVE_STATUS = 1; + final String USER_NAME_ADAM = "Adam"; + final String USER_NAME_PETER = "Peter"; + + @Autowired + protected UserRepository userRepository; + @Autowired + private EntityManager entityManager; + + @Test + @Transactional + void givenUsersWithSameNameInDB_WhenFindAllByName_ThenReturnStreamOfUsers() { + User user1 = new User(); + user1.setName(USER_NAME_ADAM); + user1.setEmail(USER_EMAIL); + userRepository.save(user1); + + User user2 = new User(); + user2.setName(USER_NAME_ADAM); + user2.setEmail(USER_EMAIL2); + userRepository.save(user2); + + User user3 = new User(); + user3.setName(USER_NAME_ADAM); + user3.setEmail(USER_EMAIL3); + userRepository.save(user3); + + User user4 = new User(); + user4.setName("SAMPLE"); + user4.setEmail(USER_EMAIL4); + userRepository.save(user4); + + try (Stream foundUsersStream = userRepository.findAllByName(USER_NAME_ADAM)) { + assertThat(foundUsersStream.count()).isEqualTo(3l); + } + } + + @Test + void givenUsersInDB_WhenFindAllWithSortByName_ThenReturnUsersSorted() { + userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); + + List usersSortByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); + + assertThat(usersSortByName.get(0) + .getName()).isEqualTo(USER_NAME_ADAM); + } + + @Test + void givenUsersInDB_WhenFindAllSortWithFunction_ThenThrowException() { + userRepository.save(new User(USER_NAME_ADAM, LocalDate.now(), USER_EMAIL, ACTIVE_STATUS)); + userRepository.save(new User(USER_NAME_PETER, LocalDate.now(), USER_EMAIL2, ACTIVE_STATUS)); + userRepository.save(new User("SAMPLE", LocalDate.now(), USER_EMAIL3, INACTIVE_STATUS)); + + userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); + + assertThrows(PropertyReferenceException.class, () -> userRepository.findAll(Sort.by("LENGTH(name)"))); + } + + @Test + @Transactional + void givenTwoUsers_whenFindByNameUsr01_ThenUserUsr01() { + User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + try (Stream users = userRepository.findAllByName("usr01")) { + assertTrue(users.allMatch(usr -> usr.equals(usr01))); + } + } + + @Test + @Transactional + void givenTwoUsers_whenFindByNameUsr00_ThenNoUsers() { + User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.now(), "usr02@baeldung.com", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + try (Stream users = userRepository.findAllByName("usr00")) { + assertEquals(0, users.count()); + } + } + + @Test + void givenTwoUsers_whenFindUsersWithGmailAddress_ThenUserUsr02() { + User usr01 = new User("usr01", LocalDate.now(), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.now(), "usr02@gmail.com", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + List users = userRepository.findUsersWithGmailAddress(); + assertEquals(1, users.size()); + assertEquals(usr02, users.get(0)); + } + + @Test + @Transactional + void givenTwoUsers_whenDeleteAllByCreationDateAfter_ThenOneUserRemains() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 1); + + userRepository.save(usr01); + userRepository.save(usr02); + + userRepository.deleteAllByCreationDateAfter(LocalDate.of(2018, 5, 1)); + + List users = userRepository.findAll(); + + assertEquals(1, users.size()); + assertEquals(usr01, users.get(0)); + } + + @Test + @Transactional + void givenTwoUsers_whenDeleteDeactivatedUsers_ThenUserUsr02Deleted() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + usr01.setLastLoginDate(LocalDate.now()); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 0); + usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); + usr02.setActive(false); + + userRepository.save(usr01); + userRepository.save(usr02); + + int deletedUsersCount = userRepository.deleteDeactivatedUsers(); + + List users = userRepository.findAll(); + assertEquals(1, users.size()); + assertEquals(usr01, users.get(0)); + assertEquals(1, deletedUsersCount); + } + + @Test + @Transactional + void givenTwoUsers_whenDeleteDeactivatedUsersWithNoModifyingAnnotation_ThenException() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + usr01.setLastLoginDate(LocalDate.now()); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.com", 0); + usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); + usr02.setActive(false); + + userRepository.save(usr01); + userRepository.save(usr02); + + assertThatThrownBy(() -> userRepository.deleteDeactivatedUsersWithNoModifyingAnnotation()) + .isInstanceOf(InvalidDataAccessApiUsageException.class); + } + + @Test + @Transactional + void givenTwoUsers_whenAddDeletedColumn_ThenUsersHaveDeletedColumn() { + User usr01 = new User("usr01", LocalDate.of(2018, 1, 1), "usr01@baeldung.com", 1); + usr01.setLastLoginDate(LocalDate.now()); + User usr02 = new User("usr02", LocalDate.of(2018, 6, 1), "usr02@baeldung.org", 1); + usr02.setLastLoginDate(LocalDate.of(2018, 7, 20)); + usr02.setActive(false); + + userRepository.save(usr01); + userRepository.save(usr02); + + userRepository.addDeletedColumn(); + + Query nativeQuery = entityManager.createNativeQuery("select deleted from USERS where NAME = 'usr01'"); + assertEquals(0, nativeQuery.getResultList().get(0)); + } + + @AfterEach + void cleanUp() { + userRepository.deleteAll(); + } +} diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/paginationsorting/ProductRepositoryIntegrationTest.java similarity index 79% rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/paginationsorting/ProductRepositoryIntegrationTest.java index 831790af95..861633242d 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/multipledb/ProductRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/paginationsorting/ProductRepositoryIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.multipledb; +package com.baeldung.jpa.paginationsorting; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; @@ -9,33 +9,30 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; -import com.baeldung.multipledb.dao.product.ProductRepository; -import com.baeldung.multipledb.model.product.Product; +import com.baeldung.jpa.paginationsorting.model.Product; +import com.baeldung.jpa.paginationsorting.repository.ProductRepository; -@RunWith(SpringRunner.class) -@SpringBootTest(classes=MultipleDbApplication.class) +@SpringBootTest(classes = PaginationSortingApplication.class) @EnableTransactionManagement -public class ProductRepositoryIntegrationTest { +class ProductRepositoryIntegrationTest { @Autowired private ProductRepository productRepository; - @Before + @BeforeEach @Transactional("productTransactionManager") - public void setUp() { + void setUp() { productRepository.save(Product.from(1001, "Book", 21)); productRepository.save(Product.from(1002, "Coffee", 10)); productRepository.save(Product.from(1003, "Jeans", 30)); @@ -44,7 +41,7 @@ public class ProductRepositoryIntegrationTest { } @Test - public void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { + void whenRequestingFirstPageOfSizeTwo_ThenReturnFirstPage() { Pageable pageRequest = PageRequest.of(0, 2); Page result = productRepository.findAll(pageRequest); @@ -57,7 +54,7 @@ public class ProductRepositoryIntegrationTest { } @Test - public void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { + void whenRequestingSecondPageOfSizeTwo_ThenReturnSecondPage() { Pageable pageRequest = PageRequest.of(1, 2); Page result = productRepository.findAll(pageRequest); @@ -70,7 +67,7 @@ public class ProductRepositoryIntegrationTest { } @Test - public void whenRequestingLastPage_ThenReturnLastPageWithRemData() { + void whenRequestingLastPage_ThenReturnLastPageWithRemData() { Pageable pageRequest = PageRequest.of(2, 2); Page result = productRepository.findAll(pageRequest); @@ -83,7 +80,7 @@ public class ProductRepositoryIntegrationTest { } @Test - public void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { + void whenSortingByNameAscAndPaging_ThenReturnSortedPagedResult() { Pageable pageRequest = PageRequest.of(0, 3, Sort.by("name")); Page result = productRepository.findAll(pageRequest); @@ -97,7 +94,7 @@ public class ProductRepositoryIntegrationTest { } @Test - public void whenSortingByPriceDescAndPaging_ThenReturnSortedPagedResult() { + void whenSortingByPriceDescAndPaging_ThenReturnSortedPagedResult() { Pageable pageRequest = PageRequest.of(0, 3, Sort.by("price") .descending()); @@ -112,7 +109,7 @@ public class ProductRepositoryIntegrationTest { } @Test - public void whenSortingByPriceDescAndNameAscAndPaging_ThenReturnSortedPagedResult() { + void whenSortingByPriceDescAndNameAscAndPaging_ThenReturnSortedPagedResult() { Pageable pageRequest = PageRequest.of(0, 5, Sort.by("price") .descending() .and(Sort.by("name"))); @@ -128,7 +125,7 @@ public class ProductRepositoryIntegrationTest { } @Test - public void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { + void whenRequestingFirstPageOfSizeTwoUsingCustomMethod_ThenReturnFirstPage() { Pageable pageRequest = PageRequest.of(0, 2); List result = productRepository.findAllByPrice(10, pageRequest); diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/projection/JpaProjectionIntegrationTest.java similarity index 67% rename from persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java rename to persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/projection/JpaProjectionIntegrationTest.java index 5fdcf6a787..a112b18721 100644 --- a/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/projection/JpaProjectionIntegrationTest.java @@ -1,23 +1,26 @@ -package com.baeldung.projection; - -import com.baeldung.projection.model.Person; -import com.baeldung.projection.repository.AddressRepository; -import com.baeldung.projection.repository.PersonRepository; -import com.baeldung.projection.view.AddressView; -import com.baeldung.projection.view.PersonDto; -import com.baeldung.projection.view.PersonView; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.test.context.jdbc.Sql; +package com.baeldung.jpa.projection; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigurationPackage; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.context.jdbc.Sql; + +import com.baeldung.jpa.projection.model.Person; +import com.baeldung.jpa.projection.repository.AddressRepository; +import com.baeldung.jpa.projection.repository.PersonRepository; +import com.baeldung.jpa.projection.view.AddressView; +import com.baeldung.jpa.projection.view.PersonDto; +import com.baeldung.jpa.projection.view.PersonView; + @DataJpaTest @Sql(scripts = "/projection-insert-data.sql") @Sql(scripts = "/projection-clean-up-data.sql", executionPhase = AFTER_TEST_METHOD) -public class JpaProjectionIntegrationTest { +@AutoConfigurationPackage(basePackages = "com.baeldung.jpa.projection") +class JpaProjectionIntegrationTest { @Autowired private AddressRepository addressRepository; @@ -25,7 +28,7 @@ public class JpaProjectionIntegrationTest { private PersonRepository personRepository; @Test - public void whenUsingClosedProjections_thenViewWithRequiredPropertiesIsReturned() { + void whenUsingClosedProjections_thenViewWithRequiredPropertiesIsReturned() { AddressView addressView = addressRepository.getAddressByState("CA").get(0); assertThat(addressView.getZipCode()).isEqualTo("90001"); @@ -35,20 +38,20 @@ public class JpaProjectionIntegrationTest { } @Test - public void whenUsingOpenProjections_thenViewWithRequiredPropertiesIsReturned() { + void whenUsingOpenProjections_thenViewWithRequiredPropertiesIsReturned() { PersonView personView = personRepository.findByLastName("Doe"); assertThat(personView.getFullName()).isEqualTo("John Doe"); } @Test - public void whenUsingClassBasedProjections_thenDtoWithRequiredPropertiesIsReturned() { + void whenUsingClassBasedProjections_thenDtoWithRequiredPropertiesIsReturned() { PersonDto personDto = personRepository.findByFirstName("John"); assertThat(personDto.getFirstName()).isEqualTo("John"); assertThat(personDto.getLastName()).isEqualTo("Doe"); } @Test - public void whenUsingDynamicProjections_thenObjectWithRequiredPropertiesIsReturned() { + void whenUsingDynamicProjections_thenObjectWithRequiredPropertiesIsReturned() { Person person = personRepository.findByLastName("Doe", Person.class); PersonView personView = personRepository.findByLastName("Doe", PersonView.class); PersonDto personDto = personRepository.findByLastName("Doe", PersonDto.class); diff --git a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/query/UserQueryRepositoryIntegrationTest.java similarity index 81% rename from persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/query/UserQueryRepositoryIntegrationTest.java index 19760f2bfe..2c85b3b1b3 100644 --- a/persistence-modules/spring-data-jpa-query-2/src/test/java/com/baeldung/spring/data/jpa/query/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/query/UserQueryRepositoryIntegrationTest.java @@ -1,26 +1,25 @@ -package com.baeldung.spring.data.jpa.query; +package com.baeldung.jpa.query; -import org.junit.Test; -import org.junit.runner.RunWith; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.AutoConfigurationPackage; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.JpaSort; import org.springframework.data.mapping.PropertyReferenceException; -import org.springframework.test.context.junit4.SpringRunner; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -@RunWith(SpringRunner.class) @DataJpaTest(properties = "spring.sql.init.data-locations=classpath:insert_users.sql", showSql = false) -public class UserRepositoryIntegrationTest { +@AutoConfigurationPackage(basePackages = "com.baeldung.jpa.query") +class UserQueryRepositoryIntegrationTest { @Autowired private UserRepository userRepository; @@ -40,47 +39,43 @@ public class UserRepositoryIntegrationTest { @Test public void whenFindAllSortedByNameThenAllSorted() { List allUsersSortedByName = userRepository.findAll(Sort.by(Sort.Direction.ASC, "name")); - assertThat(allUsersSortedByName) - .extracting("name") - .containsSequence("Bob", "Cindy", "John"); + assertThat(allUsersSortedByName).extracting("name") + .containsSequence("Bob", "Cindy", "John"); } @Test public void whenFindAllSortedByNameLengthThenException() { - assertThatThrownBy(() -> userRepository.findAll(Sort.by("LENGTH(name)"))) - .isInstanceOf(PropertyReferenceException.class); + assertThatThrownBy(() -> userRepository.findAll(Sort.by("LENGTH(name)"))).isInstanceOf(PropertyReferenceException.class); } @Test public void whenFindAllUsersSortedByNameThenAllSorted() { List allUsersSortedByName = userRepository.findAllUsers(Sort.by(Sort.Direction.ASC, "name")); - assertThat(allUsersSortedByName) - .extracting("name") - .containsSequence("Bob", "Cindy", "John"); + assertThat(allUsersSortedByName).extracting("name") + .containsSequence("Bob", "Cindy", "John"); } @Test public void whenFindAllUsersSortedByNameLengthThenAllSorted() { List allUsersSortedByName = userRepository.findAllUsers(JpaSort.unsafe("LENGTH(name)")); - assertThat(allUsersSortedByName) - .extracting("name") - .containsSequence("Bob", "John", "Cindy"); + assertThat(allUsersSortedByName).extracting("name") + .containsSequence("Bob", "John", "Cindy"); } @Test public void whenFindAllUsersWithPaginationThenPaginated() { Page page = userRepository.findAllUsersWithPagination(PageRequest.of(0, 1)); - assertThat(page.stream().map(User::getId)) - .hasSize(1) - .containsOnly(1); + assertThat(page.stream() + .map(User::getId)).hasSize(1) + .containsOnly(1); } @Test public void whenFindAllUsersWithPaginationNativeThenPaginated() { Page page = userRepository.findAllUsersWithPaginationNative(PageRequest.of(1, 1)); - assertThat(page.stream().map(User::getId)) - .hasSize(1) - .containsOnly(2); + assertThat(page.stream() + .map(User::getId)).hasSize(1) + .containsOnly(2); } @Test @@ -126,9 +121,8 @@ public class UserRepositoryIntegrationTest { @Test public void whenFindUserByNameListThenAllFound() { List users = userRepository.findUserByNameList(Arrays.asList("Bob", "Cindy")); - assertThat(users) - .extracting("name") - .containsOnly("Bob", "Cindy"); + assertThat(users).extracting("name") + .containsOnly("Bob", "Cindy"); } @Test diff --git a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookListRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/simple/BookListRepositoryIntegrationTest.java similarity index 70% rename from persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookListRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/simple/BookListRepositoryIntegrationTest.java index d004d485e4..ec2ada1e52 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookListRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/simple/BookListRepositoryIntegrationTest.java @@ -1,22 +1,24 @@ -package com.baeldung.spring.data.jpa.listrepositories.repository; +package com.baeldung.jpa.simple; + +import java.util.Arrays; +import java.util.List; -import com.baeldung.spring.data.jpa.listrepositories.entity.Book; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import java.util.Arrays; -import java.util.List; +import com.baeldung.jpa.simple.entity.Book; +import com.baeldung.jpa.simple.repository.BookListRepository; -@SpringBootTest -public class BookListRepositoryIntegrationTest { +@SpringBootTest(classes = JpaApplication.class) +class BookListRepositoryIntegrationTest { @Autowired private BookListRepository bookListRepository; @Test - public void givenDbContainsBooks_whenFindBooksByAuthor_thenReturnBooksByAuthor() { + void givenDbContainsBooks_whenFindBooksByAuthor_thenReturnBooksByAuthor() { Book book1 = new Book("Spring Data", "John Doe", "1234567890"); Book book2 = new Book("Spring Data 2", "John Doe", "1234567891"); Book book3 = new Book("Spring Data 3", "John Doe", "1234567892"); diff --git a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/simple/BookPagingAndSortingRepositoryIntegrationTest.java similarity index 76% rename from persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/simple/BookPagingAndSortingRepositoryIntegrationTest.java index 9ea865c04f..d5c8c1bca0 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/simple/BookPagingAndSortingRepositoryIntegrationTest.java @@ -1,7 +1,8 @@ -package com.baeldung.spring.data.jpa.listrepositories.repository; +package com.baeldung.jpa.simple; + +import java.util.Arrays; +import java.util.List; -import com.baeldung.spring.data.jpa.listrepositories.entity.Book; -import com.baeldung.spring.data.jpa.listrepositories.repository.BookPagingAndSortingRepository; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -10,17 +11,17 @@ import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; -import java.util.Arrays; -import java.util.List; +import com.baeldung.jpa.simple.entity.Book; +import com.baeldung.jpa.simple.repository.BookPagingAndSortingRepository; @SpringBootTest -public class BookPagingAndSortingRepositoryIntegrationTest { +class BookPagingAndSortingRepositoryIntegrationTest { @Autowired private BookPagingAndSortingRepository bookPagingAndSortingRepository; @Test - public void givenDbContainsBooks_whenfindBooksByAuthor_thenReturnBooksByAuthor() { + void givenDbContainsBooks_whenfindBooksByAuthor_thenReturnBooksByAuthor() { Book book1 = new Book("Spring Data", "John Miller", "1234567890"); Book book2 = new Book("Spring Data 2", "John Miller", "1234567891"); Book book3 = new Book("Spring Data 3", "John Miller", "1234567892"); diff --git a/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/simple/FooServiceIntegrationTest.java b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/simple/FooServiceIntegrationTest.java new file mode 100644 index 0000000000..7e2dd98ada --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/simple/FooServiceIntegrationTest.java @@ -0,0 +1,31 @@ +package com.baeldung.jpa.simple; + +import javax.sql.DataSource; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.jpa.simple.entity.Foo; +import com.baeldung.jpa.simple.service.IFooService; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { JpaApplication.class}) +@DirtiesContext +public class FooServiceIntegrationTest { + + @Autowired + private IFooService service; + + @Autowired + private DataSource dataSource; + + @Test(expected = DataIntegrityViolationException.class) + public final void whenInvalidEntityIsCreated_thenDataException() { + service.create(new Foo()); + } +} diff --git a/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/simple/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/simple/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..37afc90b59 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/test/java/com/baeldung/jpa/simple/UserRepositoryIntegrationTest.java @@ -0,0 +1,191 @@ +package com.baeldung.jpa.simple; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.jpa.simple.entity.User; +import com.baeldung.jpa.simple.repository.UserRepository; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = JpaApplication.class) +class UserRepositoryIntegrationTest { + + private static final String USER_NAME_ADAM = "Adam"; + private static final String USER_NAME_EVE = "Eve"; + private static final ZonedDateTime BIRTHDATE = ZonedDateTime.now(); + + @Autowired + private UserRepository userRepository; + + @BeforeEach + public void setUp() { + + User user1 = new User(USER_NAME_ADAM, 25, BIRTHDATE, true); + User user2 = new User(USER_NAME_ADAM, 20, BIRTHDATE, false); + User user3 = new User(USER_NAME_EVE, 20, BIRTHDATE, true); + User user4 = new User(null, 30, BIRTHDATE, false); + + userRepository.saveAll(Arrays.asList(user1, user2, user3, user4)); + } + + @AfterEach + public void tearDown() { + + userRepository.deleteAll(); + } + + @Test + void whenFindByName_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByName(USER_NAME_ADAM) + .size()); + } + + @Test + void whenFindByNameIsNull_thenReturnsCorrectResult() { + + assertEquals(1, userRepository.findByNameIsNull() + .size()); + } + + @Test + void whenFindByNameNot_thenReturnsCorrectResult() { + + assertEquals(USER_NAME_EVE, userRepository.findByNameNot(USER_NAME_ADAM) + .get(0) + .getName()); + } + + @Test + void whenFindByNameStartingWith_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByNameStartingWith("A") + .size()); + } + + @Test + void whenFindByNameEndingWith_thenReturnsCorrectResult() { + + assertEquals(1, userRepository.findByNameEndingWith("e") + .size()); + } + + @Test + void whenByNameContaining_thenReturnsCorrectResult() { + + assertEquals(1, userRepository.findByNameContaining("v") + .size()); + } + + @Test + void whenByNameLike_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByNameEndingWith("m") + .size()); + } + + @Test + void whenByAgeLessThan_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByAgeLessThan(25) + .size()); + } + + @Test + void whenByAgeLessThanEqual_thenReturnsCorrectResult() { + + assertEquals(3, userRepository.findByAgeLessThanEqual(25) + .size()); + } + + @Test + void whenByAgeGreaterThan_thenReturnsCorrectResult() { + + assertEquals(1, userRepository.findByAgeGreaterThan(25) + .size()); + } + + @Test + void whenByAgeGreaterThanEqual_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByAgeGreaterThanEqual(25) + .size()); + } + + @Test + void whenByAgeBetween_thenReturnsCorrectResult() { + + assertEquals(4, userRepository.findByAgeBetween(20, 30) + .size()); + } + + @Test + void whenByBirthDateAfter_thenReturnsCorrectResult() { + + final ZonedDateTime yesterday = BIRTHDATE.minusDays(1); + assertEquals(4, userRepository.findByBirthDateAfter(yesterday) + .size()); + } + + @Test + void whenByBirthDateBefore_thenReturnsCorrectResult() { + + final ZonedDateTime yesterday = BIRTHDATE.minusDays(1); + assertEquals(0, userRepository.findByBirthDateBefore(yesterday) + .size()); + } + + @Test + void whenByActiveTrue_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByActiveTrue() + .size()); + } + + @Test + void whenByActiveFalse_thenReturnsCorrectResult() { + + assertEquals(2, userRepository.findByActiveFalse() + .size()); + } + + @Test + void whenByAgeIn_thenReturnsCorrectResult() { + + final List ages = Arrays.asList(20, 25); + assertEquals(3, userRepository.findByAgeIn(ages) + .size()); + } + + @Test + void whenByNameOrAge() { + + assertEquals(3, userRepository.findByNameOrAge(USER_NAME_ADAM, 20) + .size()); + } + + @Test + void whenByNameOrAgeAndActive() { + + assertEquals(2, userRepository.findByNameOrAgeAndActive(USER_NAME_ADAM, 20, false) + .size()); + } + + @Test + void whenByNameOrderByName() { + + assertEquals(2, userRepository.findByNameOrderByName(USER_NAME_ADAM) + .size()); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-simple/src/test/resources/logback-test.xml b/persistence-modules/spring-data-jpa-simple/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/persistence-modules/spring-data-jpa-simple/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/resources/projection-clean-up-data.sql b/persistence-modules/spring-data-jpa-simple/src/test/resources/projection-clean-up-data.sql similarity index 100% rename from persistence-modules/spring-data-jpa-filtering/src/test/resources/projection-clean-up-data.sql rename to persistence-modules/spring-data-jpa-simple/src/test/resources/projection-clean-up-data.sql diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/resources/projection-insert-data.sql b/persistence-modules/spring-data-jpa-simple/src/test/resources/projection-insert-data.sql similarity index 100% rename from persistence-modules/spring-data-jpa-filtering/src/test/resources/projection-insert-data.sql rename to persistence-modules/spring-data-jpa-simple/src/test/resources/projection-insert-data.sql diff --git a/persistence-modules/spring-data-jpa-query/src/test/resources/test-aggregation-data.sql b/persistence-modules/spring-data-jpa-simple/src/test/resources/test-aggregation-data.sql similarity index 100% rename from persistence-modules/spring-data-jpa-query/src/test/resources/test-aggregation-data.sql rename to persistence-modules/spring-data-jpa-simple/src/test/resources/test-aggregation-data.sql diff --git a/persistence-modules/spring-data-mongodb-2/src/main/resources/logback.xml b/persistence-modules/spring-data-mongodb-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..08ed142f40 --- /dev/null +++ b/persistence-modules/spring-data-mongodb-2/src/main/resources/logback.xml @@ -0,0 +1,16 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index f9e4efaaed..a9b80de9c4 100644 --- a/pom.xml +++ b/pom.xml @@ -660,6 +660,7 @@ apache-httpclient4 apache-httpclient apache-kafka-2 + apache-kafka-3 apache-kafka apache-libraries-2 apache-libraries @@ -755,7 +756,7 @@ lombok-modules lucene mapstruct - + maven-modules mesos-marathon messaging-modules metrics @@ -805,6 +806,7 @@ spring-cloud-modules/spring-cloud-security spring-cloud-modules/spring-cloud-zuul-eureka-integration + spring-cloud-modules/spring-cloud-bootstrap spring-core-2 spring-core-3 spring-core-4 @@ -825,14 +827,14 @@ spring-kafka-2 spring-kafka-3 spring-kafka - spring-katharsis + spring-katharsis spring-mobile spring-native spring-protobuf spring-pulsar spring-quartz spring-reactive-modules - spring-remoting-modules + spring-remoting-modules spring-scheduling spring-security-modules spring-shell @@ -906,6 +908,7 @@ apache-httpclient4 apache-httpclient apache-kafka-2 + apache-kafka-3 apache-kafka apache-libraries-2 apache-libraries @@ -1002,7 +1005,7 @@ lombok-modules lucene mapstruct - + maven-modules mesos-marathon messaging-modules metrics @@ -1052,6 +1055,7 @@ spring-cloud-modules/spring-cloud-security spring-cloud-modules/spring-cloud-zuul-eureka-integration + spring-cloud-modules/spring-cloud-bootstrap spring-core-2 spring-core-3 spring-core-4 @@ -1072,14 +1076,14 @@ spring-kafka-2 spring-kafka-3 spring-kafka - spring-katharsis + spring-katharsis spring-mobile spring-native spring-protobuf spring-pulsar spring-quartz spring-reactive-modules - spring-remoting-modules + spring-remoting-modules spring-scheduling spring-security-modules spring-shell diff --git a/rxjava-modules/pom.xml b/rxjava-modules/pom.xml index 7bdfd0a9c1..e7c0b88613 100644 --- a/rxjava-modules/pom.xml +++ b/rxjava-modules/pom.xml @@ -49,11 +49,6 @@ awaitility ${awaitility.version} - - com.google.guava - guava - ${guava.version} - diff --git a/rxjava-modules/rxjava-core/pom.xml b/rxjava-modules/rxjava-core/pom.xml index 73ab98288d..247d64cc5c 100644 --- a/rxjava-modules/rxjava-core/pom.xml +++ b/rxjava-modules/rxjava-core/pom.xml @@ -13,4 +13,12 @@ 0.0.1-SNAPSHOT + + + com.google.guava + guava + ${guava.version} + + + \ No newline at end of file diff --git a/security-modules/sql-injection-samples/pom.xml b/security-modules/sql-injection-samples/pom.xml index 37779e0d14..f842c0af0a 100644 --- a/security-modules/sql-injection-samples/pom.xml +++ b/security-modules/sql-injection-samples/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -25,6 +25,11 @@ derby runtime + + org.apache.derby + derbytools + runtime + org.springframework.boot spring-boot-configuration-processor @@ -46,8 +51,9 @@ spring-boot-starter-data-jpa - org.hibernate + org.hibernate.orm hibernate-jpamodelgen + ${hibernate-jpamodelgen.version} org.springframework.boot @@ -64,4 +70,9 @@ + + 17 + 6.4.4.Final + + \ No newline at end of file diff --git a/security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/Account.java b/security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/Account.java index 3f077d5592..a2bb1765f2 100644 --- a/security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/Account.java +++ b/security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/Account.java @@ -5,11 +5,11 @@ package com.baeldung.examples.security.sql; import java.math.BigDecimal; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; import lombok.Data; diff --git a/security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java b/security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java index c7285e5fd3..e273924031 100644 --- a/security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java +++ b/security-modules/sql-injection-samples/src/main/java/com/baeldung/examples/security/sql/AccountDAO.java @@ -9,7 +9,6 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.AbstractMap; import java.util.ArrayList; -import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -17,18 +16,17 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; -import javax.persistence.EntityManager; -import javax.persistence.Query; -import javax.persistence.TypedQuery; -import javax.persistence.criteria.CriteriaBuilder; -import javax.persistence.criteria.CriteriaQuery; -import javax.persistence.criteria.Order; -import javax.persistence.criteria.Root; -import javax.persistence.metamodel.SingularAttribute; import javax.sql.DataSource; import org.springframework.stereotype.Component; +import jakarta.persistence.EntityManager; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Root; +import jakarta.persistence.metamodel.SingularAttribute; + /** * @author Philippe * diff --git a/security-modules/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java b/security-modules/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java index f61b738abc..ba0bc09343 100644 --- a/security-modules/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java +++ b/security-modules/sql-injection-samples/src/test/java/com/baeldung/examples/security/sql/SqlInjectionSamplesApplicationUnitTest.java @@ -75,7 +75,7 @@ public class SqlInjectionSamplesApplicationUnitTest { } @Test(expected = IllegalArgumentException.class) - public void givenASafeMethod_whenInvalidOrderBy_thenThroweException() { + public void givenASafeMethod_whenInvalidOrderBy_thenThrowException() { target.safeFindAccountsByCustomerId("C1", "INVALID"); } diff --git a/security-modules/sql-injection-samples/src/test/resources/application-test.yml b/security-modules/sql-injection-samples/src/test/resources/application-test.yml index 3af3f58bff..4c5d6bd853 100644 --- a/security-modules/sql-injection-samples/src/test/resources/application-test.yml +++ b/security-modules/sql-injection-samples/src/test/resources/application-test.yml @@ -11,7 +11,8 @@ spring: datasource: initialization-mode: embedded - + driver-class-name: org.apache.derby.jdbc.EmbeddedDriver + logging: level: sql: DEBUG diff --git a/spring-5/README.md b/spring-5/README.md index 6649a392db..d1487913ac 100644 --- a/spring-5/README.md +++ b/spring-5/README.md @@ -11,3 +11,4 @@ This module contains articles about Spring 5 - [Spring Assert Statements](https://www.baeldung.com/spring-assert) - [Difference between context:annotation-config vs context:component-scan](https://www.baeldung.com/spring-contextannotation-contextcomponentscan) - [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) +- [Document Query Parameters with Spring REST Docs](https://www.baeldung.com/spring-rest-document-query-parameters) 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-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java b/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java index 311bd828cb..9822d10828 100644 --- a/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java +++ b/spring-batch/src/test/java/com/baeldung/batchtesting/SpringBatchStepScopeIntegrationTest.java @@ -3,12 +3,15 @@ package com.baeldung.batchtesting; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.batch.test.AssertFile.assertFileEquals; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; import java.util.List; -import com.baeldung.batchtesting.model.Book; -import com.baeldung.batchtesting.model.BookRecord; - import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; @@ -25,13 +28,15 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.core.io.FileSystemResource; import org.springframework.test.context.ContextConfiguration; +import com.baeldung.batchtesting.model.Book; +import com.baeldung.batchtesting.model.BookRecord; @SpringBatchTest @EnableAutoConfiguration @ContextConfiguration(classes = { SpringBatchConfiguration.class }) public class SpringBatchStepScopeIntegrationTest { - private static final String TEST_OUTPUT = "src/test/resources/output/actual-output.json"; + private static String TEST_OUTPUT = "src/test/resources/output/actual-output.json"; private static final String EXPECTED_OUTPUT_ONE = "src/test/resources/output/expected-output-one.json"; @@ -45,6 +50,13 @@ public class SpringBatchStepScopeIntegrationTest { @Autowired private JobRepositoryTestUtils jobRepositoryTestUtils; + @BeforeAll + public static void setup() throws IOException { + final File tempFile = Files.createTempFile("actual-output", ".json").toFile(); + Files.copy(Paths.get(TEST_OUTPUT), Paths.get(tempFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); + TEST_OUTPUT = tempFile.getAbsolutePath(); + } + private JobParameters defaultJobParameters() { JobParametersBuilder paramsBuilder = new JobParametersBuilder(); paramsBuilder.addString("file.input", TEST_INPUT_ONE); diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 4504aff083..3be66dc168 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,20 +66,20 @@ 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 spring-boot-swagger-keycloak spring-boot-swagger-springfox - - + spring-boot-testing + spring-boot-testing-2 spring-boot-testing-spock spring-boot-vue spring-boot-actuator @@ -90,14 +90,14 @@ spring-boot-cassandre - + spring-boot-react spring-boot-3-grpc spring-boot-3-observation spring-boot-3-test-pitfalls spring-boot-3-testcontainers - + spring-boot-3-2 spring-boot-resilience4j spring-boot-properties spring-boot-properties-2 diff --git a/spring-boot-modules/spring-boot-3-2/pom.xml b/spring-boot-modules/spring-boot-3-2/pom.xml index 29ad9898fb..29d9332ca5 100644 --- a/spring-boot-modules/spring-boot-3-2/pom.xml +++ b/spring-boot-modules/spring-boot-3-2/pom.xml @@ -196,6 +196,11 @@ io.zipkin.reporter2 zipkin-sender-urlconnection + + io.swagger.core.v3 + swagger-core + 2.2.20 + @@ -290,7 +295,7 @@ com.baeldung.restclient.RestClientApplication 1.6.0.Beta1 - 2.0.0 + 2.3.0 3.0.0-M7 5.14.0 0.2.0 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 95% 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 3e12215bcb..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 @@ -15,13 +15,15 @@ import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpStatusCode; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.test.context.TestPropertySource; import org.springframework.web.client.RestClient; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -public class RestClientIntegrationTest { +@TestPropertySource(locations="classpath:connectiondetails/application-r2dbc.properties") +public class RestClientLiveTest { @LocalServerPort private int port; @@ -110,7 +112,7 @@ public class RestClientIntegrationTest { .uri(uriBase + "/articles/1234") .retrieve() .onStatus(status -> status.value() == 404, (request, response) -> { throw new ArticleNotFoundException(); }) - .body(new ParameterizedTypeReference<>() {}); + .body(new ParameterizedTypeReference() {}); }).isInstanceOf(ArticleNotFoundException.class); } diff --git a/spring-boot-modules/spring-boot-3/README.md b/spring-boot-modules/spring-boot-3/README.md index ff00a506cf..cc3ec77335 100644 --- a/spring-boot-modules/spring-boot-3/README.md +++ b/spring-boot-modules/spring-boot-3/README.md @@ -8,5 +8,5 @@ - [HTTP Interface in Spring 6](https://www.baeldung.com/spring-6-http-interface) - [Working with Virtual Threads in Spring 6](https://www.baeldung.com/spring-6-virtual-threads) - [Docker Compose Support in Spring Boot 3](https://www.baeldung.com/ops/docker-compose-support-spring-boot) - +- [The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring](https://www.baeldung.com/spring-5-junit-config) - More articles: [[next -->]](/spring-boot-modules/spring-boot-3-2) 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/Java8Condition.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/Java8Condition.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17Condition.java index c5f5e16d52..cdf6cfde58 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/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 Java8Condition implements Condition { +public class Java17Condition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - return ConditionalUtils.isJava8(); + 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/Java9Condition.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/Java9Condition.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java21Condition.java index 2afa8b25a7..ec0f3a499e 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/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 Java9Condition implements Condition { +public class Java21Condition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - return ConditionalUtils.isJava9(); + 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/Java8ConditionUnitTest.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/Java8ConditionUnitTest.java rename to spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java17ConditionUnitTest.java index 0d1b1eded6..560cd5537d 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/Java17ConditionUnitTest.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 Java17ConditionUnitTest { @Test - public void whenOnJava8_thenJava8ConditionShouldPass() { + public void whenOnJava17_thenJava7ConditionShouldPass() { try (MockedStatic theMock = Mockito.mockStatic(ConditionalUtils.class)) { - theMock.when(ConditionalUtils::isJava8) + theMock.when(ConditionalUtils::isJava17) .thenReturn(true); Assertions.assertTrue( - new Java8Condition().matches( + new Java17Condition().matches( Mockito.mock(ConditionContext.class), Mockito.mock(AnnotatedTypeMetadata.class) ) ); @@ -24,12 +24,12 @@ public class Java8ConditionUnitTest { } @Test - public void whenNotOnJava8_thenJava8ConditionShouldNotPass() { + public void whenNotOnJava17_thenJava17ConditionShouldNotPass() { try (MockedStatic theMock = Mockito.mockStatic(ConditionalUtils.class)) { - theMock.when(ConditionalUtils::isJava8) + theMock.when(ConditionalUtils::isJava17) .thenReturn(false); Assertions.assertFalse( - new Java8Condition().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/Java9ConditionUnitTest.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/Java9ConditionUnitTest.java rename to spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java21ConditionUnitTest.java index ce277e81fe..397f95c16c 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/Java21ConditionUnitTest.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 Java21ConditionUnitTest { @Test - public void whenOnJava9_thenJava9ConditionShouldPass() { + public void whenOnJava21_thenJava21ConditionShouldPass() { try (MockedStatic theMock = Mockito.mockStatic(ConditionalUtils.class)) { - theMock.when(ConditionalUtils::isJava9) + theMock.when(ConditionalUtils::isJava21) .thenReturn(true); Assertions.assertTrue( - new Java9Condition().matches( + new Java21Condition().matches( Mockito.mock(ConditionContext.class), Mockito.mock(AnnotatedTypeMetadata.class) ) ); @@ -24,12 +24,12 @@ public class Java9ConditionUnitTest { } @Test - public void whenNotOnJava9_thenJava9ConditionShouldNotPass() { + public void whenNotOnJava21_thenJava21ConditionShouldNotPass() { try (MockedStatic theMock = Mockito.mockStatic(ConditionalUtils.class)) { - theMock.when(ConditionalUtils::isJava9) + theMock.when(ConditionalUtils::isJava21) .thenReturn(false); Assertions.assertFalse( - new Java9Condition().matches( + new Java21Condition().matches( Mockito.mock(ConditionContext.class), Mockito.mock(AnnotatedTypeMetadata.class) ) ); diff --git a/spring-boot-modules/spring-boot-artifacts/pom.xml b/spring-boot-modules/spring-boot-artifacts/pom.xml index e39ddb5af1..e0e745f72c 100644 --- a/spring-boot-modules/spring-boot-artifacts/pom.xml +++ b/spring-boot-modules/spring-boot-artifacts/pom.xml @@ -51,11 +51,6 @@ javax.persistence-api ${jpa.version} - - com.google.guava - guava - ${guava.version} - org.subethamail subethasmtp diff --git a/spring-boot-modules/spring-boot-basic-customization-3/README.md b/spring-boot-modules/spring-boot-basic-customization-3/README.md new file mode 100644 index 0000000000..2641427608 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/README.md @@ -0,0 +1,5 @@ +## Spring Boot Basic Customization 3 + +This module contains articles about Spring Boot customization 3 + +### Relevant Articles: \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization-3/pom.xml b/spring-boot-modules/spring-boot-basic-customization-3/pom.xml new file mode 100644 index 0000000000..1b09162cf4 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + spring-boot-basic-customization-3 + spring-boot-basic-customization-3 + jar + Module For Spring Boot Basic Customization 3 + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + springStartupApp + com.baeldung.springStart.SpringStartApplication + + + + + repackage + + + + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/AppConfig.java b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/AppConfig.java new file mode 100644 index 0000000000..f90c7b2889 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/AppConfig.java @@ -0,0 +1,30 @@ +package com.baeldung.filter; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.DelegatingFilterProxy; + +@Configuration +public class AppConfig { + + @Bean + public FilterRegistrationBean loggingFilterDelegatingProxy() { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(new DelegatingFilterProxy("loggingFilterDelegateProxy")); + registrationBean.addUrlPatterns("/*"); + return registrationBean; + } + + @Bean + @Autowired + public FilterRegistrationBean loggingFilterRegistration(LoggingService loggingService) { + FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); + registrationBean.setFilter(new LoggingFilterRegistrationBean(loggingService)); + registrationBean.addUrlPatterns("/*"); + return registrationBean; + } + + +} diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingFilterAutowiringSupport.java b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingFilterAutowiringSupport.java new file mode 100644 index 0000000000..6aaf521ee8 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingFilterAutowiringSupport.java @@ -0,0 +1,35 @@ +package com.baeldung.filter; + +import java.io.IOException; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; + +@Component +public class LoggingFilterAutowiringSupport implements Filter { + + @Autowired + LoggingService loggingService; + + @Override + public void init(FilterConfig filterConfig) { + SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, + filterConfig.getServletContext()); + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; + loggingService.log(httpServletRequest.getMethod(), httpServletRequest.getRequestURI()); + filterChain.doFilter(servletRequest, servletResponse); + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingFilterDelegatingFilterProxy.java b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingFilterDelegatingFilterProxy.java new file mode 100644 index 0000000000..84f0477379 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingFilterDelegatingFilterProxy.java @@ -0,0 +1,27 @@ +package com.baeldung.filter; + +import java.io.IOException; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.Filter; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component("loggingFilterDelegateProxy") +public class LoggingFilterDelegatingFilterProxy implements Filter { + + @Autowired + LoggingService loggingService; + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; + loggingService.log(httpServletRequest.getMethod(), httpServletRequest.getRequestURI()); + filterChain.doFilter(servletRequest, servletResponse); + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingFilterRegistrationBean.java b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingFilterRegistrationBean.java new file mode 100644 index 0000000000..ec2c57c3a0 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingFilterRegistrationBean.java @@ -0,0 +1,32 @@ +package com.baeldung.filter; + +import java.io.IOException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.context.support.SpringBeanAutowiringSupport; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.FilterConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; + +@Component +public class LoggingFilterRegistrationBean implements Filter { + + private LoggingService loggingService; + + public LoggingFilterRegistrationBean(LoggingService loggingService) { + this.loggingService = loggingService; + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; + loggingService.log(httpServletRequest.getMethod(), httpServletRequest.getRequestURI()); + filterChain.doFilter(servletRequest, servletResponse); + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingFilterWebApplicationContext.java b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingFilterWebApplicationContext.java new file mode 100644 index 0000000000..85d83ebd9d --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingFilterWebApplicationContext.java @@ -0,0 +1,34 @@ +package com.baeldung.filter; + +import java.io.IOException; + +import jakarta.servlet.FilterChain; +import jakarta.servlet.Filter; +import jakarta.servlet.FilterConfig; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; + +import org.springframework.stereotype.Component; +import org.springframework.web.context.support.WebApplicationContextUtils; + +@Component +public class LoggingFilterWebApplicationContext implements Filter { + + private LoggingService loggingService; + + @Override + public void init(FilterConfig filterConfig) { + loggingService = WebApplicationContextUtils + .getRequiredWebApplicationContext(filterConfig.getServletContext()) + .getBean(LoggingService.class); + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; + loggingService.log(httpServletRequest.getMethod(), httpServletRequest.getRequestURI()); + filterChain.doFilter(servletRequest, servletResponse); + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingService.java b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingService.java new file mode 100644 index 0000000000..aaaa93a10b --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/LoggingService.java @@ -0,0 +1,14 @@ +package com.baeldung.filter; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +@Service +public class LoggingService { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + public void log(String message,String url){ + logger.info("Logging Request {} for URI : {}",message,url); + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/SpringBootFilterStartApp.java b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/SpringBootFilterStartApp.java new file mode 100644 index 0000000000..d497bc55ab --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/SpringBootFilterStartApp.java @@ -0,0 +1,12 @@ +package com.baeldung.filter; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringBootFilterStartApp { + + public static void main(String[] args) { + SpringApplication.run(SpringBootFilterStartApp.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/User.java b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/User.java new file mode 100644 index 0000000000..983228e8c6 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/User.java @@ -0,0 +1,39 @@ +package com.baeldung.filter; + +public class User { + + private String id; + private String name; + private String email; + + public User(String id, String name, String email) { + this.id = id; + this.name = name; + this.email = email; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/UserController.java b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/UserController.java new file mode 100644 index 0000000000..a7e3daa749 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/filter/UserController.java @@ -0,0 +1,17 @@ +package com.baeldung.filter; + +import java.util.Arrays; +import java.util.List; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class UserController { + + @GetMapping("/users") + public List getUsers(){ + return Arrays.asList(new User("1","John","john@email.com"), + new User("2","Smith","smith@email.com")); + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/springStart/SpringStartApplication.java b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/springStart/SpringStartApplication.java new file mode 100644 index 0000000000..6648fd8498 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/main/java/com/baeldung/springStart/SpringStartApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.springStart; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringStartApplication { + + public static void main(String[] args) { + SpringApplication.run(SpringStartApplication.class, args); + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/main/resources/application.properties b/spring-boot-modules/spring-boot-basic-customization-3/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/test/java/com/baeldung/filter/LoggingFilterAutowiringSupportUnitTest.java b/spring-boot-modules/spring-boot-basic-customization-3/src/test/java/com/baeldung/filter/LoggingFilterAutowiringSupportUnitTest.java new file mode 100644 index 0000000000..785bd9c514 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/test/java/com/baeldung/filter/LoggingFilterAutowiringSupportUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.filter; + +import java.lang.reflect.Field; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class LoggingFilterAutowiringSupportUnitTest { + + @Autowired + private LoggingFilterAutowiringSupport loggingFilter; + + @Test + public void givenFilter_whenAutowired_thenDependencyInjected() throws Exception { + Assert.assertNotNull(loggingFilter); + Assert.assertNotNull(getField(loggingFilter,"loggingService")); + } + + private Object getField(Object target, String fieldName) throws NoSuchFieldException, IllegalAccessException { + Field field = target.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + return field.get(target); + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/test/java/com/baeldung/filter/LoggingFilterDelegatingFilterProxyUnitTest.java b/spring-boot-modules/spring-boot-basic-customization-3/src/test/java/com/baeldung/filter/LoggingFilterDelegatingFilterProxyUnitTest.java new file mode 100644 index 0000000000..7d36a6fe10 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/test/java/com/baeldung/filter/LoggingFilterDelegatingFilterProxyUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.filter; + +import java.lang.reflect.Field; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class LoggingFilterDelegatingFilterProxyUnitTest { + + @Autowired + private LoggingFilterDelegatingFilterProxy loggingFilter; + + @Test + public void testLoggingFilter() throws Exception { + Assert.assertNotNull(loggingFilter); + Assert.assertNotNull(getField(loggingFilter,"loggingService")); + } + + private Object getField(Object target, String fieldName) throws NoSuchFieldException, IllegalAccessException { + Field field = target.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + return field.get(target); + } +} diff --git a/spring-boot-modules/spring-boot-basic-customization-3/src/test/java/com/baeldung/filter/LoggingFilterRegistrationBeanUnitTest.java b/spring-boot-modules/spring-boot-basic-customization-3/src/test/java/com/baeldung/filter/LoggingFilterRegistrationBeanUnitTest.java new file mode 100644 index 0000000000..25f1714845 --- /dev/null +++ b/spring-boot-modules/spring-boot-basic-customization-3/src/test/java/com/baeldung/filter/LoggingFilterRegistrationBeanUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.filter; + +import java.lang.reflect.Field; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class LoggingFilterRegistrationBeanUnitTest { + + @Autowired + private LoggingFilterRegistrationBean loggingFilter; + + @Test + public void testLoggingFilter() throws Exception { + Assert.assertNotNull(loggingFilter); + Assert.assertNotNull(getField(loggingFilter,"loggingService")); + } + + private Object getField(Object target, String fieldName) throws NoSuchFieldException, IllegalAccessException { + Field field = target.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + return field.get(target); + } +} diff --git a/spring-boot-modules/spring-boot-client/pom.xml b/spring-boot-modules/spring-boot-client/pom.xml index bbdc6cca7d..13fb780e45 100644 --- a/spring-boot-modules/spring-boot-client/pom.xml +++ b/spring-boot-modules/spring-boot-client/pom.xml @@ -33,11 +33,7 @@ org.springframework.boot spring-boot-starter - - com.google.guava - guava - ${guava.version} - + org.springframework spring-websocket 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-data-3/pom.xml b/spring-boot-modules/spring-boot-data-3/pom.xml index 726a6e70eb..0d35da3a0a 100644 --- a/spring-boot-modules/spring-boot-data-3/pom.xml +++ b/spring-boot-modules/spring-boot-data-3/pom.xml @@ -10,16 +10,17 @@ spring-boot-data-3 - com.baeldung.spring-boot-modules - spring-boot-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 io.hypersistence - hypersistence-utils-hibernate-55 - 3.7.1 + hypersistence-utils-hibernate-60 + ${hypersistence-utils-hibernate-60.version} org.springframework.boot @@ -68,6 +69,7 @@ 2.4.4 1.0.11 com.baeldung.startwithoutdb.StartWithoutDbApplication + 3.7.3 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/model/PersistableTask.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/model/PersistableTask.java index 949aa2935d..119789dcd8 100644 --- a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/model/PersistableTask.java +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/model/PersistableTask.java @@ -1,8 +1,8 @@ package com.baeldung.skipselectbeforeinsert.model; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Transient; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Transient; import org.springframework.data.domain.Persistable; diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/model/Task.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/model/Task.java index 9b8eaa8f6b..caeb2a9ab6 100644 --- a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/model/Task.java +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/model/Task.java @@ -1,9 +1,9 @@ package com.baeldung.skipselectbeforeinsert.model; -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 Task { diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/model/TaskWithGeneratedId.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/model/TaskWithGeneratedId.java index a3ea2a8ad0..cff4cc452f 100644 --- a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/model/TaskWithGeneratedId.java +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/model/TaskWithGeneratedId.java @@ -1,9 +1,9 @@ package com.baeldung.skipselectbeforeinsert.model; -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 TaskWithGeneratedId { diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/repository/TaskRepositoryExtensionImpl.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/repository/TaskRepositoryExtensionImpl.java index 86ff10a521..131a8ca50c 100644 --- a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/repository/TaskRepositoryExtensionImpl.java +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/skipselectbeforeinsert/repository/TaskRepositoryExtensionImpl.java @@ -1,7 +1,7 @@ package com.baeldung.skipselectbeforeinsert.repository; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; import org.springframework.stereotype.Component; diff --git a/spring-boot-modules/spring-boot-deployment/pom.xml b/spring-boot-modules/spring-boot-deployment/pom.xml index 890a5be58f..2af3a4718e 100644 --- a/spring-boot-modules/spring-boot-deployment/pom.xml +++ b/spring-boot-modules/spring-boot-deployment/pom.xml @@ -56,11 +56,7 @@ javax.persistence-api ${jpa.version} - - com.google.guava - guava - ${guava.version} - + org.subethamail subethasmtp diff --git a/spring-boot-modules/spring-boot-environment/pom.xml b/spring-boot-modules/spring-boot-environment/pom.xml index 616a1c19cc..097c3c2175 100644 --- a/spring-boot-modules/spring-boot-environment/pom.xml +++ b/spring-boot-modules/spring-boot-environment/pom.xml @@ -46,11 +46,7 @@ h2 runtime - - com.google.guava - guava - ${guava.version} - + org.subethamail subethasmtp diff --git a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java index 1349ff5918..9975b2ff93 100644 --- a/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-keycloak/src/main/java/com/baeldung/keycloak/SecurityConfig.java @@ -7,6 +7,7 @@ import java.util.Set; import java.util.stream.Collectors; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; @@ -56,6 +57,9 @@ class SecurityConfig { @Bean public SecurityFilterChain resourceServerFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth + // Allows preflight requests from browser + .requestMatchers(new AntPathRequestMatcher("/customers*", HttpMethod.OPTIONS.name())) + .permitAll() .requestMatchers(new AntPathRequestMatcher("/customers*")) .hasRole("user") .requestMatchers(new AntPathRequestMatcher("/")) diff --git a/spring-boot-modules/spring-boot-libraries-3/pom.xml b/spring-boot-modules/spring-boot-libraries-3/pom.xml index d0c1d345c0..988ce0bafe 100644 --- a/spring-boot-modules/spring-boot-libraries-3/pom.xml +++ b/spring-boot-modules/spring-boot-libraries-3/pom.xml @@ -6,9 +6,10 @@ spring-boot-libraries-3 - spring-boot-modules - com.baeldung.spring-boot-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -16,12 +17,17 @@ org.springframework.boot spring-boot-starter-data-jpa + org.springframework.kafka spring-kafka - ${spring-kafka.version} + + org.postgresql + postgresql + ${postgresql.version} + org.springframework.modulith spring-modulith-events-api @@ -33,17 +39,11 @@ ${spring-modulith-events-kafka.version} - com.fasterxml.jackson.core - jackson-databind - - - com.fasterxml.jackson.core - jackson-core - - - com.fasterxml.jackson.core - jackson-annotations + org.springframework.modulith + spring-modulith-starter-jpa + ${spring-modulith-events-kafka.version} + org.springframework.boot spring-boot-starter-test @@ -75,8 +75,10 @@ - com.h2database - h2 + org.testcontainers + postgresql + ${testcontainers.version} + test @@ -90,10 +92,12 @@ 17 - 1.1.3 - 1.19.6 + 3.1.5 + 1.1.2 + 1.19.3 4.2.0 - 3.1.2 + 42.3.1 - \ No newline at end of file + + diff --git a/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/Baeldung.java b/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/Baeldung.java index 1d309a8653..4b861a49c8 100644 --- a/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/Baeldung.java +++ b/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/Baeldung.java @@ -6,32 +6,29 @@ import org.springframework.transaction.annotation.Transactional; @Service public class Baeldung { + private final ApplicationEventPublisher applicationEvents; + private final ArticleRepository articleRepository; - private final ApplicationEventPublisher applicationEvents; - private final ArticleRepository articleRepository; + public Baeldung(ApplicationEventPublisher applicationEvents, ArticleRepository articleRepository) { + this.applicationEvents = applicationEvents; + this.articleRepository = articleRepository; + } + @Transactional + public void createArticle(Article article) { + // ... business logic + validateArticle(article); + article = addArticleTags(article); + article = articleRepository.save(article); - public Baeldung(ApplicationEventPublisher applicationEvents, ArticleRepository articleRepository) { - this.applicationEvents = applicationEvents; - this.articleRepository = articleRepository; - } + applicationEvents.publishEvent(new ArticlePublishedEvent(article.slug(), article.title())); + } - @Transactional - public void createArticle(Article article) { - // ... business logic - validateArticle(article); - article = addArticleTags(article); - article = articleRepository.save(article); + private Article addArticleTags(Article article) { + return article; + } - applicationEvents.publishEvent(new ArticlePublishedEvent(article.slug(), article.title())); - } - - - private Article addArticleTags(Article article) { - return article; - } - - private void validateArticle(Article article) { - } + private void validateArticle(Article article) { + } } diff --git a/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/EventExternalizationConfig.java b/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/EventExternalizationConfig.java index 9564696d92..6555694df9 100644 --- a/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/EventExternalizationConfig.java +++ b/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/EventExternalizationConfig.java @@ -4,12 +4,14 @@ import org.springframework.boot.autoconfigure.kafka.KafkaProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaOperations; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; -import org.springframework.kafka.core.KafkaOperations; import org.springframework.modulith.events.EventExternalizationConfiguration; import org.springframework.modulith.events.RoutingTarget; +import java.util.Objects; + @Configuration class EventExternalizationConfig { @@ -23,19 +25,30 @@ class EventExternalizationConfig { ) .mapping( ArticlePublishedEvent.class, - it -> new ArticlePublishedKafkaEvent(it.slug(), it.title()) + it -> new PostPublishedKafkaEvent(it.slug(), it.title()) + ) + .route( + WeeklySummaryPublishedEvent.class, + it -> RoutingTarget.forTarget("baeldung.articles.published").andKey(it.handle()) + ) + .mapping( + WeeklySummaryPublishedEvent.class, + it -> new PostPublishedKafkaEvent(it.handle(), it.heading()) ) .build(); } - record ArticlePublishedKafkaEvent(String slug, String title) { - } - - @Bean KafkaOperations kafkaOperations(KafkaProperties kafkaProperties) { ProducerFactory producerFactory = new DefaultKafkaProducerFactory<>(kafkaProperties.buildProducerProperties()); return new KafkaTemplate<>(producerFactory); } + + record PostPublishedKafkaEvent(String slug, String title) { + PostPublishedKafkaEvent { + Objects.requireNonNull(slug, "Article Slug must not be null!"); + } + } + } diff --git a/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/WeeklySummaryPublishedEvent.java b/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/WeeklySummaryPublishedEvent.java new file mode 100644 index 0000000000..2ae8713099 --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/WeeklySummaryPublishedEvent.java @@ -0,0 +1,7 @@ +package com.baeldung.springmodulith.events.externalization; + +import org.springframework.modulith.events.Externalized; + +@Externalized +record WeeklySummaryPublishedEvent(String handle, String heading) { +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/infra/PublicationEvents.java b/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/infra/PublicationEvents.java new file mode 100644 index 0000000000..bf0b96e78b --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-3/src/main/java/com/baeldung/springmodulith/events/externalization/infra/PublicationEvents.java @@ -0,0 +1,38 @@ +package com.baeldung.springmodulith.events.externalization.infra; + +import com.baeldung.springmodulith.events.externalization.ArticlePublishedEvent; +import org.springframework.modulith.events.CompletedEventPublications; +import org.springframework.modulith.events.IncompleteEventPublications; +import org.springframework.stereotype.Component; + +import java.time.Duration; +import java.time.Instant; + +@Component +class PublicationEvents { + private final IncompleteEventPublications incompleteEvent; + private final CompletedEventPublications completeEvents; + + public PublicationEvents(IncompleteEventPublications incompleteEvent, CompletedEventPublications completeEvents) { + this.incompleteEvent = incompleteEvent; + this.completeEvents = completeEvents; + } + + public void resubmitUnpublishedEvents() { + incompleteEvent.resubmitIncompletePublicationsOlderThan(Duration.ofSeconds(60)); + + // or + incompleteEvent.resubmitIncompletePublications(it -> + it.getPublicationDate().isBefore(Instant.now().minusSeconds(60)) + && it.getEvent() instanceof ArticlePublishedEvent); + } + + public void clearPublishedEvents() { + completeEvents.deletePublicationsOlderThan(Duration.ofSeconds(60)); + + // or + completeEvents.deletePublications(it -> + it.getPublicationDate().isBefore(Instant.now().minusSeconds(60)) + && it.getEvent() instanceof ArticlePublishedEvent); + } +} diff --git a/spring-boot-modules/spring-boot-libraries-3/src/main/resources/application.yml b/spring-boot-modules/spring-boot-libraries-3/src/main/resources/application.yml index ad8f7ab4e6..c6797b57d0 100644 --- a/spring-boot-modules/spring-boot-libraries-3/src/main/resources/application.yml +++ b/spring-boot-modules/spring-boot-libraries-3/src/main/resources/application.yml @@ -1,4 +1,3 @@ -logging.level.org.springframework.orm.jpa: TRACE spring.kafka: bootstrap-servers: localhost:9092 @@ -10,3 +9,20 @@ spring.kafka: key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: org.apache.kafka.common.serialization.StringDeserializer auto-offset-reset: earliest + +spring.modulith: + republish-outstanding-events-on-restart: true + events.jdbc.schema-initialization.enabled: true + +logging.level.org.springframework.orm.jpa: TRACE + +spring: + datasource: + username: test_user + password: test_pass + jpa: + properties: + hibernate: + dialect: org.hibernate.dialect.PostgreSQLDialect + hbm2ddl.auto: create + diff --git a/spring-boot-modules/spring-boot-libraries-3/src/test/java/com/baeldung/springmodulith/events/externalization/EventsExternalizationLiveTest.java b/spring-boot-modules/spring-boot-libraries-3/src/test/java/com/baeldung/springmodulith/events/externalization/EventsExternalizationLiveTest.java index 7f4f7a8224..a1b3dfe170 100644 --- a/spring-boot-modules/spring-boot-libraries-3/src/test/java/com/baeldung/springmodulith/events/externalization/EventsExternalizationLiveTest.java +++ b/spring-boot-modules/spring-boot-libraries-3/src/test/java/com/baeldung/springmodulith/events/externalization/EventsExternalizationLiveTest.java @@ -1,10 +1,8 @@ package com.baeldung.springmodulith.events.externalization; -import static java.time.Duration.ofMillis; -import static java.time.Duration.ofSeconds; -import static org.assertj.core.api.Assertions.assertThat; -import static org.testcontainers.shaded.org.awaitility.Awaitility.await; - +import com.baeldung.springmodulith.Application; +import com.baeldung.springmodulith.events.externalization.listener.TestKafkaListenerConfig; +import com.baeldung.springmodulith.events.externalization.listener.TestListener; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -12,14 +10,16 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.testcontainers.containers.KafkaContainer; +import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.shaded.org.awaitility.Awaitility; import org.testcontainers.utility.DockerImageName; -import com.baeldung.springmodulith.Application; -import com.baeldung.springmodulith.events.externalization.listener.TestKafkaListenerConfig; -import com.baeldung.springmodulith.events.externalization.listener.TestListener; +import static java.time.Duration.ofMillis; +import static java.time.Duration.ofSeconds; +import static org.assertj.core.api.Assertions.assertThat; +import static org.testcontainers.shaded.org.awaitility.Awaitility.await; @Testcontainers @SpringBootTest(classes = { Application.class, TestKafkaListenerConfig.class }) @@ -35,13 +35,20 @@ class EventsExternalizationLiveTest { @Container static KafkaContainer kafkaContainer = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); + @Container + public static PostgreSQLContainer postgresqlContainer = new PostgreSQLContainer() + .withDatabaseName("test_db") + .withUsername("test_user") + .withPassword("test_pass"); + @DynamicPropertySource static void dynamicProperties(DynamicPropertyRegistry registry) { registry.add("spring.kafka.bootstrap-servers", kafkaContainer::getBootstrapServers); + registry.add("spring.datasource.url", postgresqlContainer::getJdbcUrl); } static { - Awaitility.setDefaultTimeout(ofSeconds(3)); + Awaitility.setDefaultTimeout(ofSeconds(50)); Awaitility.setDefaultPollDelay(ofMillis(100)); } @@ -86,4 +93,4 @@ class EventsExternalizationLiveTest { .extracting(Article::title, Article::author) .containsExactly("Introduction to Spring Boot", "John Doe"); } -} \ No newline at end of file +} diff --git a/spring-boot-modules/spring-boot-openapi/README.md b/spring-boot-modules/spring-boot-openapi/README.md new file mode 100644 index 0000000000..cdfe6cf1a8 --- /dev/null +++ b/spring-boot-modules/spring-boot-openapi/README.md @@ -0,0 +1,2 @@ +### Relevant Articles: +- [OpenAPI Generator Custom Templates](https://www.baeldung.com/spring-boot-openapi-generator-custom-templates) diff --git a/spring-boot-modules/spring-boot-properties/pom.xml b/spring-boot-modules/spring-boot-properties/pom.xml index 61892fd076..ccf276471f 100644 --- a/spring-boot-modules/spring-boot-properties/pom.xml +++ b/spring-boot-modules/spring-boot-properties/pom.xml @@ -37,11 +37,6 @@ org.springframework.cloud spring-cloud-starter - - com.google.guava - guava - ${guava.version} - org.apache.httpcomponents httpcore diff --git a/spring-boot-modules/spring-boot-react/pom.xml b/spring-boot-modules/spring-boot-react/pom.xml index 95ae8c59d2..b808e4a32d 100644 --- a/spring-boot-modules/spring-boot-react/pom.xml +++ b/spring-boot-modules/spring-boot-react/pom.xml @@ -244,7 +244,6 @@ 1.6 v14.18.0 v1.12.1 - 2.4.4 1.0.2 diff --git a/spring-boot-modules/spring-boot-react/src/main/java/com/baeldung/springbootreact/domain/Client.java b/spring-boot-modules/spring-boot-react/src/main/java/com/baeldung/springbootreact/domain/Client.java index 46e7c29fd5..f600406a0a 100644 --- a/spring-boot-modules/spring-boot-react/src/main/java/com/baeldung/springbootreact/domain/Client.java +++ b/spring-boot-modules/spring-boot-react/src/main/java/com/baeldung/springbootreact/domain/Client.java @@ -1,9 +1,9 @@ package com.baeldung.springbootreact.domain; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "client") 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 7b2ed6976b..e43d6b0eb0 100644 --- a/spring-boot-modules/spring-boot-runtime/pom.xml +++ b/spring-boot-modules/spring-boot-runtime/pom.xml @@ -69,13 +69,8 @@ runtime - javax.persistence - javax.persistence-api - - - com.google.guava - guava - ${guava.version} + jakarta.persistence + jakarta.persistence-api org.subethamail @@ -84,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-security/src/test/resources/application.properties b/spring-boot-modules/spring-boot-security/src/test/resources/application.properties index 88bc213245..5494069009 100644 --- a/spring-boot-modules/spring-boot-security/src/test/resources/application.properties +++ b/spring-boot-modules/spring-boot-security/src/test/resources/application.properties @@ -1,2 +1,2 @@ -logging.level.root=DEBUG +logging.level.root=ERROR logging.level.com.baeldung.integrationtesting=ERROR 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-boot-testing-2/README.md b/spring-boot-modules/spring-boot-testing-2/README.md index fbf708381b..8db050228d 100644 --- a/spring-boot-modules/spring-boot-testing-2/README.md +++ b/spring-boot-modules/spring-boot-testing-2/README.md @@ -14,5 +14,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Spring Boot – Testing Redis With Testcontainers](https://www.baeldung.com/spring-boot-redis-testcontainers) - [Spring Boot – Keycloak Integration Testing with Testcontainers](https://www.baeldung.com/spring-boot-keycloak-integration-testing) - [Difference Between @Spy and @SpyBean](https://www.baeldung.com/spring-spy-vs-spybean) -- [Overriding Spring Beans in Integration Test](https://www.baeldung.com/overriding-spring-beans-in-integration-test) +- [Overriding Spring Beans in Integration Test](https://www.baeldung.com/spring-beans-integration-test-override) - More articles: [[<-- prev]](../spring-boot-testing) diff --git a/spring-boot-modules/spring-boot-testing-2/pom.xml b/spring-boot-modules/spring-boot-testing-2/pom.xml index f684d7ce97..48a7c90b0a 100644 --- a/spring-boot-modules/spring-boot-testing-2/pom.xml +++ b/spring-boot-modules/spring-boot-testing-2/pom.xml @@ -78,14 +78,21 @@ ${testcontainers-redis-junit-jupiter.version} test + + io.rest-assured + rest-assured + ${rest-assured.version} + test + + - org.jvnet.jaxb2.maven2 - maven-jaxb2-plugin - ${maven-jaxb2-plugin.version} + org.jvnet.jaxb + jaxb-maven-plugin + 4.0.0 xjc @@ -107,11 +114,12 @@ com.baeldung.boot.Application - 3.1.3 - 1.17.2 - 1.10.0 + 4.0.10 + 1.19.7 + 3.3.0 1.4.6 - 0.15.1 + 0.15.3 + 5.4.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/ProductEndpoint.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/ProductEndpoint.java index c3ba5c04a8..16b976b152 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/ProductEndpoint.java +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/ProductEndpoint.java @@ -1,21 +1,23 @@ package com.baeldung.webservice; -import com.baeldung.webservice.generated.GetProductRequest; -import com.baeldung.webservice.generated.GetProductResponse; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ws.server.endpoint.annotation.Endpoint; import org.springframework.ws.server.endpoint.annotation.PayloadRoot; import org.springframework.ws.server.endpoint.annotation.RequestPayload; import org.springframework.ws.server.endpoint.annotation.ResponsePayload; +import com.baeldung.webservice.generated.GetProductRequest; +import com.baeldung.webservice.generated.GetProductResponse; + @Endpoint public class ProductEndpoint { private static final String NAMESPACE_URI = "http://baeldung.com/spring-boot-web-service"; - @Autowired - private ProductRepository productRepository; + private final ProductRepository productRepository; + public ProductEndpoint(ProductRepository productRepository) { + this.productRepository = productRepository; + } @PayloadRoot(namespace = NAMESPACE_URI, localPart = "getProductRequest") @ResponsePayload diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/GetProductRequest.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/GetProductRequest.java index d04302456b..f6b48af278 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/GetProductRequest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/GetProductRequest.java @@ -1,11 +1,11 @@ package com.baeldung.webservice.generated; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlType; /** @@ -13,17 +13,17 @@ import javax.xml.bind.annotation.XmlType; * *

The following schema fragment specifies the expected content contained within this class. * - *

- * <complexType>
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
+ *
{@code
+ * 
+ *   
+ *     
+ *       
+ *         
+ *       
+ *     
+ *   
+ * 
+ * }
* * */ diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/GetProductResponse.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/GetProductResponse.java index f8fcaa094f..a2360d83eb 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/GetProductResponse.java +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/GetProductResponse.java @@ -1,11 +1,11 @@ package com.baeldung.webservice.generated; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlType; /** @@ -13,17 +13,17 @@ import javax.xml.bind.annotation.XmlType; * *

The following schema fragment specifies the expected content contained within this class. * - *

- * <complexType>
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="product" type="{http://baeldung.com/spring-boot-web-service}product"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
+ *
{@code
+ * 
+ *   
+ *     
+ *       
+ *         
+ *       
+ *     
+ *   
+ * 
+ * }
* * */ diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/ObjectFactory.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/ObjectFactory.java index 015ecc3f0a..e5877dd20b 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/ObjectFactory.java +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/ObjectFactory.java @@ -1,7 +1,7 @@ package com.baeldung.webservice.generated; -import javax.xml.bind.annotation.XmlRegistry; +import jakarta.xml.bind.annotation.XmlRegistry; /** @@ -32,6 +32,8 @@ public class ObjectFactory { /** * Create an instance of {@link GetProductRequest } * + * @return + * the new instance of {@link GetProductRequest } */ public GetProductRequest createGetProductRequest() { return new GetProductRequest(); @@ -40,6 +42,8 @@ public class ObjectFactory { /** * Create an instance of {@link GetProductResponse } * + * @return + * the new instance of {@link GetProductResponse } */ public GetProductResponse createGetProductResponse() { return new GetProductResponse(); @@ -48,6 +52,8 @@ public class ObjectFactory { /** * Create an instance of {@link Product } * + * @return + * the new instance of {@link Product } */ public Product createProduct() { return new Product(); diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/Product.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/Product.java index 5957aa44b4..f1d62d1489 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/Product.java +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/Product.java @@ -1,10 +1,10 @@ package com.baeldung.webservice.generated; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlType; +import jakarta.xml.bind.annotation.XmlAccessType; +import jakarta.xml.bind.annotation.XmlAccessorType; +import jakarta.xml.bind.annotation.XmlElement; +import jakarta.xml.bind.annotation.XmlType; /** @@ -12,18 +12,18 @@ import javax.xml.bind.annotation.XmlType; * *

The following schema fragment specifies the expected content contained within this class. * - *

- * <complexType name="product">
- *   <complexContent>
- *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
- *       <sequence>
- *         <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *         <element name="name" type="{http://www.w3.org/2001/XMLSchema}string"/>
- *       </sequence>
- *     </restriction>
- *   </complexContent>
- * </complexType>
- * 
+ *
{@code
+ * 
+ *   
+ *     
+ *       
+ *         
+ *         
+ *       
+ *     
+ *   
+ * 
+ * }
* * */ diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/package-info.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/package-info.java index 298ae9374b..fa8f2aeec5 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/package-info.java +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/webservice/generated/package-info.java @@ -1,2 +1,2 @@ -@javax.xml.bind.annotation.XmlSchema(namespace = "http://baeldung.com/spring-boot-web-service", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +@jakarta.xml.bind.annotation.XmlSchema(namespace = "http://baeldung.com/spring-boot-web-service", elementFormDefault = jakarta.xml.bind.annotation.XmlNsForm.QUALIFIED) package com.baeldung.webservice.generated; diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/keycloaktestcontainers/KeycloakTestContainers.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/keycloaktestcontainers/KeycloakTestContainers.java index 2a50a646c5..d68fae9cb5 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/keycloaktestcontainers/KeycloakTestContainers.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/keycloaktestcontainers/KeycloakTestContainers.java @@ -4,8 +4,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; -import javax.annotation.PostConstruct; - import org.apache.http.client.utils.URIBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,6 +21,7 @@ import org.springframework.web.reactive.function.client.WebClient; import dasniko.testcontainers.keycloak.KeycloakContainer; import io.restassured.RestAssured; +import jakarta.annotation.PostConstruct; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public abstract class KeycloakTestContainers { diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/webservice/ProductEndpointIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/webservice/ProductEndpointIntegrationTest.java index edd15090b8..0d58cfde17 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/webservice/ProductEndpointIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/webservice/ProductEndpointIntegrationTest.java @@ -15,6 +15,7 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.webservices.server.WebServiceServerTest; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.context.annotation.ComponentScan; import org.springframework.core.io.ClassPathResource; import org.springframework.ws.test.server.MockWebServiceClient; import org.springframework.xml.transform.StringSource; @@ -22,6 +23,7 @@ import org.springframework.xml.transform.StringSource; import com.baeldung.webservice.generated.Product; @WebServiceServerTest +@ComponentScan("com.baeldung.webservice") class ProductEndpointIntegrationTest { private static final Map NAMESPACE_MAPPING = createMapping(); diff --git a/spring-boot-modules/spring-boot-testing/pom.xml b/spring-boot-modules/spring-boot-testing/pom.xml index 7643183fcb..28ce90d8ec 100644 --- a/spring-boot-modules/spring-boot-testing/pom.xml +++ b/spring-boot-modules/spring-boot-testing/pom.xml @@ -50,7 +50,7 @@ - it.ozimov + com.github.codemonstur embedded-redis ${embedded-redis.version} test @@ -114,7 +114,7 @@ 2.2.4 2.4-M1-groovy-4.0 3.0.0 - 0.7.2 + 1.4.2 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java index 10e5d56857..f0ac4be194 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/TestRedisConfiguration.java @@ -1,18 +1,21 @@ package com.baeldung.boot.embeddedRedis; -import com.baeldung.boot.embeddedRedis.configuration.RedisProperties; +import java.io.IOException; + import org.springframework.boot.test.context.TestConfiguration; -import redis.embedded.RedisServer; + +import com.baeldung.boot.embeddedRedis.configuration.RedisProperties; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; +import redis.embedded.RedisServer; @TestConfiguration public class TestRedisConfiguration { private final RedisServer redisServer; - public TestRedisConfiguration(final RedisProperties redisProperties) { + public TestRedisConfiguration(final RedisProperties redisProperties) throws IOException { this.redisServer = new RedisServer(redisProperties.getRedisPort()); //Uncomment below if running on windows and can't start redis server // this.redisServer = RedisServer.builder().setting("maxheap 200m").port(6379).setting("bind localhost").build(); @@ -20,12 +23,12 @@ public class TestRedisConfiguration { } @PostConstruct - public void postConstruct() { + public void postConstruct() throws IOException { redisServer.start(); } @PreDestroy - public void preDestroy() { + public void preDestroy() throws IOException { redisServer.stop(); } } diff --git a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java index 9577ccf0e8..331801cc0a 100644 --- a/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing/src/test/java/com/baeldung/boot/embeddedRedis/domain/repository/UserRepositoryIntegrationTest.java @@ -1,26 +1,25 @@ package com.baeldung.boot.embeddedRedis.domain.repository; -import com.baeldung.boot.embeddedRedis.TestRedisConfiguration; -import com.baeldung.boot.embeddedRedis.domain.User; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.UUID; -import static org.junit.Assert.assertNotNull; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import com.baeldung.boot.embeddedRedis.TestRedisConfiguration; +import com.baeldung.boot.embeddedRedis.domain.User; + -@RunWith(SpringRunner.class) @SpringBootTest(classes = TestRedisConfiguration.class) -public class UserRepositoryIntegrationTest { +class UserRepositoryIntegrationTest { @Autowired private UserRepository userRepository; @Test - public void shouldSaveUser_toRedis() { + void shouldSaveUser_toRedis() { final UUID id = UUID.randomUUID(); final User user = new User(id, "name"); 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-cloud-modules/pom.xml b/spring-cloud-modules/pom.xml index 2613b9f9ce..187958fa6c 100644 --- a/spring-cloud-modules/pom.xml +++ b/spring-cloud-modules/pom.xml @@ -22,7 +22,8 @@ spring-cloud-hystrix - spring-cloud-bootstrap + + spring-cloud-ribbon-client spring-cloud-zookeeper spring-cloud-gateway diff --git a/spring-cloud-modules/spring-cloud-bootstrap/config/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/config/pom.xml index c1be447822..4831759fef 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/config/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/config/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../../parent-boot-2 + ../../../parent-boot-3 @@ -42,7 +42,7 @@ - 2021.0.7 + 2022.0.4 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/customer-service/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/customer-service/pom.xml index da2dee97d5..c4d31138ad 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/customer-service/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/customer-service/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../../parent-boot-2 + ../../../parent-boot-3 diff --git a/spring-cloud-modules/spring-cloud-bootstrap/discovery/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/discovery/pom.xml index 28c1a741a6..0527a232f7 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/discovery/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/discovery/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../../parent-boot-2 + ../../../parent-boot-3 @@ -54,7 +54,7 @@ - 2021.0.7 + 2022.0.3 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java index fa389ec6a3..b30515cdcf 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/discovery/src/main/java/com/baeldung/spring/cloud/bootstrap/discovery/SecurityConfig.java @@ -4,41 +4,38 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.http.HttpMethod; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; @Configuration @EnableWebSecurity @Order(1) -public class SecurityConfig extends WebSecurityConfigurerAdapter { +public class SecurityConfig { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("discUser").password("{noop}discPassword").roles("SYSTEM"); } - @Override protected void configure(HttpSecurity http) throws Exception { - http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and().requestMatchers().antMatchers("/eureka/**").and().authorizeRequests().antMatchers("/eureka/**").hasRole("SYSTEM").anyRequest().denyAll().and().httpBasic().and().csrf() - .disable(); + http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)).authorizeHttpRequests(auth -> auth.requestMatchers("/eureka/**")).authorizeRequests(auth -> auth.requestMatchers("/eureka/**").hasRole("SYSTEM").anyRequest().denyAll()).httpBasic( + Customizer.withDefaults()).csrf(csrf -> csrf.disable()); } @Configuration // no order tag means this is the last security filter to be evaluated - public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter { + public static class AdminSecurityConfig { - @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication(); } - @Override protected void configure(HttpSecurity http) throws Exception { - http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and().httpBasic().disable().authorizeRequests().antMatchers(HttpMethod.GET, "/").hasRole("ADMIN").antMatchers("/info", "/health").authenticated().anyRequest().denyAll() - .and().csrf().disable(); + http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.NEVER)).httpBasic(basic -> basic.disable()).authorizeRequests().requestMatchers(HttpMethod.GET, "/").hasRole("ADMIN").requestMatchers("/info", "/health").authenticated().anyRequest().denyAll() + .and().csrf(csrf -> csrf.disable()); } } } diff --git a/spring-cloud-modules/spring-cloud-bootstrap/gateway/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/gateway/pom.xml index fa6735199f..b29d2eb760 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/gateway/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/gateway/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../../parent-boot-2 + ../../../parent-boot-3 @@ -55,18 +55,16 @@ org.springframework.boot spring-boot-starter-data-redis - - org.springframework.cloud - spring-cloud-starter-sleuth - - - org.springframework.cloud - spring-cloud-sleuth-zipkin - org.springframework.cloud spring-cloud-starter-openfeign + + io.rest-assured + rest-assured + ${rest-assured.version} + test + @@ -105,7 +103,8 @@ - 2021.0.7 + 2022.0.4 + 5.4.0 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/order-service/order-server/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/order-service/order-server/pom.xml index 85143b557e..e565a7dcab 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/order-service/order-server/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/order-service/order-server/pom.xml @@ -20,6 +20,16 @@ 1.0.0-SNAPSHOT compile + + org.projectlombok + lombok + ${lombok.version} + provided + + + 1.18.30 + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/order-service/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/order-service/pom.xml index 16366f5eb6..9adfbb4f54 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/order-service/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/order-service/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../../parent-boot-2 + ../../../parent-boot-3 @@ -81,16 +81,6 @@ exec
- - start-application - - com.baeldung.orderservice.OrderApplication - ../order-server/target/classes - - - start - -
@@ -116,6 +106,7 @@ 1.8 1.8 com.baeldung.orderservice.OrderApplication + true \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/pom.xml index 73b07c826f..746b6f0405 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/pom.xml @@ -25,4 +25,8 @@ order-service + + 17 + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/pom.xml index 2a6196b92b..5fd97d0574 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../../parent-boot-2 + ../../../parent-boot-3 @@ -65,18 +65,10 @@ h2 runtime - - org.springframework.cloud - spring-cloud-starter-sleuth - - - org.springframework.cloud - spring-cloud-sleuth-zipkin - - 2021.0.7 + 2022.0.3 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java index 0b9520c976..054eca5cfe 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java @@ -20,18 +20,17 @@ public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - return http.authorizeHttpRequests((auth) -> auth.antMatchers(HttpMethod.GET, "/books") + return http.authorizeHttpRequests((auth) -> auth.requestMatchers(HttpMethod.GET, "/books") .permitAll() - .antMatchers(HttpMethod.GET, "/books/*") + .requestMatchers(HttpMethod.GET, "/books/*") .permitAll() - .antMatchers(HttpMethod.POST, "/books") + .requestMatchers(HttpMethod.POST, "/books") .hasRole("ADMIN") - .antMatchers(HttpMethod.PATCH, "/books/*") + .requestMatchers(HttpMethod.PATCH, "/books/*") .hasRole("ADMIN") - .antMatchers(HttpMethod.DELETE, "/books/*") + .requestMatchers(HttpMethod.DELETE, "/books/*") .hasRole("ADMIN")) - .csrf() - .disable() + .csrf(csrf -> csrf.disable()) .build(); } } diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java index f087967bab..f5e4e9b496 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java @@ -2,10 +2,10 @@ package com.baeldung.spring.cloud.bootstrap.svcbook.book; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -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 @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/pom.xml b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/pom.xml index 54572eeea2..2d5ea8369d 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/pom.xml +++ b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../../parent-boot-2 + ../../../parent-boot-3 @@ -68,14 +68,6 @@ org.springframework.boot spring-boot-starter-actuator - - org.springframework.cloud - spring-cloud-starter-sleuth - - - org.springframework.cloud - spring-cloud-sleuth-zipkin - com.h2database h2 @@ -84,7 +76,7 @@ - 2021.0.7 + 2022.0.3 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java index f470946e1d..4f32bbed98 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/SecurityConfig.java @@ -3,6 +3,7 @@ package com.baeldung.spring.cloud.bootstrap.svcrating; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.userdetails.UserDetailsService; @@ -20,22 +21,20 @@ public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { - return httpSecurity.authorizeHttpRequests((auth) -> auth.regexMatchers("^/ratings\\?bookId.*$") + return httpSecurity.authorizeHttpRequests((auth) -> auth.requestMatchers("^/ratings\\?bookId.*$") .authenticated() - .antMatchers(HttpMethod.POST, "/ratings") + .requestMatchers(HttpMethod.POST, "/ratings") .authenticated() - .antMatchers(HttpMethod.PATCH, "/ratings/*") + .requestMatchers(HttpMethod.PATCH, "/ratings/*") .hasRole("ADMIN") - .antMatchers(HttpMethod.DELETE, "/ratings/*") + .requestMatchers(HttpMethod.DELETE, "/ratings/*") .hasRole("ADMIN") - .antMatchers(HttpMethod.GET, "/ratings") + .requestMatchers(HttpMethod.GET, "/ratings") .hasRole("ADMIN") .anyRequest() .authenticated()) - .httpBasic() - .and() - .csrf() - .disable() + .httpBasic(Customizer.withDefaults()) + .csrf(csrf -> csrf.disable()) .build(); } } diff --git a/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java index 2c7069926c..cbb49914e3 100644 --- a/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java +++ b/spring-cloud-modules/spring-cloud-bootstrap/zipkin-log-svc-rating/src/main/java/com/baeldung/spring/cloud/bootstrap/svcrating/rating/Rating.java @@ -2,11 +2,11 @@ package com.baeldung.spring.cloud.bootstrap.svcrating.rating; import java.io.Serializable; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Transient; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Transient; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; diff --git a/spring-core/pom.xml b/spring-core/pom.xml index e369bc24d0..5134ad42f7 100644 --- a/spring-core/pom.xml +++ b/spring-core/pom.xml @@ -36,11 +36,6 @@ javax.inject ${javax.inject.version} - - com.google.guava - guava - ${guava.version} - org.projectlombok lombok diff --git a/spring-di-2/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java b/spring-di-2/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java index dc2240d0b5..4ebb113651 100644 --- a/spring-di-2/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java +++ b/spring-di-2/src/main/java/com/baeldung/circulardependency/CircularDependencyB.java @@ -1,6 +1,7 @@ package com.baeldung.circulardependency; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; @Component @@ -11,7 +12,7 @@ public class CircularDependencyB { private String message = "Hi!"; @Autowired - public void setCircA(final CircularDependencyA circA) { + public void setCircA(@Lazy final CircularDependencyA circA) { this.circA = circA; } diff --git a/spring-di/pom.xml b/spring-di/pom.xml index a1be835af7..078a761f9a 100644 --- a/spring-di/pom.xml +++ b/spring-di/pom.xml @@ -16,11 +16,6 @@
- - com.google.guava - guava - ${guava.version} - org.projectlombok lombok diff --git a/spring-kafka-2/pom.xml b/spring-kafka-2/pom.xml index 7a4d5a5fea..b2d9d01b8e 100644 --- a/spring-kafka-2/pom.xml +++ b/spring-kafka-2/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -26,10 +26,12 @@ org.springframework.kafka spring-kafka + ${spring-kafka.version} org.apache.kafka kafka-streams + ${kafka-streams.version} com.fasterxml.jackson.core @@ -40,6 +42,10 @@ lombok ${lombok.version} + + org.apache.commons + commons-lang3 + org.springframework.kafka spring-kafka-test @@ -54,7 +60,6 @@ org.testcontainers junit-jupiter - ${testcontainers-junit-jupiter.version} test @@ -66,9 +71,9 @@ 1.19.3 - 3.0.12 - 3.6.0 - 1.16.2 + 3.1.2 + 3.6.1 + com.baeldung.spring.kafka.dlt.KafkaDltApplication \ 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-kafka/pom.xml b/spring-kafka/pom.xml index 4a8267b7e3..13649f924b 100644 --- a/spring-kafka/pom.xml +++ b/spring-kafka/pom.xml @@ -26,12 +26,10 @@ org.springframework.boot spring-boot-starter-actuator - ${spring-boot-starter-actuator.version} io.micrometer micrometer-registry-prometheus - ${micrometer-registry-prometheus.version} org.springframework.kafka @@ -49,7 +47,6 @@ org.projectlombok lombok - ${lombok.version} org.springframework.kafka @@ -59,13 +56,11 @@ org.testcontainers kafka - ${testcontainers-kafka.version} test org.testcontainers junit-jupiter - ${testcontainers-kafka.version} test @@ -92,10 +87,9 @@ - 3.0.5 - 1.10.5 - 1.19.3 3.1.2 + 3.2.2 + 5.10.2 \ No newline at end of file diff --git a/spring-kafka/src/test/java/com/baeldung/partitioningstrategy/KafkaApplicationIntegrationTest.java b/spring-kafka/src/test/java/com/baeldung/partitioningstrategy/KafkaApplicationIntegrationTest.java index 2f2cccbb12..bd55b538af 100644 --- a/spring-kafka/src/test/java/com/baeldung/partitioningstrategy/KafkaApplicationIntegrationTest.java +++ b/spring-kafka/src/test/java/com/baeldung/partitioningstrategy/KafkaApplicationIntegrationTest.java @@ -29,7 +29,7 @@ import static org.awaitility.Awaitility.await; import static java.util.concurrent.TimeUnit.SECONDS; @SpringBootTest -@EmbeddedKafka(partitions = 3, brokerProperties = { "listeners=PLAINTEXT://localhost:9092" }) +@EmbeddedKafka(partitions = 3, brokerProperties = { "listeners=PLAINTEXT://localhost:9092" }, kraft = false) public class KafkaApplicationIntegrationTest { @Autowired diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 595cde5109..a9076fd28b 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -9,6 +9,7 @@ spring-katharsis war + com.baeldung parent-boot-2 diff --git a/spring-protobuf/pom.xml b/spring-protobuf/pom.xml index ea80ddaa1a..0e872508e4 100644 --- a/spring-protobuf/pom.xml +++ b/spring-protobuf/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -37,12 +37,14 @@ org.apache.httpcomponents httpclient + ${httpclient.version} - 3.1.0 + 3.25.3 1.4 + 4.5.14 com.baeldung.protobuf.Application diff --git a/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java index df750db1db..8c339ef5dd 100644 --- a/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java +++ b/spring-protobuf/src/test/java/com/baeldung/protobuf/ApplicationIntegrationTest.java @@ -11,7 +11,7 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; 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.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/spring-reactive-modules/spring-reactive-data/README.md b/spring-reactive-modules/spring-reactive-data/README.md index 259ab0be62..7119986986 100644 --- a/spring-reactive-modules/spring-reactive-data/README.md +++ b/spring-reactive-modules/spring-reactive-data/README.md @@ -7,5 +7,5 @@ This module contains articles about reactive Spring Boot Data The "REST With Spring" Classes: http://bit.ly/restwithspring ### Relevant Articles -- [A Quick Look at R2DBC with Spring Data](https://www.baeldung.com/spring-data-r2dbc) +- [A Quick Look at R2DBC With Spring Data](https://www.baeldung.com/spring-data-r2dbc) - [Pagination in Spring Webflux and Spring Data Reactive](https://www.baeldung.com/spring-data-webflux-pagination) diff --git a/spring-reactive-modules/spring-reactive-data/pom.xml b/spring-reactive-modules/spring-reactive-data/pom.xml index d72072e419..80f7a76ff0 100644 --- a/spring-reactive-modules/spring-reactive-data/pom.xml +++ b/spring-reactive-modules/spring-reactive-data/pom.xml @@ -8,9 +8,10 @@ jar - com.baeldung.spring.reactive - spring-reactive-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -41,11 +42,6 @@ h2 runtime - - io.r2dbc - r2dbc-h2 - runtime - org.projectlombok lombok @@ -58,9 +54,9 @@ test - javax.validation - validation-api - ${validation-api.version} + jakarta.validation + jakarta.validation-api + ${jakarta.validation-api.version} io.r2dbc @@ -69,8 +65,8 @@ - UTF-8 - 2.0.1.Final + 3.1.0-M1 + true \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/model/Product.java b/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/model/Product.java index c82e31309c..b97aefaaee 100644 --- a/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/model/Product.java +++ b/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/model/Product.java @@ -2,8 +2,8 @@ package com.baeldung.pagination.model; import java.util.UUID; -import javax.validation.constraints.NotNull; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Size; import org.springframework.data.annotation.Id; import org.springframework.data.relational.core.mapping.Table; diff --git a/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/repository/ProductRepository.java b/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/repository/ProductRepository.java index 1610d452da..f2ddc63ecb 100644 --- a/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/repository/ProductRepository.java +++ b/spring-reactive-modules/spring-reactive-data/src/main/java/com/baeldung/pagination/repository/ProductRepository.java @@ -9,8 +9,11 @@ import org.springframework.stereotype.Repository; import com.baeldung.pagination.model.Product; import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; @Repository public interface ProductRepository extends ReactiveSortingRepository { Flux findAllBy(Pageable pageable); + + Mono count(); } diff --git a/spring-reactive-modules/spring-reactor/pom.xml b/spring-reactive-modules/spring-reactor/pom.xml index 54a97b92de..60564ac84d 100644 --- a/spring-reactive-modules/spring-reactor/pom.xml +++ b/spring-reactive-modules/spring-reactor/pom.xml @@ -10,9 +10,10 @@ http://maven.apache.org - com.baeldung.spring.reactive - spring-reactive-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 diff --git a/spring-reactive-modules/spring-reactor/src/test/java/com/baeldung/reactorbus/NotificationApplicationIntegrationTest.java b/spring-reactive-modules/spring-reactor/src/test/java/com/baeldung/reactorbus/NotificationApplicationIntegrationTest.java index 0adea21fd4..586e23f5fc 100644 --- a/spring-reactive-modules/spring-reactor/src/test/java/com/baeldung/reactorbus/NotificationApplicationIntegrationTest.java +++ b/spring-reactive-modules/spring-reactor/src/test/java/com/baeldung/reactorbus/NotificationApplicationIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung.reactorbus; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; 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-remoting-modules/pom.xml b/spring-remoting-modules/pom.xml index e7de7c5740..f7f8abbf87 100644 --- a/spring-remoting-modules/pom.xml +++ b/spring-remoting-modules/pom.xml @@ -10,6 +10,8 @@ Parent for all projects related to Spring Remoting, except remoting-hessian-burlap + com.baeldung diff --git a/spring-security-modules/spring-security-auth0/pom.xml b/spring-security-modules/spring-security-auth0/pom.xml index 8ee59eeac1..ba21a899f9 100644 --- a/spring-security-modules/spring-security-auth0/pom.xml +++ b/spring-security-modules/spring-security-auth0/pom.xml @@ -69,7 +69,7 @@ - 20190722 + 20240303 1.2.0 diff --git a/spring-security-modules/spring-security-core-2/README.md b/spring-security-modules/spring-security-core-2/README.md index 5f54dc1a50..922c473b75 100644 --- a/spring-security-modules/spring-security-core-2/README.md +++ b/spring-security-modules/spring-security-core-2/README.md @@ -9,6 +9,8 @@ This module contains articles about core Spring Security - [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver) - [A Custom Spring SecurityConfigurer](https://www.baeldung.com/spring-security-custom-configurer) - [HttpSecurity vs. WebSecurity in Spring Security](https://www.baeldung.com/spring-security-httpsecurity-vs-websecurity) +- [Migrate Application from Spring Security 5 to Spring Security 6/Spring Boot 3](https://www.baeldung.com/spring-security-migrate-5-to-6) +- [Spring Security AuthorizationManager](https://www.baeldung.com/spring-security-authorizationmanager) ### Build the Project diff --git a/spring-security-modules/spring-security-oauth2-bff/README.md b/spring-security-modules/spring-security-oauth2-bff/README.md index a102190043..1bff72e4b8 100644 --- a/spring-security-modules/spring-security-oauth2-bff/README.md +++ b/spring-security-modules/spring-security-oauth2-bff/README.md @@ -3,4 +3,4 @@ This module contains articles about core Spring Security Oauth2 Backend-for-Frontend ### Relevant Articles: -- [OAuth2 Backend for Frontend With Spring Cloud Gateway](https://www.baeldung.com/spring-backend-for-frontend-with-spring-cloud-gateway) +- [OAuth2 Backend for Frontend With Spring Cloud Gateway](https://www.baeldung.com/spring-cloud-gateway-bff-oauth2) 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-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectApplication.java b/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectApplication.java index 1e44240449..e9d2cc08e8 100644 --- a/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectApplication.java +++ b/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectApplication.java @@ -5,6 +5,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ImportResource; @SpringBootApplication +//Comment this line when you want to use the class definition for defining Spring security rules, LoginRedirectSecurityConfig. +// Uncomment the annotations from LoginRedirectSecurityConfig. @ImportResource({"classpath*:spring-security-login-redirect.xml"}) class LoginRedirectApplication { public static void main(String[] args) { diff --git a/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectSecurityConfig.java b/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectSecurityConfig.java index c9aa607a9f..c19c2ce03e 100644 --- a/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectSecurityConfig.java +++ b/spring-security-modules/spring-security-web-boot-2/src/main/java/com/baeldung/loginredirect/LoginRedirectSecurityConfig.java @@ -13,8 +13,9 @@ import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -@Configuration -@EnableWebSecurity +//if you use xsd configuration (spring-security-login-redirect.xml) please comment the annotations from this class, because it will overlap with configuration from this class +/*@Configuration +@EnableWebSecurity*/ class LoginRedirectSecurityConfig { private static final String LOGIN_USER = "/loginUser"; diff --git a/spring-security-modules/spring-security-web-boot-2/src/main/resources/spring-security-login-redirect.xml b/spring-security-modules/spring-security-web-boot-2/src/main/resources/spring-security-login-redirect.xml index e711abce1f..8bdc35d055 100644 --- a/spring-security-modules/spring-security-web-boot-2/src/main/resources/spring-security-login-redirect.xml +++ b/spring-security-modules/spring-security-web-boot-2/src/main/resources/spring-security-login-redirect.xml @@ -6,11 +6,11 @@ xmlns:security="http://www.springframework.org/schema/security" xsi:schemaLocation=" http://www.springframework.org/schema/mvc - http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd - http://www.springframework.org/schema/security - http://www.springframework.org/schema/security/spring-security-5.2.xsd - http://www.springframework.org/schema/beans - http://www.springframework.org/schema/beans/spring-beans.xsd"> + https://www.springframework.org/schema/mvc/spring-mvc.xsd + http://www.springframework.org/schema/security + https://www.springframework.org/schema/security/spring-security.xsd + http://www.springframework.org/schema/beans + https://www.springframework.org/schema/beans/spring-beans.xsd"> @@ -40,7 +40,7 @@ - + diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/resources/logback.xml b/spring-security-modules/spring-security-web-boot-3/src/main/resources/logback.xml new file mode 100644 index 0000000000..79357f34c2 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/src/main/resources/logback.xml @@ -0,0 +1,16 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-mvc-custom/pom.xml b/spring-security-modules/spring-security-web-mvc-custom/pom.xml index 41f24050b2..7f7f256196 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/pom.xml +++ b/spring-security-modules/spring-security-web-mvc-custom/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring-5 + parent-spring-6 0.0.1-SNAPSHOT - ../../parent-spring-5 + ../../parent-spring-6 @@ -86,15 +86,15 @@ - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} + jakarta.servlet + jakarta.servlet-api + ${jakarta.servlet-api.version} provided - javax.servlet - jstl - ${jstl.version} + jakarta.servlet.jsp.jstl + jakarta.servlet.jsp.jstl-api + ${jakarta.jstl-api.version} runtime @@ -127,9 +127,9 @@ test - javax.annotation - javax.annotation-api - ${javax.annotation-api.version} + jakarta.annotation + jakarta.annotation-api + ${jakarta.annotation-api.version} @@ -173,7 +173,10 @@ 1.6.1 - 1.3.2 + 3.0.0-M1 + 6.1.0-M1 + 3.0.0 + 6.2.1 \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 728445952e..9422e7032d 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -5,9 +5,9 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/spring/MyUserDetailsService.java b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/spring/MyUserDetailsService.java index ee80ad12d7..9cf0779e73 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/spring/MyUserDetailsService.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/spring/MyUserDetailsService.java @@ -7,7 +7,7 @@ import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Service; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import java.util.*; @Service diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/spring/SecSecurityConfig.java index d5e83a1110..d228dec49f 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/spring/SecSecurityConfig.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -6,6 +6,7 @@ import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 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.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @@ -40,29 +41,20 @@ public class SecSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/anonymous*") + http.authorizeHttpRequests(auth -> auth.requestMatchers("/anonymous*") .anonymous() - .antMatchers("/login*") + .requestMatchers("/login*") .permitAll() .anyRequest() - .authenticated() - .and() - .formLogin() - .loginPage("/login.html") - .loginProcessingUrl("/login") - .successHandler(myAuthenticationSuccessHandler()) - .failureUrl("/login.html?error=true") - .and() - .logout() - .deleteCookies("JSESSIONID") - .and() - .rememberMe() - .key("uniqueAndSecret") - .tokenValiditySeconds(86400) - .and() - .csrf() - .disable(); + .authenticated()) + .formLogin(formLogin -> formLogin.loginPage("/login.html") + .loginProcessingUrl("/login") + .successHandler(myAuthenticationSuccessHandler()) + .failureUrl("/login.html?error=true")) + .rememberMe(rememberMe -> rememberMe.key("uniqueAndSecret") + .tokenValiditySeconds(86400)) + .logout(logout -> logout.deleteCookies("JSESSIONID")) + .csrf(AbstractHttpConfigurer::disable); return http.build(); } diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/controller/FooController.java b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/controller/FooController.java index 6f9268c976..8d5016cdc4 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/controller/FooController.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/controller/FooController.java @@ -5,7 +5,7 @@ import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import java.util.Arrays; import java.util.List; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import com.baeldung.web.dto.Foo; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/controller/LoginController.java b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/controller/LoginController.java index 8a823cdf7e..5f73f9ea8f 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/controller/LoginController.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/controller/LoginController.java @@ -1,10 +1,5 @@ package com.baeldung.web.controller; -import javax.annotation.Resource; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; @@ -15,6 +10,10 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; +import jakarta.annotation.Resource; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; + @Controller @RequestMapping(value = "/custom") public class LoginController { diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/interceptor/LoggerInterceptor.java b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/interceptor/LoggerInterceptor.java index 669e4cb3c5..78f3de6c20 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/interceptor/LoggerInterceptor.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/interceptor/LoggerInterceptor.java @@ -2,8 +2,8 @@ package com.baeldung.web.interceptor; import java.util.Enumeration; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/interceptor/SessionTimerInterceptor.java b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/interceptor/SessionTimerInterceptor.java index e7decc262f..d914b564fe 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/interceptor/SessionTimerInterceptor.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/interceptor/SessionTimerInterceptor.java @@ -1,8 +1,8 @@ package com.baeldung.web.interceptor; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/interceptor/UserInterceptor.java b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/interceptor/UserInterceptor.java index ad80571be6..152d9f9864 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/interceptor/UserInterceptor.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/main/java/com/baeldung/web/interceptor/UserInterceptor.java @@ -1,8 +1,8 @@ package com.baeldung.web.interceptor; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfAbstractIntegrationTest.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfAbstractIntegrationTest.java index 97972b7358..fc289015a7 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfAbstractIntegrationTest.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/csrf/CsrfAbstractIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung.security.csrf; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; -import javax.servlet.Filter; +import jakarta.servlet.Filter; import com.baeldung.web.dto.Foo; import org.junit.Before; diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityConfig.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityConfig.java index d2553ac2a8..0aba57ea73 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityConfig.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityConfig.java @@ -3,11 +3,13 @@ package com.baeldung.security.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @@ -15,7 +17,7 @@ import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true) +@EnableMethodSecurity public class ManualSecurityConfig { @Bean @@ -34,7 +36,7 @@ public class ManualSecurityConfig { @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring() - .antMatchers("/resources/**"); + .requestMatchers("/resources/**"); } @Bean @@ -45,20 +47,13 @@ public class ManualSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.authorizeRequests() - .mvcMatchers("/custom/login") - .permitAll() - .anyRequest() - .authenticated() - .and() - .httpBasic() - .and() - .headers() - .cacheControl() - .disable() - .and() - .csrf() - .disable(); + http.csrf(AbstractHttpConfigurer::disable) + .httpBasic(Customizer.withDefaults()) + .headers(headers -> headers.cacheControl((cacheControl) -> cacheControl.disable())) + .authorizeHttpRequests(auth -> auth.requestMatchers("/custom/login") + .permitAll() + .anyRequest() + .authenticated()); return http.build(); } diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityIntegrationTest.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityIntegrationTest.java index 002ba8df3e..bf21c3a402 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityIntegrationTest.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/ManualSecurityIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung.security.spring; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import com.baeldung.spring.MvcConfig; import org.junit.Before; diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java index a1a7c8bc54..a1070be9cd 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfConfig.java @@ -3,11 +3,14 @@ package com.baeldung.security.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @@ -15,7 +18,7 @@ import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true) +@EnableMethodSecurity public class SecurityWithCsrfConfig { @Bean @@ -40,22 +43,17 @@ public class SecurityWithCsrfConfig { @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring() - .antMatchers("/resources/**"); + .requestMatchers("/resources/**"); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/auth/admin/*") - .hasAnyRole("ROLE_ADMIN") - .anyRequest() - .authenticated() - .and() - .httpBasic() - .and() - .headers() - .cacheControl() - .disable(); + http.httpBasic(Customizer.withDefaults()) + .headers(headers -> headers.cacheControl((cacheControl) -> cacheControl.disable())) + .authorizeHttpRequests(auth -> auth.requestMatchers("/auth/admin/*") + .hasAnyRole("ADMIN") + .anyRequest() + .authenticated()); return http.build(); } diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfCookieConfig.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfCookieConfig.java index a34fa4c704..d10606eba0 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfCookieConfig.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithCsrfCookieConfig.java @@ -3,8 +3,9 @@ package com.baeldung.security.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; @@ -16,7 +17,7 @@ import org.springframework.security.web.csrf.CookieCsrfTokenRepository; @Configuration @EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true) +@EnableMethodSecurity public class SecurityWithCsrfCookieConfig { @Bean @@ -41,26 +42,19 @@ public class SecurityWithCsrfCookieConfig { @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring() - .antMatchers("/resources/**"); + .requestMatchers("/resources/**"); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/auth/admin/*") - .hasAnyRole("ROLE_ADMIN") - .anyRequest() - .authenticated() - .and() - .httpBasic() - .and() - .headers() - .cacheControl() - .disable() - // Stateless API CSRF configuration - .and() - .csrf() - .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); + // Stateless API CSRF configuration + http.csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())) + .httpBasic(Customizer.withDefaults()) + .headers(headers -> headers.cacheControl((cacheControl) -> cacheControl.disable())) + .authorizeHttpRequests(auth -> auth.requestMatchers("/auth/admin/*") + .hasAnyRole("ADMIN") + .anyRequest() + .authenticated()); return http.build(); } diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java index 20df0f4d6d..a70c71f3b4 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/security/spring/SecurityWithoutCsrfConfig.java @@ -3,11 +3,13 @@ package com.baeldung.security.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.provisioning.InMemoryUserDetailsManager; @@ -15,7 +17,7 @@ import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true) +@EnableMethodSecurity public class SecurityWithoutCsrfConfig { @Bean @@ -28,11 +30,11 @@ public class SecurityWithoutCsrfConfig { public InMemoryUserDetailsManager userDetailsService() { UserDetails user = User.withUsername("user1") .password("user1Pass") - .authorities("ROLE_USER") + .authorities("USER") .build(); UserDetails admin = User.withUsername("admin") .password("adminPass") - .authorities("ROLE_ADMIN") + .authorities("ADMIN") .build(); return new InMemoryUserDetailsManager(user, admin); } @@ -40,25 +42,18 @@ public class SecurityWithoutCsrfConfig { @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring() - .antMatchers("/resources/**"); + .requestMatchers("/resources/**"); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/auth/admin/*") - .hasAnyRole("ROLE_ADMIN") - .anyRequest() - .authenticated() - .and() - .httpBasic() - .and() - .headers() - .cacheControl() - .disable() - .and() - .csrf() - .disable(); + http.csrf(AbstractHttpConfigurer::disable) + .httpBasic(Customizer.withDefaults()) + .headers(headers -> headers.cacheControl((cacheControl) -> cacheControl.disable())) + .authorizeHttpRequests(auth -> auth.requestMatchers("/auth/admin/*") + .hasAnyRole("ADMIN") + .anyRequest() + .authenticated()); return http.build(); } diff --git a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java index 873c28c6a2..c17769e081 100644 --- a/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java +++ b/spring-security-modules/spring-security-web-mvc-custom/src/test/java/com/baeldung/web/interceptor/SessionTimerInterceptorIntegrationTest.java @@ -3,7 +3,7 @@ package com.baeldung.web.interceptor; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import javax.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSession; import com.baeldung.security.spring.SecurityWithoutCsrfConfig; import com.baeldung.spring.MvcConfig; diff --git a/spring-security-modules/spring-security-web-persistent-login/pom.xml b/spring-security-modules/spring-security-web-persistent-login/pom.xml index beafc10ffd..cdd3441ddc 100644 --- a/spring-security-modules/spring-security-web-persistent-login/pom.xml +++ b/spring-security-modules/spring-security-web-persistent-login/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-spring-5 + parent-spring-6 0.0.1-SNAPSHOT - ../../parent-spring-5 + ../../parent-spring-6 @@ -20,17 +20,17 @@ org.springframework.security spring-security-web - ${org.springframework.security.version} + ${spring.version} org.springframework.security spring-security-config - ${org.springframework.security.version} + ${spring.version} org.springframework.security spring-security-taglibs - ${org.springframework.security.version} + ${spring.version} org.springframework @@ -91,15 +91,15 @@ - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} + jakarta.servlet + jakarta.servlet-api + ${jakarta.servlet-api} provided - javax.servlet - jstl - ${jstl.version} + jakarta.servlet.jsp.jstl + jakarta.servlet.jsp.jstl-api + ${jakarta.servlet.jsp.jstl-api} runtime @@ -167,13 +167,12 @@ - - 4.2.6.RELEASE + 6.0.0 + 3.0.0 9.4.1212 1.6.1 - 1.5.10.RELEASE \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java index 5d3c59be11..d539bae243 100644 --- a/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java +++ b/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/security/MySimpleUrlAuthenticationSuccessHandler.java @@ -3,10 +3,6 @@ package com.baeldung.security; import java.io.IOException; import java.util.Collection; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.core.Authentication; @@ -17,6 +13,10 @@ import org.springframework.security.web.WebAttributes; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpSession; + @Component(value = "mySimpleUrlAuthenticationSuccessHandler") public class MySimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler { diff --git a/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/spring/MvcConfig.java b/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/spring/MvcConfig.java index 6fa3b522e7..f017deb5e8 100644 --- a/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/spring/MvcConfig.java +++ b/spring-security-modules/spring-security-web-persistent-login/src/main/java/com/baeldung/spring/MvcConfig.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @@ -16,7 +16,7 @@ import org.springframework.web.servlet.view.JstlView; @EnableWebMvc @ComponentScan("com.baeldung") @Configuration -public class MvcConfig extends WebMvcConfigurerAdapter { +public class MvcConfig implements WebMvcConfigurer { public MvcConfig() { super(); @@ -24,7 +24,6 @@ public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(final ViewControllerRegistry registry) { - super.addViewControllers(registry); registry.addViewController("/anonymous.html"); registry.addViewController("/login.html"); registry.addViewController("/homepage.html"); diff --git a/spring-security-modules/spring-security-web-persistent-login/src/main/resources/webSecurityConfig.xml b/spring-security-modules/spring-security-web-persistent-login/src/main/resources/webSecurityConfig.xml index 9fc3f7f355..3ccc866d3b 100644 --- a/spring-security-modules/spring-security-web-persistent-login/src/main/resources/webSecurityConfig.xml +++ b/spring-security-modules/spring-security-web-persistent-login/src/main/resources/webSecurityConfig.xml @@ -2,7 +2,7 @@ auth.requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html") + .permitAll() + .anyRequest() + .authenticated()) + .httpBasic(Customizer.withDefaults()); return http.build(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception { auth.inMemoryAuthentication() - .withUser("user") - .password(passwordEncoder.encode("password")) - .roles("USER"); + .withUser("user") + .password(passwordEncoder.encode("password")) + .roles("USER"); } - + } diff --git a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/config/SecurityConfiguration.java b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/config/SecurityConfiguration.java index 2b849031ce..6e5e99bcb1 100644 --- a/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/config/SecurityConfiguration.java +++ b/spring-security-modules/spring-security-web-springdoc/src/main/java/com/baeldung/formlogin/config/SecurityConfiguration.java @@ -6,7 +6,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; @@ -16,25 +16,21 @@ public class SecurityConfiguration { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http - .csrf().disable() - .authorizeRequests() - .antMatchers("/v3/api-docs/**", - "/swagger-ui/**", - "/swagger-ui.html").permitAll() - .anyRequest().authenticated() - .and() - .formLogin() - .defaultSuccessUrl("/foos"); + http.csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests(auth -> auth.requestMatchers("/v3/api-docs/**", "/swagger-ui/**", "/swagger-ui.html") + .permitAll() + .anyRequest() + .authenticated()) + .formLogin(formLogin -> formLogin.defaultSuccessUrl("/foos")); return http.build(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth, PasswordEncoder passwordEncoder) throws Exception { auth.inMemoryAuthentication() - .withUser("user") - .password(passwordEncoder.encode("password")) - .roles("USER"); + .withUser("user") + .password(passwordEncoder.encode("password")) + .roles("USER"); } - + } diff --git a/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/basicauth/OpenAPIIntegrationTest.java b/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/basicauth/OpenAPIIntegrationTest.java index 3e622059c1..f07ad4f4fc 100644 --- a/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/basicauth/OpenAPIIntegrationTest.java +++ b/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/basicauth/OpenAPIIntegrationTest.java @@ -4,7 +4,7 @@ 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; diff --git a/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/formlogin/OpenAPIIntegrationTest.java b/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/formlogin/OpenAPIIntegrationTest.java index 5d942f2126..85e8152399 100644 --- a/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/formlogin/OpenAPIIntegrationTest.java +++ b/spring-security-modules/spring-security-web-springdoc/src/test/java/com/baeldung/formlogin/OpenAPIIntegrationTest.java @@ -4,7 +4,7 @@ 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; diff --git a/spring-vault/pom.xml b/spring-vault/pom.xml index 72165e6424..47cd290ee0 100644 --- a/spring-vault/pom.xml +++ b/spring-vault/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -67,12 +67,19 @@ spring-cloud-starter-vault-config ${spring-cloud-starter-vault-config.version} + + org.springframework.data + spring-data-commons + 3.0.8 + - 2.3.4 - 2.20.140 - 3.1.3 + 3.0.4 + 2.25.6 + 4.0.2 + 17 + com.baeldung.springvault.SpringVaultApplication \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-2/pom.xml b/spring-web-modules/spring-mvc-basics-2/pom.xml index 32cf3c9e9f..f79671ae63 100644 --- a/spring-web-modules/spring-mvc-basics-2/pom.xml +++ b/spring-web-modules/spring-mvc-basics-2/pom.xml @@ -157,7 +157,7 @@ 1.9.0 1.4.9 5.1.0 - 20180130 + 20240303 1.6.1 2.5.6 diff --git a/spring-web-modules/spring-mvc-basics-5/pom.xml b/spring-web-modules/spring-mvc-basics-5/pom.xml index fe36bed5b4..cac49da5c0 100644 --- a/spring-web-modules/spring-mvc-basics-5/pom.xml +++ b/spring-web-modules/spring-mvc-basics-5/pom.xml @@ -81,7 +81,7 @@ - 2.8.0 + 2.9.0 2.3.5 2.0.0 3.0.0 diff --git a/spring-web-modules/spring-mvc-java/pom.xml b/spring-web-modules/spring-mvc-java/pom.xml index e7c66ac0ee..30bf3327e6 100644 --- a/spring-web-modules/spring-mvc-java/pom.xml +++ b/spring-web-modules/spring-mvc-java/pom.xml @@ -210,7 +210,7 @@ 5.0.0-M1 6.1.0-M1 4.0.0-M1 - 2.8.0 + 2.9.0 com.baeldung.SpringMVCApplication 3.0.0 5.4.0 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/spring-web-modules/spring-resttemplate-1/pom.xml b/spring-web-modules/spring-resttemplate-1/pom.xml index 209c941ede..5900e816ed 100644 --- a/spring-web-modules/spring-resttemplate-1/pom.xml +++ b/spring-web-modules/spring-resttemplate-1/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -27,4 +27,8 @@ + + com.baeldung.resttemplate.RestTemplateApplication + + \ No newline at end of file diff --git a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java b/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java index 7fa0d55690..aa9ad9699f 100644 --- a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java +++ b/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/lists/client/EmployeeClient.java @@ -46,7 +46,7 @@ public class EmployeeClient { ResponseEntity response = restTemplate.getForEntity( - "http://localhost:8082/spring-rest/employees/", + "http://localhost:8080/spring-rest/employees/", Employee[].class); Employee[] employees = response.getBody(); @@ -64,7 +64,7 @@ public class EmployeeClient { ResponseEntity> response = restTemplate.exchange( - "http://localhost:8082/spring-rest/employees/", + "http://localhost:8080/spring-rest/employees/", HttpMethod.GET, null, new ParameterizedTypeReference>() { @@ -83,7 +83,7 @@ public class EmployeeClient { EmployeeList response = restTemplate.getForObject( - "http://localhost:8082/spring-rest/employees/v2", + "http://localhost:8080/spring-rest/employees/v2", EmployeeList.class); List employees = response.getEmployees(); @@ -101,7 +101,7 @@ public class EmployeeClient { newEmployees.add(new Employee(4, "CEO")); restTemplate.postForObject( - "http://localhost:8082/spring-rest/employees/", + "http://localhost:8080/spring-rest/employees/", newEmployees, ResponseEntity.class); } @@ -114,7 +114,7 @@ public class EmployeeClient { newEmployees.add(new Employee(4, "CEO")); restTemplate.postForObject( - "http://localhost:8082/spring-rest/employees/v2/", + "http://localhost:8080/spring-rest/employees/v2", new EmployeeList(newEmployees), ResponseEntity.class); } diff --git a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java b/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java index b3131cc00c..8c74aa9bad 100644 --- a/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java +++ b/spring-web-modules/spring-resttemplate-1/src/main/java/com/baeldung/resttemplate/web/controller/PersonAPI.java @@ -1,6 +1,6 @@ package com.baeldung.resttemplate.web.controller; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import com.baeldung.resttemplate.web.service.PersonService; import com.baeldung.resttemplate.web.dto.Person; diff --git a/spring-web-modules/spring-resttemplate-1/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java b/spring-web-modules/spring-resttemplate-1/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java index f1861ede92..73a408b67f 100644 --- a/spring-web-modules/spring-resttemplate-1/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java +++ b/spring-web-modules/spring-resttemplate-1/src/test/java/com/baeldung/resttemplate/postjson/PersonAPILiveTest.java @@ -41,8 +41,8 @@ public class PersonAPILiveTest { @BeforeClass public static void runBeforeAllTestMethods() throws JSONException { - createPersonUrl = "http://localhost:8082/spring-rest/createPerson"; - updatePersonUrl = "http://localhost:8082/spring-rest/updatePerson"; + createPersonUrl = "http://localhost:8080/spring-rest/createPerson"; + updatePersonUrl = "http://localhost:8080/spring-rest/updatePerson"; restTemplate = new RestTemplate(); diff --git a/spring-web-modules/spring-resttemplate-2/README.md b/spring-web-modules/spring-resttemplate-2/README.md index ad2a671040..1709e544fc 100644 --- a/spring-web-modules/spring-resttemplate-2/README.md +++ b/spring-web-modules/spring-resttemplate-2/README.md @@ -10,3 +10,4 @@ This module contains articles about Spring RestTemplate - [How to Compress Requests Using the Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-compressing-requests) - [Get list of JSON objects with Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-json-list) - [Spring RestTemplate Exception: “Not enough variables available to expand”](https://www.baeldung.com/spring-not-enough-variables-available) +- [A Guide To Spring Redirects](https://www.baeldung.com/spring-redirect-and-forward) diff --git a/spring-web-modules/spring-thymeleaf-5/README.md b/spring-web-modules/spring-thymeleaf-5/README.md index 31796e251f..72aeba1fb4 100644 --- a/spring-web-modules/spring-thymeleaf-5/README.md +++ b/spring-web-modules/spring-thymeleaf-5/README.md @@ -7,6 +7,6 @@ This module contains articles about Spring with Thymeleaf - [Conditionals in Thymeleaf](https://www.baeldung.com/spring-thymeleaf-conditionals) - [Iteration in Thymeleaf](https://www.baeldung.com/thymeleaf-iteration) - [Spring with Thymeleaf Pagination for a List](https://www.baeldung.com/spring-thymeleaf-pagination) -- [Display Image With Thymeleaf](https://www.baeldung.com/spring-thymeleaf-image) - [How to Check if a Variable Is Defined in Thymeleaf](https://www.baeldung.com/spring-thymeleaf-variable-defined) +- [Display Image With Thymeleaf](https://www.baeldung.com/java-thymeleaf-image) - More articles: [[<-- prev]](../spring-thymeleaf-4) diff --git a/spring-web-modules/spring-web-url/pom.xml b/spring-web-modules/spring-web-url/pom.xml index 258ce88afd..ac50bcd2ae 100644 --- a/spring-web-modules/spring-web-url/pom.xml +++ b/spring-web-modules/spring-web-url/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -27,7 +27,6 @@ org.springframework.boot spring-boot-starter-thymeleaf - provided diff --git a/spring-web-modules/spring-web-url/src/main/java/com/baeldung/exclude_urls_filter/filter/HeaderValidatorFilter.java b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/exclude_urls_filter/filter/HeaderValidatorFilter.java index d6c1777326..2eb5398c8c 100644 --- a/spring-web-modules/spring-web-url/src/main/java/com/baeldung/exclude_urls_filter/filter/HeaderValidatorFilter.java +++ b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/exclude_urls_filter/filter/HeaderValidatorFilter.java @@ -4,9 +4,9 @@ import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.web.filter.OncePerRequestFilter; -import javax.servlet.*; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.*; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; @Order(1) diff --git a/spring-web-modules/spring-web-url/src/main/java/com/baeldung/exclude_urls_filter/filter/LogFilter.java b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/exclude_urls_filter/filter/LogFilter.java index fcde4f7f8f..9409506b13 100644 --- a/spring-web-modules/spring-web-url/src/main/java/com/baeldung/exclude_urls_filter/filter/LogFilter.java +++ b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/exclude_urls_filter/filter/LogFilter.java @@ -5,9 +5,9 @@ import org.slf4j.LoggerFactory; import org.springframework.core.annotation.Order; import org.springframework.web.filter.OncePerRequestFilter; -import javax.servlet.*; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.*; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; @Order(1) diff --git a/spring-web-modules/spring-web-url/src/main/java/com/baeldung/spring/slash/SlashParsingController.java b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/spring/slash/SlashParsingController.java index 07b62a5b4d..11256c79d8 100644 --- a/spring-web-modules/spring-web-url/src/main/java/com/baeldung/spring/slash/SlashParsingController.java +++ b/spring-web-modules/spring-web-url/src/main/java/com/baeldung/spring/slash/SlashParsingController.java @@ -1,6 +1,6 @@ package com.baeldung.spring.slash; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; diff --git a/testing-modules/groovy-spock/src/main/java/com/baeldung/spock/capture/ArgumentCaptureDependency.java b/testing-modules/groovy-spock/src/main/java/com/baeldung/spock/capture/ArgumentCaptureDependency.java new file mode 100644 index 0000000000..5b0637bbca --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/com/baeldung/spock/capture/ArgumentCaptureDependency.java @@ -0,0 +1,9 @@ +package com.baeldung.spock.capture; + +public class ArgumentCaptureDependency { + + public String catchMe(final String input) { + return "***" + input + "***"; + } + +} \ No newline at end of file diff --git a/testing-modules/groovy-spock/src/main/java/com/baeldung/spock/capture/ArgumentCaptureSubject.java b/testing-modules/groovy-spock/src/main/java/com/baeldung/spock/capture/ArgumentCaptureSubject.java new file mode 100644 index 0000000000..71038016fa --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/com/baeldung/spock/capture/ArgumentCaptureSubject.java @@ -0,0 +1,23 @@ +package com.baeldung.spock.capture; + +public class ArgumentCaptureSubject { + + ArgumentCaptureDependency calledClass; + + public ArgumentCaptureSubject(ArgumentCaptureDependency calledClass) { + this.calledClass = calledClass; + } + + public String catchMeIfYouCan(final String input) { + return "Received " + input; + } + + public String callOtherClass() { + return calledClass.catchMe("Internal Parameter"); + } + + public String callOtherClass(final String input) { + return calledClass.catchMe(input); + } + +} diff --git a/testing-modules/groovy-spock/src/test/groovy/com/baeldung/spock/capture/ArgumentCaptureUnitTest.groovy b/testing-modules/groovy-spock/src/test/groovy/com/baeldung/spock/capture/ArgumentCaptureUnitTest.groovy new file mode 100644 index 0000000000..df3960d832 --- /dev/null +++ b/testing-modules/groovy-spock/src/test/groovy/com/baeldung/spock/capture/ArgumentCaptureUnitTest.groovy @@ -0,0 +1,221 @@ +package com.baeldung.spock.capture + + +import spock.lang.PendingFeature +import spock.lang.Specification +import spock.lang.Subject +import spock.lang.Title + +@Title("A selection of tests to demonstrate capturing arguments") +class ArgumentCaptureUnitTest extends Specification { + + // 3. Preparing Our Data-Driven Test + def "given a Stub when we invoke it then we capture the stubbed response"() { + given: "an input and a result" + def input = "Input" + def stubbedResponse = "42" + + and: "a Stub for our response" + @Subject + ArgumentCaptureSubject stubClass = Stub() + stubClass.catchMeIfYouCan(_) >> stubbedResponse + + when: "we invoke our Stub's method" + def result = stubClass.catchMeIfYouCan(input) + + then: "we get our stubbed response" + result == stubbedResponse + } + + + // 4. Capturing Arguments - argument list and a stubbed response + def "given a Stub when we invoke it then we capture the list of arguments and return a stubbed result"() { + given: "an input and a result" + def input = "Input" + def stubbedResponse = "42" + + and: "a variable and a Stub with a Closure to capture our arguments" + def captured + @Subject + ArgumentCaptureSubject stubClass = Stub() + stubClass.catchMeIfYouCan(_) >> { arguments -> captured = arguments; stubbedResponse } + + when: "we invoke our method" + def result = stubClass.catchMeIfYouCan(input) + + then: "what we captured matches the input" + captured[0] == input + result == stubbedResponse + } + + + // 4. Capturing Arguments - single argument + def "given a Stub when we invoke it then we capture the argument"() { + given: "an input and a result" + def input = "Input" + + and: "a variable and a Stub with a Closure to capture our arguments" + @Subject + def captured + ArgumentCaptureSubject stubClass = Stub() + stubClass.catchMeIfYouCan(_) >> { arguments -> captured = arguments[0] } + + when: "we invoke our method" + stubClass.catchMeIfYouCan(input) + + then: "what we captured matches the input" + captured == input + } + + + // 4. Capturing Arguments - single argument and a stubbed response + def "given a Stub when we invoke it then we capture the argument and return a stubbed result"() { + given: "an input and a result" + def input = "Input" + def stubbedResponse = "42" + + and: "a variable and a Stub with a Closure to capture our variable and return a stubbed response" + @Subject + def captured + ArgumentCaptureSubject stubClass = Stub() + stubClass.catchMeIfYouCan(_) >> { arguments -> captured = arguments[0]; stubbedResponse } + + when: "we invoke our method" + def result = stubClass.catchMeIfYouCan(input) + + then: "what we captured matches the input and we got our stubbed response" + captured == input + result == stubbedResponse + } + + + // 5. Capturing with Spies - calling real method + def "given a Spy when we invoke it then we capture the argument and then delegate to the real method"() { + given: "an input string" + def input = "Input" + + and: "a variable and a Spy with a Closure to capture the argument and call the underlying method" + def captured + @Subject + ArgumentCaptureSubject spyClass = Spy() + spyClass.catchMeIfYouCan(_) >> { arguments -> captured = arguments[0]; callRealMethod() } + + when: "we invoke our method" + def result = spyClass.catchMeIfYouCan(input) + + then: "what we captured matches the input and our result comes from the real method" + captured == input + result == "Received Input" + } + + // 5. Capturing with Spies - tampering with the arguments + def "given a Spy when we invoke it then we capture the argument and then delegate to the real method with a different value"() { + given: "an input string" + def input = "Input" + + and: "a variable and a Spy with a Closure to capture and change the first argument then call the underlying method" + def captured + @Subject + ArgumentCaptureSubject spyClass = Spy() + spyClass.catchMeIfYouCan(_) >> { arguments -> captured = arguments[0]; callRealMethodWithArgs('Tampered:' + captured) } + + when: "we invoke our method" + def result = spyClass.catchMeIfYouCan(input) + + then: "what we captured matches the input" + captured == input + result == "Received Tampered:Input" + } + + + // 6. Capturing Arguments Using an Injected Mock + def "given an internal method call when we invoke our subject then we capture the internal argument and return the result of the real method"() { + given: "a variable and a Spy with a Closure to capture the first argument and call the underlying method" + def captured + ArgumentCaptureDependency spyClass = Spy() + spyClass.catchMe(_) >> { arguments -> captured = arguments[0]; callRealMethod() } + + and: "our subject with an injected Spy" + @Subject + def argumentCaptureSubject = new ArgumentCaptureSubject(spyClass) + + when: "we invoke our method" + def result = argumentCaptureSubject.callOtherClass() + + then: "what we captured matches the input" + captured == "Internal Parameter" + result == "***Internal Parameter***" + } + + + // 7. Capturing Multiple Invocations + def "given an dynamic Mock when we invoke our subject then we capture the argument for each invocation"() { + given: "a variable for our captured arguments and a mock to capture them" + def capturedStrings = new ArrayList() + ArgumentCaptureDependency mockClass = Mock() + + and: "our subject" + @Subject + def argumentCaptureSubject = new ArgumentCaptureSubject(mockClass) + + when: "we invoke our method" + argumentCaptureSubject.callOtherClass("First") + argumentCaptureSubject.callOtherClass("Second") + + then: "our method was called twice and captured the argument" + 2 * mockClass.catchMe(_ as String) >> { arguments -> + capturedStrings.add(arguments[0]) + } + + and: "our captured list contains an entry for both of our input values" + capturedStrings[0] == "First" + capturedStrings[1] == "Second" + capturedStrings.contains("First") + capturedStrings.contains("Second") + } + + + // 8. Using Multiple then Blocks + def "given a Mock when we invoke our subject twice then our Mock verifies the sequence"() { + given: "a mock" + ArgumentCaptureDependency mockClass = Mock() + + and: "our subject" + @Subject argumentCaptureSubject = new ArgumentCaptureSubject(mockClass) + + when: "we invoke our method" + argumentCaptureSubject.callOtherClass("First") + argumentCaptureSubject.callOtherClass("Second") + + then: "we invoked our Mock with 'First' the first time" + 1 * mockClass.catchMe( "First") + + then: "we invoked our Mock with 'Second' the next time" + 1 * mockClass.catchMe( "Second") + } + + + // 8. Using Multiple then Blocks - demonstrate error message + @PendingFeature(reason = "Remove this annotation to fail this test and see what message Spock issues when invocations occur in the wrong sequence") + def "given a Mock when we invoke our subject in the wrong order then Spock's Mock detects the wrong sequence"() { + given: "an input string" + def input = "Input" + + and: "a mock and a variable for our captured argument" + ArgumentCaptureDependency mockClass = Mock() + + and: "our subject" + @Subject argumentCaptureSubject = new ArgumentCaptureSubject(mockClass) + + when: "we invoke our method" + argumentCaptureSubject.callOtherClass("Second") + argumentCaptureSubject.callOtherClass("First") + + then: "we invoked our Mock with 'First' the first time" + 1 * mockClass.catchMe( "First") + + then: "we invoked our Mock with 'Second' the next time" + 1 * mockClass.catchMe( "Second") + } + +} diff --git a/testing-modules/junit-5-advanced-2/README.md b/testing-modules/junit-5-advanced-2/README.md index 3a98488398..881a104c34 100644 --- a/testing-modules/junit-5-advanced-2/README.md +++ b/testing-modules/junit-5-advanced-2/README.md @@ -1,3 +1,3 @@ ## Relevant Articles: -- [Solving the ParameterResolutionException in JUnit 5](https://www.baeldung.com/solving-the-parameterresolutionexception-in-junit-5/) +- [Solving the ParameterResolutionException in JUnit 5](https://www.baeldung.com/junit-5-parameterresolutionexception) diff --git a/testing-modules/junit5-annotations/README.md b/testing-modules/junit5-annotations/README.md index 53e409151b..b7efaa1ee8 100644 --- a/testing-modules/junit5-annotations/README.md +++ b/testing-modules/junit5-annotations/README.md @@ -3,7 +3,7 @@ This module contains articles about JUnit 5 Annotations ### Relevant Articles: -- [A Guide to @RepeatedTest in Junit 5](https://www.baeldung.com/junit-5-repeated-test) +- [A Guide to @RepeatedTest in JUnit 5](https://www.baeldung.com/junit-5-repeated-test) - [JUnit 5 Conditional Test Execution with Annotations](https://www.baeldung.com/junit-5-conditional-test-execution) - [JUnit5 Programmatic Extension Registration with @RegisterExtension](https://www.baeldung.com/junit-5-registerextension-annotation) - [Guide to JUnit 5 Parameterized Tests](https://www.baeldung.com/parameterized-tests-junit-5) 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/rest-assured/pom.xml b/testing-modules/rest-assured/pom.xml index 47df64c56f..c5cfc79915 100644 --- a/testing-modules/rest-assured/pom.xml +++ b/testing-modules/rest-assured/pom.xml @@ -28,11 +28,6 @@ spring-boot-starter-test test - - com.google.guava - guava - ${guava.version} - javax.servlet javax.servlet-api 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/testing-modules/spring-testing/pom.xml b/testing-modules/spring-testing/pom.xml index 665ac305a0..a201d3c126 100644 --- a/testing-modules/spring-testing/pom.xml +++ b/testing-modules/spring-testing/pom.xml @@ -8,13 +8,14 @@ 0.1-SNAPSHOT spring-testing + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + + - - ch.qos.logback - logback-classic - 1.5.0 - test - org.hamcrest java-hamcrest @@ -29,7 +30,6 @@ org.springframework.boot spring-boot-starter - 3.2.2 org.springframework.boot @@ -40,53 +40,43 @@ org.springframework.boot spring-boot - 3.2.2 org.springframework.data spring-data-jpa - 3.2.2 org.springframework.data spring-data-commons - 3.2.2 org.springframework spring-beans - ${spring.version} org.springframework spring-core - ${spring.version} compile org.springframework spring-context - ${spring.version} org.springframework spring-expression - ${spring.version} org.springframework spring-test - ${spring.version} org.springframework spring-web - ${spring.version} org.springframework spring-webmvc - ${spring.version} org.eclipse.persistence @@ -102,14 +92,12 @@ jakarta.servlet jakarta.servlet-api - 6.0.0 org.springframework.boot spring-boot-starter-test test - 3.2.2 org.springframework.boot @@ -120,13 +108,13 @@ org.junit.jupiter junit-jupiter - 5.9.2 + ${junit-jupiter.version} test org.junit.vintage junit-vintage-engine - 5.9.2 + ${junit-jupiter.version} test @@ -157,6 +145,9 @@ 3.1.6 6.1.3 2.1.1 + true + 3.2.2 + 5.10.2 \ No newline at end of file diff --git a/text-processing-libraries-modules/pdf-2/README.md b/text-processing-libraries-modules/pdf-2/README.md index 12c0934543..c3eaa2018a 100644 --- a/text-processing-libraries-modules/pdf-2/README.md +++ b/text-processing-libraries-modules/pdf-2/README.md @@ -1,3 +1,4 @@ ## Relevant articles - [Editing Existing PDF Files in Java](https://www.baeldung.com/java-edit-existing-pdf) - [Get Information About a PDF in Java](https://www.baeldung.com/java-pdf-info) +- [Convert Excel Files to PDF Using Java](https://www.baeldung.com/java-convert-excel-files-pdf) 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/javax-servlets-2/pom.xml b/web-modules/javax-servlets-2/pom.xml index a6bfc6b473..a792f6eea2 100644 --- a/web-modules/javax-servlets-2/pom.xml +++ b/web-modules/javax-servlets-2/pom.xml @@ -59,7 +59,7 @@ org.apache.httpcomponents httpclient - ${org.apache.httpcomponents.version} + ${httpclient.version} test @@ -106,7 +106,7 @@ - 4.5.13 + 4.5.13 1.49 5.3.20 2.22.2 diff --git a/web-modules/javax-servlets/pom.xml b/web-modules/javax-servlets/pom.xml index 406cfc05c1..ba585d36f6 100644 --- a/web-modules/javax-servlets/pom.xml +++ b/web-modules/javax-servlets/pom.xml @@ -31,7 +31,7 @@ org.apache.httpcomponents httpclient - ${org.apache.httpcomponents.version} + ${httpclient.version} test @@ -48,7 +48,7 @@ - 4.5.3 + 4.5.3 2.10.1 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); } diff --git a/web-modules/jooby/pom.xml b/web-modules/jooby/pom.xml index c298ea8729..0c4cb56c58 100644 --- a/web-modules/jooby/pom.xml +++ b/web-modules/jooby/pom.xml @@ -44,7 +44,7 @@ com.squareup.okhttp3 okhttp - ${squareup.okhttp.version} + ${okhttp.version} @@ -61,7 +61,7 @@ maven-compiler-plugin - ${maven-compiler.version} + ${maven-compiler-plugin.version} -parameters @@ -76,8 +76,7 @@ 3.1.1 com.baeldung.jooby.App 3.2.4 - 5.0.0-alpha.12 - 3.12.1 + 5.0.0-alpha.12 \ No newline at end of file diff --git a/web-modules/ratpack/pom.xml b/web-modules/ratpack/pom.xml index 1ef358cc55..3f93f25bef 100644 --- a/web-modules/ratpack/pom.xml +++ b/web-modules/ratpack/pom.xml @@ -29,7 +29,7 @@ org.codehaus.groovy groovy-sql - ${groovy.sql.version} + ${groovy-sql.version} io.ratpack @@ -104,7 +104,7 @@ 4.5.3 4.4.6 1.5.12 - 2.4.15 + 2.4.15 1.6.1 diff --git a/web-modules/resteasy/pom.xml b/web-modules/resteasy/pom.xml index 355dcdb9b5..edc75fe4c7 100644 --- a/web-modules/resteasy/pom.xml +++ b/web-modules/resteasy/pom.xml @@ -40,7 +40,7 @@ javax.servlet javax.servlet-api - 4.0.1 + ${javax.servlet-api.version} diff --git a/web-modules/spark-java/pom.xml b/web-modules/spark-java/pom.xml index e49be68319..22bbac92bc 100644 --- a/web-modules/spark-java/pom.xml +++ b/web-modules/spark-java/pom.xml @@ -20,17 +20,16 @@ spark-core ${sparkjava.spark-core.version} - com.google.code.gson gson - ${google.code.gson.version} + ${gson.version} 2.5.4 - 2.10.1 + 2.10.1 \ No newline at end of file diff --git a/xml-2/pom.xml b/xml-2/pom.xml index 12240c2c99..e8c4079f59 100644 --- a/xml-2/pom.xml +++ b/xml-2/pom.xml @@ -85,7 +85,7 @@ 2.1.3 - 20230227 + 20240303 1.89 1.4.18 2.3.3