diff --git a/akka-modules/akka-actors/README.md b/akka-modules/akka-actors/README.md new file mode 100644 index 0000000000..20611aee6a --- /dev/null +++ b/akka-modules/akka-actors/README.md @@ -0,0 +1,7 @@ +## Akka HTTP + +This module contains articles about Akka actors. + +### Relevant articles: + +- [Introduction to Akka Actors in Java](https://www.baeldung.com/akka-actors-java) diff --git a/akka-modules/akka-actors/pom.xml b/akka-modules/akka-actors/pom.xml new file mode 100644 index 0000000000..f354b13bd9 --- /dev/null +++ b/akka-modules/akka-actors/pom.xml @@ -0,0 +1,33 @@ + + + 4.0.0 + akka-actors + akka-actors + + + com.baeldung + akka-modules + 1.0.0-SNAPSHOT + + + + + com.typesafe.akka + akka-actor_${scala.version} + ${typesafe-akka.version} + + + com.typesafe.akka + akka-testkit_${scala.version} + ${typesafe-akka.version} + test + + + + + 2.5.11 + + + \ No newline at end of file diff --git a/libraries-5/src/main/java/com/baeldung/akka/FirstActor.java b/akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/FirstActor.java similarity index 95% rename from libraries-5/src/main/java/com/baeldung/akka/FirstActor.java rename to akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/FirstActor.java index 9680429fb1..1d166604ee 100644 --- a/libraries-5/src/main/java/com/baeldung/akka/FirstActor.java +++ b/akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/FirstActor.java @@ -1,4 +1,4 @@ -package com.baeldung.akka; +package com.baeldung.akkaactors; import akka.actor.AbstractActor; import akka.actor.Props; diff --git a/libraries-5/src/main/java/com/baeldung/akka/MyActor.java b/akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/MyActor.java similarity index 95% rename from libraries-5/src/main/java/com/baeldung/akka/MyActor.java rename to akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/MyActor.java index 99ee3158b6..2149242c19 100644 --- a/libraries-5/src/main/java/com/baeldung/akka/MyActor.java +++ b/akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/MyActor.java @@ -1,4 +1,4 @@ -package com.baeldung.akka; +package com.baeldung.akkaactors; import akka.actor.AbstractActor; import akka.event.Logging; diff --git a/libraries-5/src/main/java/com/baeldung/akka/PrinterActor.java b/akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/PrinterActor.java similarity index 97% rename from libraries-5/src/main/java/com/baeldung/akka/PrinterActor.java rename to akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/PrinterActor.java index 55b6e4e0f4..85a4fcc7ad 100644 --- a/libraries-5/src/main/java/com/baeldung/akka/PrinterActor.java +++ b/akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/PrinterActor.java @@ -1,4 +1,4 @@ -package com.baeldung.akka; +package com.baeldung.akkaactors; import akka.actor.AbstractActor; import akka.actor.Props; diff --git a/libraries-5/src/main/java/com/baeldung/akka/ReadingActor.java b/akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/ReadingActor.java similarity index 98% rename from libraries-5/src/main/java/com/baeldung/akka/ReadingActor.java rename to akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/ReadingActor.java index f1a21c8e28..bc68754364 100644 --- a/libraries-5/src/main/java/com/baeldung/akka/ReadingActor.java +++ b/akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/ReadingActor.java @@ -1,4 +1,4 @@ -package com.baeldung.akka; +package com.baeldung.akkaactors; import akka.actor.AbstractActor; import akka.actor.ActorRef; diff --git a/libraries-5/src/main/java/com/baeldung/akka/WordCounterActor.java b/akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/WordCounterActor.java similarity index 97% rename from libraries-5/src/main/java/com/baeldung/akka/WordCounterActor.java rename to akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/WordCounterActor.java index 3e23683971..07eb6f4aa2 100644 --- a/libraries-5/src/main/java/com/baeldung/akka/WordCounterActor.java +++ b/akka-modules/akka-actors/src/main/java/com/baeldung/akkaactors/WordCounterActor.java @@ -1,4 +1,4 @@ -package com.baeldung.akka; +package com.baeldung.akkaactors; import akka.actor.AbstractActor; import akka.event.Logging; diff --git a/libraries-5/src/test/java/com/baeldung/akka/AkkaActorsUnitTest.java b/akka-modules/akka-actors/src/test/java/com/baeldung/akkaactors/AkkaActorsUnitTest.java similarity index 99% rename from libraries-5/src/test/java/com/baeldung/akka/AkkaActorsUnitTest.java rename to akka-modules/akka-actors/src/test/java/com/baeldung/akkaactors/AkkaActorsUnitTest.java index adaff86565..362aef4600 100644 --- a/libraries-5/src/test/java/com/baeldung/akka/AkkaActorsUnitTest.java +++ b/akka-modules/akka-actors/src/test/java/com/baeldung/akkaactors/AkkaActorsUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.akka; +package com.baeldung.akkaactors; import akka.actor.ActorRef; import akka.actor.ActorSystem; diff --git a/akka-modules/pom.xml b/akka-modules/pom.xml index 3a9d5e41ff..60432c4eea 100644 --- a/akka-modules/pom.xml +++ b/akka-modules/pom.xml @@ -14,6 +14,7 @@ + akka-actors akka-http akka-streams spring-akka diff --git a/apache-httpclient-2/pom.xml b/apache-httpclient-2/pom.xml index 8b7217dbe1..92b10a0992 100644 --- a/apache-httpclient-2/pom.xml +++ b/apache-httpclient-2/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java + parent-modules + 1.0.0-SNAPSHOT @@ -74,11 +73,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source.version} - ${maven.compiler.target.version} - @@ -87,8 +81,6 @@ 3.22.0 5.11.2 5.2.1 - 11 - 11 2.1.7.RELEASE diff --git a/apache-httpclient/pom.xml b/apache-httpclient/pom.xml index f671c93cfc..b44df09dd3 100644 --- a/apache-httpclient/pom.xml +++ b/apache-httpclient/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java + parent-modules + 1.0.0-SNAPSHOT diff --git a/apache-kafka-2/pom.xml b/apache-kafka-2/pom.xml index dedd5df602..68d547d489 100644 --- a/apache-kafka-2/pom.xml +++ b/apache-kafka-2/pom.xml @@ -61,9 +61,9 @@ 5.7.0 - 2.8.0 + 3.6.1 1.19.3 - 1.15.3 + 1.19.3 2.15.2 diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/consumer/CustomKafkaListener.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/consumer/CustomKafkaListener.java new file mode 100644 index 0000000000..f4cefb21eb --- /dev/null +++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/consumer/CustomKafkaListener.java @@ -0,0 +1,56 @@ +package com.baeldung.kafka.consumer; + +import java.io.Closeable; +import java.time.Duration; +import java.util.Arrays; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import java.util.logging.Logger; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.clients.consumer.KafkaConsumer; +import org.apache.kafka.common.serialization.StringDeserializer; + +public class CustomKafkaListener implements Runnable { + private static final Logger log = Logger.getLogger(CustomKafkaListener.class.getName()); + private final String topic; + private final KafkaConsumer consumer; + private Consumer recordConsumer; + + + public CustomKafkaListener(String topic, KafkaConsumer consumer) { + this.topic = topic; + this.consumer = consumer; + this.recordConsumer = record -> log.info("received: " + record); + } + + public CustomKafkaListener(String topic, String bootstrapServers) { + this(topic, defaultKafkaConsumer(bootstrapServers)); + } + + private static KafkaConsumer defaultKafkaConsumer(String boostrapServers) { + Properties props = new Properties(); + props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, boostrapServers); + props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "test_group_id"); + props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); + return new KafkaConsumer<>(props); + } + + public CustomKafkaListener onEach(Consumer newConsumer) { + recordConsumer = recordConsumer.andThen(newConsumer); + return this; + } + + @Override + public void run() { + consumer.subscribe(Arrays.asList(topic)); + while (true) { + consumer.poll(Duration.ofMillis(100)) + .forEach(record -> recordConsumer.accept(record.value())); + } + } + +} diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/consumer/CustomKafkaListenerLiveTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/consumer/CustomKafkaListenerLiveTest.java new file mode 100644 index 0000000000..201a72114d --- /dev/null +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/consumer/CustomKafkaListenerLiveTest.java @@ -0,0 +1,82 @@ +package com.baeldung.kafka.consumer; + +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 java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.CompletableFuture; + +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.StringSerializer; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.KafkaContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.shaded.org.awaitility.Awaitility; +import org.testcontainers.utility.DockerImageName; + +@Testcontainers +class CustomKafkaListenerLiveTest { + + @Container + private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); + + static { + Awaitility.setDefaultTimeout(ofSeconds(5L)); + Awaitility.setDefaultPollInterval(ofMillis(50L)); + } + + @Test + void givenANewCustomKafkaListener_thenConsumesAllMessages() { + // given + String topic = "baeldung.articles.published"; + String bootstrapServers = KAFKA_CONTAINER.getBootstrapServers(); + List consumedMessages = new ArrayList<>(); + + // when + CustomKafkaListener listener = new CustomKafkaListener(topic, bootstrapServers).onEach(consumedMessages::add); + CompletableFuture.runAsync(listener); + + // and + publishArticles(topic, + "Introduction to Kafka", + "Kotlin for Java Developers", + "Reactive Spring Boot", + "Deploying Spring Boot Applications", + "Spring Security" + ); + + // then + await().untilAsserted(() -> + assertThat(consumedMessages).containsExactlyInAnyOrder( + "Introduction to Kafka", + "Kotlin for Java Developers", + "Reactive Spring Boot", + "Deploying Spring Boot Applications", + "Spring Security" + )); + } + + private void publishArticles(String topic, String... articles) { + try (KafkaProducer producer = testKafkaProducer()) { + Arrays.stream(articles) + .map(article -> new ProducerRecord<>(topic, "key-1", article)) + .forEach(producer::send); + } + } + + private static KafkaProducer testKafkaProducer() { + Properties props = new Properties(); + props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); + return new KafkaProducer<>(props); + } +} \ No newline at end of file diff --git a/apache-kafka/pom.xml b/apache-kafka/pom.xml index 22be7a83c6..6aa5fb894a 100644 --- a/apache-kafka/pom.xml +++ b/apache-kafka/pom.xml @@ -181,6 +181,7 @@ + 2.13.4 3.4.0 1.19.3 1.15.3 diff --git a/apache-kafka/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java b/apache-kafka/src/test/java/com/baeldung/flink/BackupCreatorUnitTest.java similarity index 99% rename from apache-kafka/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java rename to apache-kafka/src/test/java/com/baeldung/flink/BackupCreatorUnitTest.java index f46fffbb59..046a9bb9ec 100644 --- a/apache-kafka/src/test/java/com/baeldung/flink/BackupCreatorIntegrationTest.java +++ b/apache-kafka/src/test/java/com/baeldung/flink/BackupCreatorUnitTest.java @@ -29,7 +29,7 @@ import java.util.List; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; -public class BackupCreatorIntegrationTest { +public class BackupCreatorUnitTest { public static ObjectMapper mapper; @Before diff --git a/apache-kafka/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java b/apache-kafka/src/test/java/com/baeldung/flink/WordCapitalizerUnitTest.java similarity index 95% rename from apache-kafka/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java rename to apache-kafka/src/test/java/com/baeldung/flink/WordCapitalizerUnitTest.java index 8a98dae4b5..c521cfa62e 100644 --- a/apache-kafka/src/test/java/com/baeldung/flink/WordCapitalizerIntegrationTest.java +++ b/apache-kafka/src/test/java/com/baeldung/flink/WordCapitalizerUnitTest.java @@ -10,7 +10,7 @@ import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -public class WordCapitalizerIntegrationTest { +public class WordCapitalizerUnitTest { @Test public void givenDataSet_whenExecuteWordCapitalizer_thenReturnCapitalizedWords() throws Exception { diff --git a/apache-kafka/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java b/apache-kafka/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java index 3b559b619e..c733a4a1f4 100644 --- a/apache-kafka/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java +++ b/apache-kafka/src/test/java/com/baeldung/kafkastreams/KafkaStreamsLiveTest.java @@ -21,8 +21,7 @@ import org.junit.Ignore; import org.junit.Test; public class KafkaStreamsLiveTest { - private String bootstrapServers = "localhost:9092"; - private Path stateDirectory; + private final String bootstrapServers = "localhost:9092"; @Test @Ignore("it needs to have kafka broker running on local") @@ -44,8 +43,8 @@ public class KafkaStreamsLiveTest { // Use a temporary directory for storing state, which will be automatically removed after the test. try { - this.stateDirectory = Files.createTempDirectory("kafka-streams"); - streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, this.stateDirectory.toAbsolutePath() + Path stateDirectory = Files.createTempDirectory("kafka-streams"); + streamsConfiguration.put(StreamsConfig.STATE_DIR_CONFIG, stateDirectory.toAbsolutePath() .toString()); } catch (final IOException e) { throw new UncheckedIOException("Cannot create temporary directory", e); diff --git a/asm/README.md b/asm/README.md deleted file mode 100644 index e10cdc45bd..0000000000 --- a/asm/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## ASM - -This module contains articles about ASM - -### Relevant Articles: - -- [A Guide to Java Bytecode Manipulation with ASM](https://www.baeldung.com/java-asm) diff --git a/asm/pom.xml b/asm/pom.xml deleted file mode 100644 index 4edfe86ae5..0000000000 --- a/asm/pom.xml +++ /dev/null @@ -1,54 +0,0 @@ - - - 4.0.0 - com.baeldung.examples - asm - 1.0 - asm - jar - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.ow2.asm - asm - ${asm.version} - - - org.ow2.asm - asm-util - ${asm.version} - - - - - - - org.apache.maven.plugins - maven-jar-plugin - ${maven-jar-plugin.version} - - - - - com.baeldung.examples.asm.instrumentation.Premain - - - - - - - - - - 5.2 - - - \ No newline at end of file diff --git a/aws-modules/aws-dynamodb/pom.xml b/aws-modules/aws-dynamodb/pom.xml index 155d48c240..199b9a187e 100644 --- a/aws-modules/aws-dynamodb/pom.xml +++ b/aws-modules/aws-dynamodb/pom.xml @@ -40,22 +40,6 @@ - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - false - - - - package - - shade - - - - org.apache.maven.plugins maven-dependency-plugin diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml index b6326b6eb1..f04e84e14f 100644 --- a/aws-modules/aws-miscellaneous/pom.xml +++ b/aws-modules/aws-miscellaneous/pom.xml @@ -34,22 +34,6 @@ - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - false - - - - package - - shade - - - - org.apache.maven.plugins maven-dependency-plugin diff --git a/aws-modules/aws-reactive/pom.xml b/aws-modules/aws-reactive/pom.xml index 22bd62c2ee..e36a2d1a46 100644 --- a/aws-modules/aws-reactive/pom.xml +++ b/aws-modules/aws-reactive/pom.xml @@ -63,6 +63,7 @@ io.projectreactor reactor-test + ${reactor.version} test @@ -93,6 +94,7 @@ 2.2.1.RELEASE 2.17.283 + 3.6.0 \ No newline at end of file diff --git a/aws-modules/aws-s3/pom.xml b/aws-modules/aws-s3/pom.xml index e2bc04964a..9ba436b43f 100644 --- a/aws-modules/aws-s3/pom.xml +++ b/aws-modules/aws-s3/pom.xml @@ -39,27 +39,6 @@ - - - - org.apache.maven.plugins - maven-shade-plugin - ${maven-shade-plugin.version} - - false - - - - package - - shade - - - - - - - 2.20.52 1.10.L001 diff --git a/checker-framework/pom.xml b/checker-framework/pom.xml index d8a44ec0c9..068c543af0 100644 --- a/checker-framework/pom.xml +++ b/checker-framework/pom.xml @@ -31,8 +31,8 @@ + org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} true -Xlint:all diff --git a/core-java-modules/core-java-10/pom.xml b/core-java-modules/core-java-10/pom.xml index 7eccb098a0..40fd75ee02 100644 --- a/core-java-modules/core-java-10/pom.xml +++ b/core-java-modules/core-java-10/pom.xml @@ -26,7 +26,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${maven.compiler.source.version} ${maven.compiler.target.version} diff --git a/core-java-modules/core-java-11/pom.xml b/core-java-modules/core-java-11/pom.xml index 5bbaec0057..7092f4e53d 100644 --- a/core-java-modules/core-java-11/pom.xml +++ b/core-java-modules/core-java-11/pom.xml @@ -48,7 +48,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${maven.compiler.source.version} ${maven.compiler.target.version} diff --git a/core-java-modules/core-java-14/pom.xml b/core-java-modules/core-java-14/pom.xml index 55c50b2a5c..38f640762f 100644 --- a/core-java-modules/core-java-14/pom.xml +++ b/core-java-modules/core-java-14/pom.xml @@ -27,7 +27,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${maven.compiler.release} --enable-preview diff --git a/core-java-modules/core-java-16/pom.xml b/core-java-modules/core-java-16/pom.xml index f8d287880a..c439a5bf12 100644 --- a/core-java-modules/core-java-16/pom.xml +++ b/core-java-modules/core-java-16/pom.xml @@ -27,7 +27,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${maven.compiler.release} --enable-preview diff --git a/core-java-modules/core-java-18/pom.xml b/core-java-modules/core-java-18/pom.xml index 7af6258497..78552d2c70 100644 --- a/core-java-modules/core-java-18/pom.xml +++ b/core-java-modules/core-java-18/pom.xml @@ -19,7 +19,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${maven.compiler.release} --enable-preview diff --git a/core-java-modules/core-java-20/README.md b/core-java-modules/core-java-20/README.md index f859bf9e23..994fbccdbd 100644 --- a/core-java-modules/core-java-20/README.md +++ b/core-java-modules/core-java-20/README.md @@ -1,3 +1,4 @@ ## Relevant Articles - [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values) - [How to Read Zip Files Entries With Java](https://www.baeldung.com/java-read-zip-files) +- [Deserializing JSON to Java Record using Gson](https://www.baeldung.com/java-json-deserialize-record-gson) diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/localdatetoiso/LocalDateToISO.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/localdatetoiso/LocalDateToISO.java new file mode 100644 index 0000000000..e09d823ce4 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/localdatetoiso/LocalDateToISO.java @@ -0,0 +1,44 @@ +package com.baeldung.localdatetoiso; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Date; + +import org.apache.commons.lang3.time.DateFormatUtils; + +import org.joda.time.DateTime; +import org.joda.time.DateTimeZone; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.ISODateTimeFormat; + +import org.apache.commons.lang3.time.FastDateFormat; + +public class LocalDateToISO { + public String formatUsingDateTimeFormatter(LocalDate localDate) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"); + String formattedDate = localDate.atStartOfDay().atOffset(ZoneOffset.UTC).format(formatter); + return formattedDate; + } + + public String formatUsingSimpleDateFormat(LocalDate date) { + Date utilDate = Date.from(date.atStartOfDay(ZoneOffset.UTC).toInstant()); + DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); + String formattedDate = dateFormat.format(utilDate); + return formattedDate; + } + + public String formatUsingJodaTime(org.joda.time.LocalDate localDate) { + org.joda.time.format.DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + return formatter.print(localDate.toDateTimeAtStartOfDay(DateTimeZone.UTC)); + } + + public String formatUsingApacheCommonsLang(LocalDate localDate) { + Date date = Date.from(localDate.atStartOfDay().toInstant(ZoneOffset.UTC)); + String formattedDate = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", TimeZone.getTimeZone("UTC")) + .format(date); + return formattedDate; + } +} diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/monthintervalbetweentwodates/MonthInterval.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/monthintervalbetweentwodates/MonthInterval.java new file mode 100644 index 0000000000..7ad10ab253 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/monthintervalbetweentwodates/MonthInterval.java @@ -0,0 +1,44 @@ +package com.baeldung.monthintervalbetweentwodates; + +import java.util.Calendar; +import java.util.Date; + +public class MonthInterval { + + public int monthsBetween(Date startDate, Date endDate) { + if (startDate == null || endDate == null) { + throw new IllegalArgumentException("Both startDate and endDate must be provided"); + } + + Calendar startCalendar = Calendar.getInstance(); + startCalendar.setTime(startDate); + int startDateTotalMonths = 12 * startCalendar.get(Calendar.YEAR) + startCalendar.get(Calendar.MONTH); + + Calendar endCalendar = Calendar.getInstance(); + endCalendar.setTime(endDate); + int endDateTotalMonths = 12 * endCalendar.get(Calendar.YEAR) + endCalendar.get(Calendar.MONTH); + + return endDateTotalMonths - startDateTotalMonths; + } + + public int monthsBetweenWithDayValue(Date startDate, Date endDate) { + if (startDate == null || endDate == null) { + throw new IllegalArgumentException("Both startDate and endDate must be provided"); + } + + Calendar startCalendar = Calendar.getInstance(); + startCalendar.setTime(startDate); + + int startDateDayOfMonth = startCalendar.get(Calendar.DAY_OF_MONTH); + int startDateTotalMonths = 12 * startCalendar.get(Calendar.YEAR) + startCalendar.get(Calendar.MONTH); + + Calendar endCalendar = Calendar.getInstance(); + endCalendar.setTime(endDate); + + int endDateDayOfMonth = endCalendar.get(Calendar.DAY_OF_MONTH); + int endDateTotalMonths = 12 * endCalendar.get(Calendar.YEAR) + endCalendar.get(Calendar.MONTH); + + return (startDateDayOfMonth > endDateDayOfMonth) ? (endDateTotalMonths - startDateTotalMonths) - 1 : (endDateTotalMonths - startDateTotalMonths); + } + +} diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/localdatetoiso/LocalDateToISOUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/localdatetoiso/LocalDateToISOUnitTest.java new file mode 100644 index 0000000000..1979c91eca --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/localdatetoiso/LocalDateToISOUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.localdatetoiso; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; +import java.time.LocalDate; + +public class LocalDateToISOUnitTest { + @Test + void givenLocalDate_whenUsingDateTimeFormatter_thenISOFormat(){ + LocalDateToISO localDateToISO = new LocalDateToISO(); + LocalDate localDate = LocalDate.of(2023, 11, 6); + + String expected = "2023-11-06T00:00:00.000Z"; + String actual = localDateToISO.formatUsingDateTimeFormatter(localDate); + assertEquals(expected, actual); + } + + @Test + void givenLocalDate_whenUsingSimpleDateFormat_thenISOFormat(){ + LocalDateToISO localDateToISO = new LocalDateToISO(); + LocalDate localDate = LocalDate.of(2023, 11, 6); + + String expected = "2023-11-06T00:00:00.000Z"; + String actual = localDateToISO.formatUsingSimpleDateFormat(localDate); + assertEquals(expected, actual); + } + + @Test + void givenLocalDate_whenUsingJodaTime_thenISOFormat() { + LocalDateToISO localDateToISO = new LocalDateToISO(); + org.joda.time.LocalDate localDate = new org.joda.time.LocalDate(2023, 11, 6); + + String expected = "2023-11-06T00:00:00.000Z"; + String actual = localDateToISO.formatUsingJodaTime(localDate); + assertEquals(expected, actual); + } + + @Test + void givenLocalDate_whenUsingApacheCommonsLang_thenISOFormat() { + LocalDateToISO localDateToISO = new LocalDateToISO(); + LocalDate localDate = LocalDate.of(2023, 11, 6); + + String expected = "2023-11-06T00:00:00.000Z"; + String actual = localDateToISO.formatUsingApacheCommonsLang(localDate); + assertEquals(expected, actual); + } +} diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/monthintervalbetweentwodates/MonthIntervalUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/monthintervalbetweentwodates/MonthIntervalUnitTest.java new file mode 100644 index 0000000000..2cd5638cc8 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/monthintervalbetweentwodates/MonthIntervalUnitTest.java @@ -0,0 +1,93 @@ +package com.baeldung.monthintervalbetweentwodates; + +import org.joda.time.DateTime; +import org.joda.time.Months; +import org.junit.jupiter.api.Test; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.time.Period; +import java.time.YearMonth; +import java.time.temporal.ChronoUnit; +import java.util.Date; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class MonthIntervalUnitTest { + + @Test + void givenTwoDates_whenCalculatingMonthsBetweenUsingJodaTime_thenReturnMonthsDifference() { + DateTime firstDate = new DateTime(2023, 5, 25, 0, 0); + DateTime secondDate = new DateTime(2023, 11, 23, 0, 0); + + int monthsBetween = Months.monthsBetween(firstDate, secondDate) + .getMonths(); + assertEquals(5, monthsBetween); + } + + @Test + void givenTwoDates_whenCalculatingMonthsBetweenUsingJodaTimeSetTimeToFirstDayOfMonth_thenReturnMonthsDifference() { + DateTime firstDate = new DateTime(2023, 5, 25, 0, 0).withDayOfMonth(1); + DateTime secondDate = new DateTime(2023, 11, 23, 0, 0).withDayOfMonth(1); + + int monthsBetween = Months.monthsBetween(firstDate, secondDate) + .getMonths(); + assertEquals(6, monthsBetween); + } + + @Test + void givenTwoDates_whenCalculatingMonthsBetweenUsingPeriodClass_thenReturnMonthsDifference() { + Period diff = Period.between(LocalDate.parse("2023-05-25"), LocalDate.parse("2023-11-23")); + assertEquals(5, diff.getMonths()); + } + + @Test + void givenTwoDates_whenCalculatingMonthsBetweenUsingPeriodClassAndAdjsutingDatesToFirstDayOfTheMonth_thenReturnMonthsDifference() { + Period diff = Period.between(LocalDate.parse("2023-05-25") + .withDayOfMonth(1), LocalDate.parse("2023-11-23") + .withDayOfMonth(1)); + assertEquals(6, diff.getMonths()); + } + + @Test + void givenTwoDates_whenCalculatingMonthsBetweenUsingChronoUnitAndYearMonth_thenReturnMonthsDifference() { + long diff = ChronoUnit.MONTHS.between(YearMonth.from(LocalDate.parse("2023-05-25")), LocalDate.parse("2023-11-23")); + assertEquals(6, diff); + } + + @Test + void givenTwoDates_whenCalculatingMonthsBetweenUsingChronoUnitEnum_thenReturnMonthsDifference() { + long monthsBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2023-05-25"), LocalDate.parse("2023-11-23")); + assertEquals(5, monthsBetween); + } + + @Test + void givenTwoDates_whenCalculatingMonthsBetweenUsingChronoUnitEnumdSetTimeToFirstDayOfMonth_thenReturnMonthsDifference() { + long monthsBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2023-05-25") + .withDayOfMonth(1), LocalDate.parse("2023-11-23") + .withDayOfMonth(1)); + assertEquals(6, monthsBetween); + } + + @Test + void givenTwoDates_whenCalculatingMonthsBetweenUsingLegacyDateApi_thenReturnMonthsDifference() throws ParseException { + MonthInterval monthDifference = new MonthInterval(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date startDate = sdf.parse("2016-05-31"); + Date endDate = sdf.parse("2016-11-30"); + int monthsBetween = monthDifference.monthsBetween(startDate, endDate); + assertEquals(6, monthsBetween); + + } + + @Test + void givenTwoDates_whenCalculatingMonthsBetweenUsingLegacyDateApiDayValueConsidered_thenReturnMonthsDifference() throws ParseException { + MonthInterval monthDifference = new MonthInterval(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + Date startDate = sdf.parse("2016-05-31"); + Date endDate = sdf.parse("2016-11-28"); + int monthsBetween = monthDifference.monthsBetweenWithDayValue(startDate, endDate); + assertEquals(5, monthsBetween); + } +} diff --git a/core-java-modules/core-java-9/pom.xml b/core-java-modules/core-java-9/pom.xml index 616dceb2bf..dbb6b0a539 100644 --- a/core-java-modules/core-java-9/pom.xml +++ b/core-java-modules/core-java-9/pom.xml @@ -59,7 +59,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${maven.compiler.source} ${maven.compiler.target} diff --git a/core-java-modules/core-java-arrays-convert/README.md b/core-java-modules/core-java-arrays-convert/README.md index 2e34829525..118d8e00ed 100644 --- a/core-java-modules/core-java-arrays-convert/README.md +++ b/core-java-modules/core-java-arrays-convert/README.md @@ -11,3 +11,4 @@ This module contains articles about arrays conversion in Java - [Converting an int[] to HashSet in Java](https://www.baeldung.com/java-converting-int-array-to-hashset) - [Convert an ArrayList of String to a String Array in Java](https://www.baeldung.com/java-convert-string-arraylist-array) - [Convert Char Array to Int Array in Java](https://www.baeldung.com/java-convert-char-int-array) +- [How to Convert Byte Array to Char Array](https://www.baeldung.com/java-convert-byte-array-char) diff --git a/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/iteratorvsforloop/IteratorForLoopUnitTest.java b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/iteratorvsforloop/IteratorForLoopUnitTest.java new file mode 100644 index 0000000000..a7655c68eb --- /dev/null +++ b/core-java-modules/core-java-collections-5/src/test/java/com/baeldung/iteratorvsforloop/IteratorForLoopUnitTest.java @@ -0,0 +1,129 @@ +package com.baeldung.iteratorvsforloop; + +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.ConcurrentModificationException; +import java.util.List; +import java.util.Iterator; +import java.util.Collections; +import java.util.ListIterator; + +public class IteratorForLoopUnitTest { + + @Test + public void givenEmptyCollection_whenUsingForLoop_thenNoElementsAreIterated() { + List names = Collections.emptyList(); + StringBuilder stringBuilder = new StringBuilder(); + + for (int i = 0; i < names.size(); i++) { + stringBuilder.append(names.get(i)); + } + + assertEquals("", stringBuilder.toString()); + } + + @Test + public void givenEmptyCollection_whenUsingIterator_thenNoElementsAreIterated() { + List names = Collections.emptyList(); + StringBuilder stringBuilder = new StringBuilder(); + + Iterator iterator = names.iterator(); + while (iterator.hasNext()) { + stringBuilder.append(iterator.next()); + } + + assertEquals("", stringBuilder.toString()); + } + + + @Test + public void givenCollectionWithElements_whenUsingForLoop_thenAllElementsAreIterated() { + List names = Arrays.asList("Alice", "Bob", "Charlie"); + StringBuilder stringBuilder = new StringBuilder(); + + for (int i = 0; i < names.size(); i++) { + stringBuilder.append(names.get(i)); + } + + assertEquals("AliceBobCharlie", stringBuilder.toString()); + } + + @Test + public void givenCollectionWithElements_whenUsingIterator_thenAllElementsAreIterated() { + List names = Arrays.asList("Alice", "Bob", "Charlie"); + StringBuilder stringBuilder = new StringBuilder(); + + Iterator iterator = names.iterator(); + while (iterator.hasNext()) { + stringBuilder.append(iterator.next()); + } + + assertEquals("AliceBobCharlie", stringBuilder.toString()); + } + + @Test + public void givenCollectionWithElements_whenUsingForLoop_thenAllElementsAreIteratedReverseOrder() { + List names = Arrays.asList("Alice", "Bob", "Charlie"); + StringBuilder stringBuilder = new StringBuilder(); + + for (int i = names.size() - 1; i >= 0; i--) { + stringBuilder.append(names.get(i)); + } + + assertEquals("CharlieBobAlice", stringBuilder.toString()); + } + + @Test + public void givenCollectionWithElements_whenUsingListIterator_thenAllElementsAreIteratedInReverseOrder() { + List names = Arrays.asList("Alice", "Bob", "Charlie"); + StringBuilder stringBuilder = new StringBuilder(); + + ListIterator listIterator = names.listIterator(names.size()); + while (listIterator.hasPrevious()) { + stringBuilder.append(listIterator.previous()); + } + + assertEquals("CharlieBobAlice", stringBuilder.toString()); + } + + @Test + public void givenCollectionWithElements_whenRemovingElementDuringForLoopIteration_thenConcurrentModificationExceptionIsThrown() { + List names = new ArrayList<>(List.of("Alice", "Bob", "Charlie")); + + assertThrows(ConcurrentModificationException.class, () -> { + for (String name : names) { + names.remove("Bob"); + } + }); + } + + @Test + public void givenCollectionWithElements_whenRemovingElementUsingIterator_thenElementIsRemovedSafely() { + List names = new ArrayList<>(Arrays.asList("Alice", "Bob", "Charlie")); + Iterator iterator = names.iterator(); + + while (iterator.hasNext()) { + String name = iterator.next(); + if (name.equals("Bob")) { + iterator.remove(); + } + } + List expected = Arrays.asList("Alice", "Charlie"); + assertIterableEquals(expected, names); + } + + @Test + public void givenCollectionWithElements_whenModifyingElementToLowerCaseDuringForLoopIteration_thenElementsAreModifiedToLowerCase() { + List names = new ArrayList<>(List.of("Alice", "Bob", "Charlie")); + + for (int i = 0; i < names.size(); i++) { + names.set(i, names.get(i).toLowerCase()); + } + + List expected = Arrays.asList("alice","bob", "charlie"); + assertIterableEquals(expected, names); + } +} 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 46ef4ff4c9..18a153ff06 100644 --- a/core-java-modules/core-java-collections-list-6/pom.xml +++ b/core-java-modules/core-java-collections-list-6/pom.xml @@ -13,4 +13,20 @@ 0.0.1-SNAPSHOT + + + com.google.guava + guava + ${guava.version} + + + io.vavr + vavr + ${vavr.version} + + + + + 0.10.4 + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-6/src/main/java/com/baeldung/sorting/SortingBasedOnAnotherList.java b/core-java-modules/core-java-collections-list-6/src/main/java/com/baeldung/sorting/SortingBasedOnAnotherList.java new file mode 100644 index 0000000000..b53b3a946a --- /dev/null +++ b/core-java-modules/core-java-collections-list-6/src/main/java/com/baeldung/sorting/SortingBasedOnAnotherList.java @@ -0,0 +1,52 @@ +package com.baeldung.sorting; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.google.common.collect.Ordering; + +public class SortingBasedOnAnotherList { + static List sortUsingForLoop(List listToSort, List listWithOrder) { + List sortedList = new ArrayList<>(); + for(String element: listWithOrder) { + if(listToSort.contains(element)) { + sortedList.add(element); + } + } + return sortedList; + } + + static void sortUsingComparator(List listToSort, List listWithOrder) { + listToSort.sort(Comparator.comparingInt(listWithOrder::indexOf)); + } + + static void sortUsingStreamAPI(List listToSort, List listWithOrder) { + Map indicesMap = listWithOrder.stream().collect(Collectors.toMap(e->e, listWithOrder::indexOf)); + listToSort.sort(Comparator.comparingInt(indicesMap::get)); + } + + static void sortUsingMap(List listToSort, List listWithOrder) { + Map orderedIndicesMap = new HashMap<>(); + for(int i = 0; i < listWithOrder.size(); i++) { + orderedIndicesMap.put(listWithOrder.get(i), i); + } + listToSort.sort(Comparator.comparingInt(orderedIndicesMap::get)); + } + + static List sortUsingGuava(List listToSort, List listWithOrder) { + Ordering explicitOrdering = Ordering.explicit(listWithOrder); + List sortedList = explicitOrdering.sortedCopy(listToSort); + return sortedList; + } + + static List sortUsingVavr(List listToSort, List listWithOrder) { + io.vavr.collection.List listWithOrderedElements = io.vavr.collection.List.ofAll(listWithOrder); + io.vavr.collection.List listToSortElements = io.vavr.collection.List.ofAll(listToSort); + io.vavr.collection.List sortedList = listToSortElements.sortBy(listWithOrderedElements::indexOf); + return sortedList.asJava(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-list-6/src/test/java/com/baeldung/sorting/SortingBasedOnAnotherListUnitTest.java b/core-java-modules/core-java-collections-list-6/src/test/java/com/baeldung/sorting/SortingBasedOnAnotherListUnitTest.java new file mode 100644 index 0000000000..2ed7d52eee --- /dev/null +++ b/core-java-modules/core-java-collections-list-6/src/test/java/com/baeldung/sorting/SortingBasedOnAnotherListUnitTest.java @@ -0,0 +1,70 @@ +package com.baeldung.sorting; + +import static com.baeldung.sorting.SortingBasedOnAnotherList.sortUsingComparator; +import static com.baeldung.sorting.SortingBasedOnAnotherList.sortUsingForLoop; +import static com.baeldung.sorting.SortingBasedOnAnotherList.sortUsingGuava; +import static com.baeldung.sorting.SortingBasedOnAnotherList.sortUsingMap; +import static com.baeldung.sorting.SortingBasedOnAnotherList.sortUsingStreamAPI; +import static com.baeldung.sorting.SortingBasedOnAnotherList.sortUsingVavr; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; + +public class SortingBasedOnAnotherListUnitTest { + @Test + public void givenTwoList_whenUsingForLoop_thenSort() { + List listWithOrder = Arrays.asList("Burger", "Coke", "Fries", "Pizza"); + List listToSort = Arrays.asList("Pizza", "Burger", "Fries", "Coke"); + sortUsingForLoop(listToSort, listWithOrder); + List expectedSortedList = Arrays.asList("Burger", "Coke", "Fries", "Pizza"); + assertEquals(expectedSortedList, listWithOrder); + } + + @Test + public void givenTwoList_whenUsingComparator_thenSort() { + List listWithOrder = Arrays.asList("Burger", "Coke", "Fries", "Pizza"); + List listToSort = Arrays.asList("Pizza", "Burger", "Fries", "Coke"); + sortUsingComparator(listToSort, listWithOrder); + List expectedSortedList = Arrays.asList("Burger", "Coke", "Fries", "Pizza"); + assertEquals(expectedSortedList, listToSort); + } + + @Test + public void givenTwoList_whenUsingStreamAPI_thenSort() { + List listWithOrder = Arrays.asList("Burger", "Coke", "Fries", "Pizza"); + List listToSort = Arrays.asList("Pizza", "Burger", "Fries", "Coke"); + sortUsingStreamAPI(listToSort, listWithOrder); + List expectedSortedList = Arrays.asList("Burger", "Coke", "Fries", "Pizza"); + assertEquals(expectedSortedList, listToSort); + } + + @Test + public void givenTwoList_whenUsingMap_thenSort() { + List listWithOrder = Arrays.asList("Burger", "Coke", "Fries", "Pizza"); + List listToSort = Arrays.asList("Pizza", "Burger", "Fries", "Coke"); + sortUsingMap(listToSort, listWithOrder); + List expectedSortedList = Arrays.asList("Burger", "Coke", "Fries", "Pizza"); + assertEquals(expectedSortedList, listToSort); + } + + @Test + public void givenTwoList_whenUsingGuavaExplicit_thenSort() { + List listWithOrder = Arrays.asList("Burger", "Coke", "Fries", "Pizza"); + List listToSort = Arrays.asList("Pizza", "Burger", "Fries", "Coke"); + sortUsingGuava(listToSort, listWithOrder); + List expectedSortedList = Arrays.asList("Burger", "Coke", "Fries", "Pizza"); + assertEquals(expectedSortedList, listWithOrder); + } + + @Test + public void givenTwoList_whenUsingVavr_thenSort() { + List listWithOrder = Arrays.asList("Burger", "Coke", "Fries", "Pizza"); + List listToSort = Arrays.asList("Pizza", "Burger", "Fries", "Coke"); + sortUsingVavr(listToSort, listWithOrder); + List expectedSortedList = Arrays.asList("Burger", "Coke", "Fries", "Pizza"); + assertEquals(expectedSortedList, listWithOrder); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-3/README.md b/core-java-modules/core-java-collections-maps-3/README.md index 0d07bde8c1..d7b0153a69 100644 --- a/core-java-modules/core-java-collections-maps-3/README.md +++ b/core-java-modules/core-java-collections-maps-3/README.md @@ -10,4 +10,5 @@ This module contains articles about Map data structures in Java. - [Java HashMap Load Factor](https://www.baeldung.com/java-hashmap-load-factor) - [Converting Java Properties to HashMap](https://www.baeldung.com/java-convert-properties-to-hashmap) - [Get Values and Keys as ArrayList From a HashMap](https://www.baeldung.com/java-values-keys-arraylists-hashmap) -- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2) +- [Remove Duplicate Values From HashMap in Java](https://www.baeldung.com/java-hashmap-delete-duplicates) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2)[[next -->]](/core-java-modules/core-java-collections-maps-4) diff --git a/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/removeduplicate/RemoveDuplicateValuesUnitTest.java b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/removeduplicate/RemoveDuplicateValuesUnitTest.java similarity index 98% rename from core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/removeduplicate/RemoveDuplicateValuesUnitTest.java rename to core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/removeduplicate/RemoveDuplicateValuesUnitTest.java index 080bc46289..e1fca2b93a 100644 --- a/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/removeduplicate/RemoveDuplicateValuesUnitTest.java +++ b/core-java-modules/core-java-collections-maps-3/src/test/java/com/baeldung/map/removeduplicate/RemoveDuplicateValuesUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.map.removeuplicate; +package com.baeldung.map.removeduplicate; import static java.util.stream.Collectors.toMap; import static org.assertj.core.api.Assertions.assertThat; diff --git a/core-java-modules/core-java-collections-maps-4/README.md b/core-java-modules/core-java-collections-maps-4/README.md index 9dd9cbe0d9..cc7c9b77e0 100644 --- a/core-java-modules/core-java-collections-maps-4/README.md +++ b/core-java-modules/core-java-collections-maps-4/README.md @@ -9,3 +9,4 @@ This module contains articles about Map data structures in Java. - [Difference Between Map and HashMap in Java](https://www.baeldung.com/java-map-vs-hashmap) - [How to Create a New Entry in a Map](https://www.baeldung.com/java-map-new-entry) - [Difference Between Map and MultivaluedMap in Java](https://www.baeldung.com/java-map-vs-multivaluedmap) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-3)[[next -->]](/core-java-modules/core-java-collections-maps-5) diff --git a/core-java-modules/core-java-collections-maps-5/README.md b/core-java-modules/core-java-collections-maps-5/README.md index e1817c7ba4..b952bbeb2d 100644 --- a/core-java-modules/core-java-collections-maps-5/README.md +++ b/core-java-modules/core-java-collections-maps-5/README.md @@ -10,4 +10,5 @@ - [How to Invert a Map in Java](https://www.baeldung.com/java-invert-map) - [Implementing a Map with Multiple Keys in Java](https://www.baeldung.com/java-multiple-keys-map) - [Difference Between Map.ofEntries() and Map.of()](https://www.baeldung.com/map-ofentries-and-map-of) -- More articles: [[<-- prev]](../core-java-collections-maps-4) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-4)[[next -->]](/core-java-modules/core-java-collections-maps-6) + diff --git a/core-java-modules/core-java-collections-maps-6/README.md b/core-java-modules/core-java-collections-maps-6/README.md index f116d0315e..4e03cdee36 100644 --- a/core-java-modules/core-java-collections-maps-6/README.md +++ b/core-java-modules/core-java-collections-maps-6/README.md @@ -7,6 +7,7 @@ - [Converting JsonNode Object to Map](https://www.baeldung.com/jackson-jsonnode-map) - [How to Modify a Key in a HashMap?](https://www.baeldung.com/java-hashmap-modify-key) - [Converting String or String Array to Map in Java](https://www.baeldung.com/java-convert-string-to-map) -- [Remove Duplicate Values From HashMap in Java](https://www.baeldung.com/java-hashmap-delete-duplicates) - [Sorting Java Map in Descending Order](https://www.baeldung.com/java-sort-map-descending) - [Convert HashMap.toString() to HashMap in Java](https://www.baeldung.com/hashmap-from-tostring) +- More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-5)[[next -->]](/core-java-modules/core-java-collections-maps-7) + diff --git a/core-java-modules/core-java-concurrency-2/README.md b/core-java-modules/core-java-concurrency-2/README.md index 3badd36d5e..5d05c900b8 100644 --- a/core-java-modules/core-java-concurrency-2/README.md +++ b/core-java-modules/core-java-concurrency-2/README.md @@ -7,3 +7,4 @@ - [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded) - [How to Check if All Runnables Are Done](https://www.baeldung.com/java-runnables-check-status) - [Parallelize for Loop in Java](https://www.baeldung.com/java-for-loop-parallel) +- [How to Effectively Unit Test CompletableFuture](https://www.baeldung.com/java-completablefuture-unit-test) diff --git a/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/callback/completablefuture/CompletableFutureCallbackExample.java b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/callback/completablefuture/CompletableFutureCallbackExample.java new file mode 100644 index 0000000000..1c642d4ef7 --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/callback/completablefuture/CompletableFutureCallbackExample.java @@ -0,0 +1,30 @@ +package com.baeldung.callback.completablefuture; + +import java.util.concurrent.CompletableFuture; + +public class CompletableFutureCallbackExample { + public static void main(String[] args) { + CompletableFuture completableFuture = new CompletableFuture<>(); + Runnable runnable = downloadFile(completableFuture); + completableFuture.whenComplete((res, error) -> { + if (error != null) { + // handle the exception scenario + } else if (res != null) { + // send data to DB + } + }); + new Thread(runnable).start(); + } + + private static Runnable downloadFile(CompletableFuture completableFuture) { + return () -> { + try { + //logic to download file + Thread.sleep(5000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + completableFuture.complete("pic.jpg"); + }; + } +} diff --git a/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/callback/listenablefuture/ListenableFutureCallbackExample.java b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/callback/listenablefuture/ListenableFutureCallbackExample.java new file mode 100644 index 0000000000..f3a5e889af --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-5/src/main/java/com/baeldung/callback/listenablefuture/ListenableFutureCallbackExample.java @@ -0,0 +1,42 @@ +package com.baeldung.callback.listenablefuture; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; + + +public class ListenableFutureCallbackExample { + public static void main(String[] args) { + + ExecutorService executorService = Executors.newFixedThreadPool(1); + ListeningExecutorService pool = MoreExecutors.listeningDecorator(executorService); + ListenableFuture listenableFuture = pool.submit(downloadFile()); + + Futures.addCallback(listenableFuture, new FutureCallback() { + @Override + public void onSuccess(String result) { + // code to push fileName to DB + } + + @Override + public void onFailure(Throwable throwable) { + // code to take appropriate action when there is an error + } + }, executorService); + } + + private static Callable downloadFile() { + return () -> { + // Mimicking the downloading of a file by adding a sleep call + Thread.sleep(5000); + return "pic.jpg"; + }; + } + +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/executorservice/ExecuteExample.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/executorservice/ExecuteExample.java new file mode 100644 index 0000000000..6b6d6e3e8a --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/executorservice/ExecuteExample.java @@ -0,0 +1,24 @@ +package com.baeldung.concurrent.executorservice; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +public class ExecuteExample { + public static void main(String[] args) { + ExecutorService executorService = Executors.newFixedThreadPool(2); + // Task using Runnable + Runnable task = () -> { + int[] numbers = { 1, 2, 3, 4, 5 }; + int sum = 0; + for (int num : numbers) { + sum += num; + } + System.out.println("Sum calculated using execute:" + sum); + }; + // Submit the task using execute + executorService.execute(task); + executorService.shutdown(); + + } + +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/executorservice/SubmitExample.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/executorservice/SubmitExample.java new file mode 100644 index 0000000000..cd715edcc0 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/executorservice/SubmitExample.java @@ -0,0 +1,31 @@ +package com.baeldung.concurrent.executorservice; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +public class SubmitExample { + public static void main(String[] args) { + ExecutorService executorService = Executors.newFixedThreadPool(2); + Callable task = () -> { + int[] numbers = { 1, 2, 3, 4, 5 }; + int sum = 0; + for (int num : numbers) { + sum += num; + } + return sum; + }; + // Submit the task and obtain a Future + Future result = executorService.submit(task); + try { + // Get the result + int sum = result.get(); + System.out.println("Sum calculated using submit:" + sum); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + executorService.shutdown(); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-function/src/main/java/com/baeldung/lazylambda/LambdaSupplier.java b/core-java-modules/core-java-function/src/main/java/com/baeldung/lazylambda/LambdaSupplier.java new file mode 100644 index 0000000000..36cd1b31ae --- /dev/null +++ b/core-java-modules/core-java-function/src/main/java/com/baeldung/lazylambda/LambdaSupplier.java @@ -0,0 +1,16 @@ +package com.baeldung.lazylambda; + +import java.util.function.Supplier; + +public class LambdaSupplier { + + protected final Supplier expensiveData; + + public LambdaSupplier(Supplier expensiveData) { + this.expensiveData = expensiveData; + } + + public T getData() { + return expensiveData.get(); + } +} diff --git a/core-java-modules/core-java-function/src/main/java/com/baeldung/lazylambda/LazyLambdaSupplier.java b/core-java-modules/core-java-function/src/main/java/com/baeldung/lazylambda/LazyLambdaSupplier.java new file mode 100644 index 0000000000..dce3cc4997 --- /dev/null +++ b/core-java-modules/core-java-function/src/main/java/com/baeldung/lazylambda/LazyLambdaSupplier.java @@ -0,0 +1,21 @@ +package com.baeldung.lazylambda; + +import java.util.function.Supplier; + +public class LazyLambdaSupplier extends LambdaSupplier { + + private T data; + + public LazyLambdaSupplier(Supplier expensiveData) { + super(expensiveData); + } + + @Override + public T getData() { + if (data != null) { + return data; + } + return data = expensiveData.get(); + } + +} diff --git a/core-java-modules/core-java-function/src/main/java/com/baeldung/lazylambda/LazyLambdaThreadSafeSupplier.java b/core-java-modules/core-java-function/src/main/java/com/baeldung/lazylambda/LazyLambdaThreadSafeSupplier.java new file mode 100644 index 0000000000..32eec0a5d8 --- /dev/null +++ b/core-java-modules/core-java-function/src/main/java/com/baeldung/lazylambda/LazyLambdaThreadSafeSupplier.java @@ -0,0 +1,26 @@ +package com.baeldung.lazylambda; + +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; + +public class LazyLambdaThreadSafeSupplier extends LambdaSupplier { + + private final AtomicReference data; + + public LazyLambdaThreadSafeSupplier(Supplier expensiveData) { + super(expensiveData); + data = new AtomicReference<>(); + } + + public T getData() { + if (data.get() == null) { + synchronized (data) { + if (data.get() == null) { + data.set(expensiveData.get()); + } + } + } + return data.get(); + } + +} diff --git a/core-java-modules/core-java-function/src/test/java/com/baeldung/lazylambda/LambdaSupplierUnitTest.java b/core-java-modules/core-java-function/src/test/java/com/baeldung/lazylambda/LambdaSupplierUnitTest.java new file mode 100644 index 0000000000..f0a500e084 --- /dev/null +++ b/core-java-modules/core-java-function/src/test/java/com/baeldung/lazylambda/LambdaSupplierUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.lazylambda; + +import java.util.function.Supplier; + +import org.junit.Test; +import org.mockito.Mockito; + +public class LambdaSupplierUnitTest { + + @Test + public void whenCalledMultipleTimes_thenShouldBeCalledMultipleTimes() { + @SuppressWarnings("unchecked") Supplier mockedExpensiveFunction = Mockito.mock(Supplier.class); + Mockito.when(mockedExpensiveFunction.get()) + .thenReturn("expensive call"); + LambdaSupplier testee = new LambdaSupplier<>(mockedExpensiveFunction); + Mockito.verify(mockedExpensiveFunction, Mockito.never()) + .get(); + testee.getData(); + testee.getData(); + Mockito.verify(mockedExpensiveFunction, Mockito.times(2)) + .get(); + } + +} diff --git a/core-java-modules/core-java-function/src/test/java/com/baeldung/lazylambda/LazyLambdaSupplierUnitTest.java b/core-java-modules/core-java-function/src/test/java/com/baeldung/lazylambda/LazyLambdaSupplierUnitTest.java new file mode 100644 index 0000000000..1371983a3d --- /dev/null +++ b/core-java-modules/core-java-function/src/test/java/com/baeldung/lazylambda/LazyLambdaSupplierUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.lazylambda; + +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; + +public class LazyLambdaSupplierUnitTest { + + @Test + public void whenCalledMultipleTimes_thenShouldBeCalledOnlyOnce() { + @SuppressWarnings("unchecked") Supplier mockedExpensiveFunction = Mockito.mock(Supplier.class); + Mockito.when(mockedExpensiveFunction.get()) + .thenReturn("expensive call"); + LazyLambdaSupplier testee = new LazyLambdaSupplier<>(mockedExpensiveFunction); + Mockito.verify(mockedExpensiveFunction, Mockito.never()) + .get(); + testee.getData(); + testee.getData(); + Mockito.verify(mockedExpensiveFunction, Mockito.times(1)) + .get(); + } + + @Test + public void whenCalledMultipleTimesConcurrently_thenShouldBeCalledMultipleTimes() throws InterruptedException { + @SuppressWarnings("unchecked") Supplier mockedExpensiveFunction = Mockito.mock(Supplier.class); + Mockito.when(mockedExpensiveFunction.get()) + .thenAnswer((Answer) invocation -> { + Thread.sleep(1000L); + return "Late response!"; + }); + LazyLambdaSupplier testee = new LazyLambdaSupplier<>(mockedExpensiveFunction); + Mockito.verify(mockedExpensiveFunction, Mockito.never()) + .get(); + + ExecutorService executorService = Executors.newFixedThreadPool(4); + executorService.invokeAll(List.of(testee::getData, testee::getData)); + executorService.shutdown(); + if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + } + + Mockito.verify(mockedExpensiveFunction, Mockito.times(2)) + .get(); + } +} diff --git a/core-java-modules/core-java-function/src/test/java/com/baeldung/lazylambda/LazyLambdaThreadSafeSupplierUnitTest.java b/core-java-modules/core-java-function/src/test/java/com/baeldung/lazylambda/LazyLambdaThreadSafeSupplierUnitTest.java new file mode 100644 index 0000000000..83bd49aa7e --- /dev/null +++ b/core-java-modules/core-java-function/src/test/java/com/baeldung/lazylambda/LazyLambdaThreadSafeSupplierUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.lazylambda; + +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; + +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; + +public class LazyLambdaThreadSafeSupplierUnitTest { + + @Test + public void whenCalledMultipleTimes_thenShouldBeCalledOnlyOnce() { + @SuppressWarnings("unchecked") Supplier mockedExpensiveFunction = Mockito.mock(Supplier.class); + Mockito.when(mockedExpensiveFunction.get()) + .thenReturn("expensive call"); + LazyLambdaThreadSafeSupplier testee = new LazyLambdaThreadSafeSupplier<>(mockedExpensiveFunction); + Mockito.verify(mockedExpensiveFunction, Mockito.never()) + .get(); + testee.getData(); + testee.getData(); + Mockito.verify(mockedExpensiveFunction, Mockito.times(1)) + .get(); + } + + @Test + public void whenCalledMultipleTimesConcurrently_thenShouldBeCalledOnlyOnce() throws InterruptedException { + @SuppressWarnings("unchecked") Supplier mockedExpensiveFunction = Mockito.mock(Supplier.class); + Mockito.when(mockedExpensiveFunction.get()) + .thenAnswer((Answer) invocation -> { + Thread.sleep(1000L); + return "Late response!"; + }); + LazyLambdaThreadSafeSupplier testee = new LazyLambdaThreadSafeSupplier<>(mockedExpensiveFunction); + Mockito.verify(mockedExpensiveFunction, Mockito.never()) + .get(); + + ExecutorService executorService = Executors.newFixedThreadPool(4); + executorService.invokeAll(List.of(testee::getData, testee::getData)); + executorService.shutdown(); + if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) { + executorService.shutdownNow(); + } + + Mockito.verify(mockedExpensiveFunction, Mockito.times(1)) + .get(); + } + +} diff --git a/core-java-modules/core-java-io-5/src/main/java/com/baeldung/splitlargefile/SplitLargeFile.java b/core-java-modules/core-java-io-5/src/main/java/com/baeldung/splitlargefile/SplitLargeFile.java new file mode 100644 index 0000000000..59b7a86602 --- /dev/null +++ b/core-java-modules/core-java-io-5/src/main/java/com/baeldung/splitlargefile/SplitLargeFile.java @@ -0,0 +1,59 @@ +package com.baeldung.splitlargefile; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.io.FilenameUtils; + +class SplitLargeFile { + + public List splitByFileSize(File largeFile, int maxSizeOfSplitFiles, + String splitedFileDirPath) throws IOException { + List listOfSplitFiles = new ArrayList<>(); + try (InputStream in = Files.newInputStream(largeFile.toPath())) { + final byte[] buffer = new byte[maxSizeOfSplitFiles]; + int dataRead = in.read(buffer); + while (dataRead > -1) { + File splitFile = getSplitFile(FilenameUtils.removeExtension(largeFile.getName()), + buffer, dataRead, splitedFileDirPath); + listOfSplitFiles.add(splitFile); + dataRead = in.read(buffer); + } + } + return listOfSplitFiles; + } + + private File getSplitFile(String largeFileName, byte[] buffer, int length, + String splitedFileDirPath) throws IOException { + File splitFile = File.createTempFile(largeFileName + "-", "-split", + new File(splitedFileDirPath)); + try (FileOutputStream fos = new FileOutputStream(splitFile)) { + fos.write(buffer, 0, length); + } + return splitFile; + } + + public List splitByNumberOfFiles(File largeFile, int noOfFiles, String splitedFileDirPath) + throws IOException { + return splitByFileSize(largeFile, getSizeInBytes(largeFile.length(), noOfFiles), + splitedFileDirPath); + } + + private int getSizeInBytes(long largefileSizeInBytes, int numberOfFilesforSplit) { + if (largefileSizeInBytes % numberOfFilesforSplit != 0) { + largefileSizeInBytes = ((largefileSizeInBytes / numberOfFilesforSplit) + 1) + * numberOfFilesforSplit; + } + long x = largefileSizeInBytes / numberOfFilesforSplit; + if (x > Integer.MAX_VALUE) { + throw new NumberFormatException("size too large"); + + } + return (int) x; + } +} diff --git a/core-java-modules/core-java-io-5/src/test/java/com/baeldung/outputstreamtobytearray/OutputStreamToByteArrayUnitTest.java b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/outputstreamtobytearray/OutputStreamToByteArrayUnitTest.java new file mode 100644 index 0000000000..ed0cab250a --- /dev/null +++ b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/outputstreamtobytearray/OutputStreamToByteArrayUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.outputstreamtobytearray; + +import org.apache.commons.io.FileUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class OutputStreamToByteArrayUnitTest { + + @Test + public void givenFileOutputStream_whenUsingFileUtilsToReadTheFile_thenReturnByteArray(@TempDir Path tempDir) throws IOException { + String data = "Welcome to Baeldung!"; + String fileName = "file.txt"; + Path filePath = tempDir.resolve(fileName); + + try (FileOutputStream outputStream = new FileOutputStream(filePath.toFile())) { + outputStream.write(data.getBytes(StandardCharsets.UTF_8)); + } + + byte[] writtenData = FileUtils.readFileToByteArray(filePath.toFile()); + String result = new String(writtenData, StandardCharsets.UTF_8); + assertEquals(data, result); + } + + + @Test + public void givenSystemOut_whenUsingDrainableOutputStream_thenReturnByteArray() throws IOException { + String data = "Welcome to Baeldung!\n"; + + DrainableOutputStream drainableOutputStream = new DrainableOutputStream(System.out); + try (drainableOutputStream) { + drainableOutputStream.write(data.getBytes(StandardCharsets.UTF_8)); + } + + byte[] writtenData = drainableOutputStream.toByteArray(); + assertEquals(data, new String(writtenData, StandardCharsets.UTF_8)); + } + + public class DrainableOutputStream extends FilterOutputStream { + private final ByteArrayOutputStream buffer; + + public DrainableOutputStream(OutputStream out) { + super(out); + this.buffer = new ByteArrayOutputStream(); + } + + @Override + public void write(byte b[]) throws IOException { + buffer.write(b); + super.write(b); + } + + public byte[] toByteArray() { + return buffer.toByteArray(); + } + } +} diff --git a/core-java-modules/core-java-io-5/src/test/java/com/baeldung/splitlargefile/SplitLargeFileUnitTest.java b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/splitlargefile/SplitLargeFileUnitTest.java new file mode 100644 index 0000000000..d31cbd67ad --- /dev/null +++ b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/splitlargefile/SplitLargeFileUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.splitlargefile; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.junit.BeforeClass; + +public class SplitLargeFileUnitTest { + + @BeforeClass + public static void prepareData() throws IOException { + Files.createDirectories(Paths.get("target/split")); + } + + private String splitedFileDirPath() throws Exception { + return Paths.get("target").toString() + "/split"; + } + + private Path largeFilePath() throws Exception { + return Paths.get(this.getClass().getClassLoader().getResource("large-file.txt").toURI()); + } + + + @org.junit.Test + public void givenLargeFile_whenSplitLargeFile_thenSplitBySize() throws Exception { + File input = largeFilePath().toFile(); + SplitLargeFile slf = new SplitLargeFile(); + slf.splitByFileSize(input, 1024_000, splitedFileDirPath()); + } + + @org.junit.Test + public void givenLargeFile_whenSplitLargeFile_thenSplitByNumberOfFiles() throws Exception { + File input = largeFilePath().toFile(); + SplitLargeFile slf = new SplitLargeFile(); + slf.splitByNumberOfFiles(input, 3, splitedFileDirPath()); + } + +} diff --git a/core-java-modules/core-java-ipc/README.md b/core-java-modules/core-java-ipc/README.md new file mode 100644 index 0000000000..bbfbf6d070 --- /dev/null +++ b/core-java-modules/core-java-ipc/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Inter-Process Communication Methods in Java](https://www.baeldung.com/java-ipc) diff --git a/core-java-modules/core-java-lang-6/README.md b/core-java-modules/core-java-lang-6/README.md index fe79a8ecd4..214409dd04 100644 --- a/core-java-modules/core-java-lang-6/README.md +++ b/core-java-modules/core-java-lang-6/README.md @@ -10,3 +10,4 @@ This module contains articles about core features in the Java language - [Stop Executing Further Code in Java](https://www.baeldung.com/java-stop-running-code) - [Using the Apache Commons Lang 3 for Comparing Objects in Java](https://www.baeldung.com/java-apache-commons-lang-3-compare-objects) - [Return First Non-null Value in Java](https://www.baeldung.com/java-first-non-null) +- [Static Final Variables in Java](https://www.baeldung.com/java-static-final-variables) diff --git a/core-java-modules/core-java-lang-6/pom.xml b/core-java-modules/core-java-lang-6/pom.xml index 54035c1eb0..a47ed459f6 100644 --- a/core-java-modules/core-java-lang-6/pom.xml +++ b/core-java-modules/core-java-lang-6/pom.xml @@ -23,6 +23,16 @@ commons-lang3 ${commons-lang3.version} + + org.openjdk.jmh + jmh-core + ${jmh.version} + + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + @@ -39,6 +49,11 @@ mapstruct-processor ${mapstruct.version} + + org.openjdk.jmh + jmh-generator-annprocess + ${jmh.version} + @@ -50,6 +65,7 @@ 17 UTF-8 1.6.0.Beta1 + 1.37 \ No newline at end of file diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java index 88e2283985..5a7ea2da58 100644 --- a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/compressbytes/CompressByteArrayUtil.java @@ -23,6 +23,23 @@ public class CompressByteArrayUtil { return outputStream.toByteArray(); } + public static byte[] compressWithCustomLevel(byte[] input, int level) { + Deflater deflater = new Deflater(); + deflater.setInput(input); + deflater.setLevel(level); + deflater.finish(); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + + while (!deflater.finished()) { + int compressedSize = deflater.deflate(buffer); + outputStream.write(buffer, 0, compressedSize); + } + + return outputStream.toByteArray(); + } + public static byte[] decompress(byte[] input) throws DataFormatException { Inflater inflater = new Inflater(); inflater.setInput(input); diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/staticfinal/Bike.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/staticfinal/Bike.java new file mode 100644 index 0000000000..bde7b44897 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/staticfinal/Bike.java @@ -0,0 +1,14 @@ +package com.baeldung.staticfinal; + +import java.util.HashMap; + +public class Bike { + public static final int TIRE = 2; + public static final int PEDAL; + public static final HashMap PART = new HashMap<>(); + + static { + PEDAL = 5; + } + +} diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/compressbytes/CompressByteArrayUnitTest.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/compressbytes/CompressByteArrayUnitTest.java new file mode 100644 index 0000000000..822ad5063c --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/compressbytes/CompressByteArrayUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.compressbytes; + +import org.junit.jupiter.api.Test; + +import java.util.zip.DataFormatException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CompressByteArrayUnitTest { + + private static final String INPUT_STRING = "Building a REST API is not a trivial task – from the high-level RESTful " + + "constraints down to the nitty-gritty of making everything work and work well." + + "Spring has made REST a first-class citizen and the platform has been maturing in leaps and bounds." + + "With this guide, my aim is to organize the mountains of information that are available on the subject and " + + "guide you through properly building an API." + + "The guide starts with the basics – bootstrapping the REST API, the Spring MVC Configuration, and basic customization."; + + @Test + void givenInputString_whenCompressWithDefaultLevel_thenDecompressWithSameSize() throws DataFormatException { + byte[] input = INPUT_STRING.getBytes(); + byte[] compressedData = CompressByteArrayUtil.compress(input); + byte[] decompressedData = CompressByteArrayUtil.decompress(compressedData); + System.out.println("Original: " + input.length + " bytes"); + System.out.println("Compressed: " + compressedData.length + " bytes"); + System.out.println("Decompressed: " + decompressedData.length + " bytes"); + assertEquals(input.length, decompressedData.length); + } + + @Test + void givenInputString_whenCompressWithCustomLevel_thenDecompressWithSameSize() throws DataFormatException { + byte[] input = INPUT_STRING.getBytes(); + byte[] compressedData = CompressByteArrayUtil.compressWithCustomLevel(input, 1); + byte[] decompressedData = CompressByteArrayUtil.decompress(compressedData); + System.out.println("Original: " + input.length + " bytes"); + System.out.println("Compressed: " + compressedData.length + " bytes"); + System.out.println("Decompressed: " + decompressedData.length + " bytes"); + assertEquals(input.length, decompressedData.length); + } +} diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/recursivelysumintarray/RecursivelySumIntArrayUnitTest.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/recursivelysumintarray/RecursivelySumIntArrayUnitTest.java new file mode 100644 index 0000000000..fc61a806e1 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/recursivelysumintarray/RecursivelySumIntArrayUnitTest.java @@ -0,0 +1,38 @@ +package com.baeldung.recursivelysumintarray; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class RecursivelySumIntArrayUnitTest { + + private static final int[] INT_ARRAY = { 1, 2, 3, 4, 5 }; + + static int sumIntArray1(int[] array) { + if (array.length == 1) { + return array[0]; + } else { + return array[0] + sumIntArray1(Arrays.copyOfRange(array, 1, array.length)); + } + } + + static int sumIntArray2(int[] array, int index) { + if (index == 0) { + return array[index]; + } else { + return array[index] + sumIntArray2(array, index - 1); + } + } + + @Test + void whenUsingSumIntArray1_thenGetExpectedResult() { + assertEquals(15, sumIntArray1(INT_ARRAY)); + } + + @Test + void whenUsingSumIntArray2_thenGetExpectedResult() { + assertEquals(15, sumIntArray2(INT_ARRAY, INT_ARRAY.length - 1)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/recursivelysumintarray/SumArrayBenchmark.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/recursivelysumintarray/SumArrayBenchmark.java new file mode 100644 index 0000000000..7d6a612a8d --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/recursivelysumintarray/SumArrayBenchmark.java @@ -0,0 +1,61 @@ +package com.baeldung.recursivelysumintarray; + +import static com.baeldung.recursivelysumintarray.RecursivelySumIntArrayUnitTest.sumIntArray1; +import static com.baeldung.recursivelysumintarray.RecursivelySumIntArrayUnitTest.sumIntArray2; + +import java.util.Random; +import java.util.concurrent.TimeUnit; + +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +@BenchmarkMode(Mode.AverageTime) +@State(Scope.Thread) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 2) +@Fork(1) +@Measurement(iterations = 5) +public class SumArrayBenchmark { + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder().include(SumArrayBenchmark.class.getSimpleName()) + .build(); + new Runner(options).run(); + } + + @Param({ "10", "10000" }) + public int size; + int[] array; + + @Setup + public void setup() { + var r = new Random(); + array = new int[size]; + + for (int i = 0; i < size; i++) { + array[i] = r.nextInt(); + } + } + + @Benchmark + public int withArrayCopy() { + return sumIntArray1(array); + } + + @Benchmark + public int withoutArrayCopy() { + return sumIntArray2(array, array.length - 1); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticfinal/BikeUnitTest.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticfinal/BikeUnitTest.java new file mode 100644 index 0000000000..2201dae4d1 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticfinal/BikeUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.staticfinal; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class BikeUnitTest { + + @Test + void givenTireConstantSetUponDeclaration_whenGetTire_thenReturnTwo() { + assertEquals(2, Bike.TIRE); + } + + @Test + void givenPedalConstantSetByStaticBlock_whenGetPedal_thenReturnFive() { + assertEquals(5, Bike.PEDAL); + } + + @Test + void givenPartConstantObject_whenObjectStateChanged_thenCorrect() { + Bike.PART.put("seat", 1); + assertEquals(1, Bike.PART.get("seat")); + + Bike.PART.put("seat", 5); + assertEquals(5, Bike.PART.get("seat")); + } + + @Test + void givenMathClass_whenAccessingPiConstant_thenVerifyPiValueIsCorrect() { + assertEquals(3.141592653589793, Math.PI); + } + +} \ 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 551e5db1d5..118998991f 100644 --- a/core-java-modules/core-java-lang-math/pom.xml +++ b/core-java-modules/core-java-lang-math/pom.xml @@ -5,6 +5,14 @@ 4.0.0 core-java-lang-math core-java-lang-math + + + org.projectlombok + lombok + ${lombok.version} + compile + + jar diff --git a/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/BigDecimalPercentageCalculator.java b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/BigDecimalPercentageCalculator.java new file mode 100644 index 0000000000..91fde335e9 --- /dev/null +++ b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/BigDecimalPercentageCalculator.java @@ -0,0 +1,20 @@ +package com.baeldung.algorithms.percentage; + +import lombok.experimental.ExtensionMethod; +import java.math.BigDecimal; +import java.util.Scanner; + +@ExtensionMethod(FastBigDecimalPercentage.class) +public class BigDecimalPercentageCalculator { + public static void main(String[] args) { + + Scanner in = new Scanner(System.in); + System.out.println("Enter obtained marks:"); + BigDecimal obtained = new BigDecimal(in.nextDouble()); + System.out.println("Enter total marks:"); + BigDecimal total = new BigDecimal(in.nextDouble()); + + System.out.println("Percentage obtained :"+ obtained.toPercentageOf(total)); + } + +} diff --git a/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/BigDecimalPercentages.java b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/BigDecimalPercentages.java new file mode 100644 index 0000000000..c91cf0e9d4 --- /dev/null +++ b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/BigDecimalPercentages.java @@ -0,0 +1,18 @@ +package com.baeldung.algorithms.percentage; + + +import java.math.BigDecimal; +import java.math.RoundingMode; + +public class BigDecimalPercentages { + + private static final BigDecimal ONE_HUNDRED = new BigDecimal("100"); + + public BigDecimal toPercentageOf(BigDecimal value, BigDecimal total) { + return value.divide(total, 4, RoundingMode.HALF_UP).multiply(ONE_HUNDRED); + } + + public BigDecimal percentOf(BigDecimal percentage, BigDecimal total) { + return percentage.multiply(total).divide(ONE_HUNDRED, 2, RoundingMode.HALF_UP); + } +} diff --git a/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/FastBigDecimalPercentage.java b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/FastBigDecimalPercentage.java new file mode 100644 index 0000000000..f00a9f3e35 --- /dev/null +++ b/core-java-modules/core-java-lang-math/src/main/java/com/baeldung/algorithms/percentage/FastBigDecimalPercentage.java @@ -0,0 +1,16 @@ +package com.baeldung.algorithms.percentage; + +import java.math.BigDecimal; +import java.math.RoundingMode; + +public class FastBigDecimalPercentage { + + public static BigDecimal toPercentageOf(BigDecimal value, BigDecimal total) { + return value.divide(total, 4, RoundingMode.HALF_UP).scaleByPowerOfTen(2); + } + + public static BigDecimal percentOf(BigDecimal percentage, BigDecimal total) { + return percentage.multiply(total).scaleByPowerOfTen(-2); + } + +} diff --git a/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/percentage/BigDecimalPercentageUnitTest.java b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/percentage/BigDecimalPercentageUnitTest.java new file mode 100644 index 0000000000..dac2cb4de6 --- /dev/null +++ b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/percentage/BigDecimalPercentageUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.algorithms.percentage; + +import org.hamcrest.number.BigDecimalCloseTo; +import org.junit.Assert; +import org.junit.Test; + +import java.math.BigDecimal; + +public class BigDecimalPercentageUnitTest { + private BigDecimalPercentages pc = new BigDecimalPercentages(); + + + @Test + public void shouldConvertToPercentageOfTotal(){ + BigDecimalCloseTo expected = new BigDecimalCloseTo(new BigDecimal(5.05), new BigDecimal(0.001)); + Assert.assertTrue("Result not as expected",expected.matchesSafely( + pc.toPercentageOf(new BigDecimal(50.5),new BigDecimal(1000)))); + } + + @Test + public void shouldCalculatePercentageOfTotal(){ + BigDecimalCloseTo expected = new BigDecimalCloseTo(new BigDecimal(31.40), new BigDecimal(0.001)); + Assert.assertTrue("Result not as expected",expected.matchesSafely( + pc.percentOf(new BigDecimal(3.14),new BigDecimal(1000)))); + } + +} diff --git a/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/percentage/FastBigDecimalPercentageUnitTest.java b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/percentage/FastBigDecimalPercentageUnitTest.java new file mode 100644 index 0000000000..dd97e5881c --- /dev/null +++ b/core-java-modules/core-java-lang-math/src/test/java/com/baeldung/algorithms/percentage/FastBigDecimalPercentageUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.algorithms.percentage; + +import org.hamcrest.number.BigDecimalCloseTo; +import org.junit.Assert; +import org.junit.Test; + +import java.math.BigDecimal; + +public class FastBigDecimalPercentageUnitTest { + private FastBigDecimalPercentage pc = new FastBigDecimalPercentage(); + + + @Test + public void shouldConvertToPercentageOfTotal(){ + BigDecimalCloseTo expected = new BigDecimalCloseTo(new BigDecimal(5.05), new BigDecimal(0.001)); + Assert.assertTrue("Result not as expected",expected.matchesSafely( + pc.toPercentageOf(new BigDecimal(50.5),new BigDecimal(1000)))); + } + + @Test + public void shouldCalculatePercentageOfTotal(){ + BigDecimalCloseTo expected = new BigDecimalCloseTo(new BigDecimal(31.40), new BigDecimal(0.001)); + Assert.assertTrue("Result not as expected",expected.matchesSafely( + pc.percentOf(new BigDecimal(3.14),new BigDecimal(1000)))); + } + +} 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 fe6b5a9f36..9b01a97918 100644 --- a/core-java-modules/core-java-lang-oop-generics/pom.xml +++ b/core-java-modules/core-java-lang-oop-generics/pom.xml @@ -37,8 +37,8 @@ - 1.8 - 1.8 + 17 + 17 \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/classtype/CollectionWithAndWithoutGenerics.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/classtype/CollectionWithAndWithoutGenerics.java new file mode 100644 index 0000000000..f0435559a7 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/classtype/CollectionWithAndWithoutGenerics.java @@ -0,0 +1,33 @@ +package com.baeldung.generics.classtype; + +import java.util.ArrayList; +import java.util.List; + +public class CollectionWithAndWithoutGenerics { + + public static void main(String[] args) { + withoutGenerics(); + } + + private static void withoutGenerics() { + List container = new ArrayList(); + container.add(1); + container.add("2"); + container.add("string"); + + for (int i = 0; i < container.size(); i++) { + int val = (int) container.get(i); + } + } + + public static void withGenerics() { + List container = new ArrayList(); + container.add(1); + container.add(2); + container.add(3); + + for (int i = 0; i < container.size(); i++) { + int val = container.get(i); + } + } +} diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/classtype/ContainerTypeFromReflection.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/classtype/ContainerTypeFromReflection.java new file mode 100644 index 0000000000..bca47748d3 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/classtype/ContainerTypeFromReflection.java @@ -0,0 +1,13 @@ +package com.baeldung.generics.classtype; + +public class ContainerTypeFromReflection { + private T content; + + public ContainerTypeFromReflection(T content) { + this.content = content; + } + + public Class getClazz() { + return this.content.getClass(); + } +} diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/classtype/ContainerTypeFromTypeParameter.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/classtype/ContainerTypeFromTypeParameter.java new file mode 100644 index 0000000000..dc28ccf13a --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/classtype/ContainerTypeFromTypeParameter.java @@ -0,0 +1,13 @@ +package com.baeldung.generics.classtype; + +public class ContainerTypeFromTypeParameter { + private Class clazz; + + public ContainerTypeFromTypeParameter(Class clazz) { + this.clazz = clazz; + } + + public Class getClazz() { + return this.clazz; + } +} diff --git a/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/classtype/TypeToken.java b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/classtype/TypeToken.java new file mode 100644 index 0000000000..3a539ba652 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/main/java/com/baeldung/generics/classtype/TypeToken.java @@ -0,0 +1,17 @@ +package com.baeldung.generics.classtype; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +public abstract class TypeToken { + private Type type; + + protected TypeToken(){ + Type superclass = getClass().getGenericSuperclass(); + this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0]; + } + + public Type getType() { + return type; + } +} diff --git a/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/classtype/GenericClassTypeUnitTest.java b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/classtype/GenericClassTypeUnitTest.java new file mode 100644 index 0000000000..85026e53de --- /dev/null +++ b/core-java-modules/core-java-lang-oop-generics/src/test/java/com/baeldung/classtype/GenericClassTypeUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.classtype; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.baeldung.generics.classtype.ContainerTypeFromReflection; +import com.baeldung.generics.classtype.ContainerTypeFromTypeParameter; +import com.baeldung.generics.classtype.TypeToken; + +public class GenericClassTypeUnitTest { + + @Test + public void givenContainerClassWithGenericType_whenTypeParameterUsed_thenReturnsClassType() { + var stringContainer = new ContainerTypeFromTypeParameter<>(String.class); + Class containerClass = stringContainer.getClazz(); + + assertEquals(containerClass, String.class); + } + + @Test + public void givenContainerClassWithGenericType_whenReflectionUsed_thenReturnsClassType() { + var stringContainer = new ContainerTypeFromReflection<>("Hello Java"); + Class stringClazz = stringContainer.getClazz(); + assertEquals(stringClazz, String.class); + + var integerContainer = new ContainerTypeFromReflection<>(1); + Class integerClazz = integerContainer.getClazz(); + assertEquals(integerClazz, Integer.class); + } + + @Test + public void giveContainerClassWithGenericType_whenTypeTokenUsed_thenReturnsClassType() { + class ContainerTypeFromTypeToken extends TypeToken> { + } + + var container = new ContainerTypeFromTypeToken(); + ParameterizedType type = (ParameterizedType) container.getType(); + Type actualTypeArgument = type.getActualTypeArguments()[0]; + + assertEquals(actualTypeArgument, String.class); + } +} diff --git a/core-java-modules/core-java-lang-operators-2/README.md b/core-java-modules/core-java-lang-operators-2/README.md index e8b792e634..4b93f8d192 100644 --- a/core-java-modules/core-java-lang-operators-2/README.md +++ b/core-java-modules/core-java-lang-operators-2/README.md @@ -10,3 +10,4 @@ This module contains articles about Java operators - [Check if at Least Two Out of Three Booleans Are True in Java](https://www.baeldung.com/java-check-two-of-three-booleans) - [Alternatives for instanceof Operator in Java](https://www.baeldung.com/java-instanceof-alternatives) - [What Does “––>†Mean in Java?](https://www.baeldung.com/java-minus-minus-greaterthan) +- [All the Ways Java Uses the Colon Character](https://www.baeldung.com/java-colon) diff --git a/core-java-modules/core-java-loops/README.md b/core-java-modules/core-java-loops/README.md new file mode 100644 index 0000000000..5616cce48b --- /dev/null +++ b/core-java-modules/core-java-loops/README.md @@ -0,0 +1 @@ +## Relevant Articles diff --git a/core-java-modules/core-java-loops/pom.xml b/core-java-modules/core-java-loops/pom.xml new file mode 100644 index 0000000000..c9ce86f54b --- /dev/null +++ b/core-java-modules/core-java-loops/pom.xml @@ -0,0 +1,16 @@ + + + 4.0.0 + core-java-loops + core-java-loops + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + diff --git a/core-java-modules/core-java-loops/src/test/java/com/baeldung/loops/TheLastIterationInForEachUnitTest.java b/core-java-modules/core-java-loops/src/test/java/com/baeldung/loops/TheLastIterationInForEachUnitTest.java new file mode 100644 index 0000000000..e8e20d4db7 --- /dev/null +++ b/core-java-modules/core-java-loops/src/test/java/com/baeldung/loops/TheLastIterationInForEachUnitTest.java @@ -0,0 +1,93 @@ +package com.baeldung.loops; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + +import org.junit.jupiter.api.Test; + +public class TheLastIterationInForEachUnitTest { + + //@formatter:off + private static final List MOVIES = List.of( + "Titanic", + "The Deer Hunter", + "Lord of the Rings", + "One Flew Over the Cuckoo's Nest", + "No Country For Old Men"); + //@formatter:on + + @Test + void whenUsingForEach_thenGetTheLastElementAfterTheLoop() { + String myLastMovie = ""; + for (String movie : MOVIES) { + // ... work with movie + myLastMovie = movie; + } + assertEquals("No Country For Old Men", myLastMovie); + } + + @Test + void whenLoopingWithIndexes_thenGetExpectedResult() { + int size = MOVIES.size(); + String myLastMovie = null; + for (int i = 0; i < size; i++) { + String movie = MOVIES.get(i); + // ... work with movie + if (i == size - 1) { + myLastMovie = movie; + } + } + assertEquals("No Country For Old Men", myLastMovie); + } + + @Test + void whenUsingIntStream_thenGetExpectedResult() { + int size = MOVIES.size(); + final Map myLastMovie = new HashMap<>(); + IntStream.range(0, size) + .forEach(idx -> { + String movie = MOVIES.get(idx); + // ... work with movie + if (idx == size - 1) { + myLastMovie.put(idx, movie); + } + }); + assertEquals(1, myLastMovie.size()); + assertTrue(myLastMovie.containsKey(size - 1)); + assertTrue(myLastMovie.containsValue("No Country For Old Men")); + } + + @Test + void whenUsingCounter_thenGetExpectedResult() { + int size = MOVIES.size(); + String myLastMovie = null; + int cnt = 0; + for (String movie : MOVIES) { + // ... work with movie + if (++cnt == size) { + myLastMovie = movie; + } + } + assertEquals("No Country For Old Men", myLastMovie); + } + + @Test + void whenUsingIterator_thenGetExpectedResult() { + String movie; + String myLastMovie = null; + for (Iterator it = MOVIES.iterator(); it.hasNext(); ) { + movie = it.next(); + // ... work with movie + if (!it.hasNext()) { // the last element + myLastMovie = movie; + } + } + assertEquals("No Country For Old Men", myLastMovie); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-numbers-7/README.md b/core-java-modules/core-java-numbers-7/README.md new file mode 100644 index 0000000000..42a43fd1fd --- /dev/null +++ b/core-java-modules/core-java-numbers-7/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Check if a double Is an Integer in Java](https://www.baeldung.com/java-check-double-integer) diff --git a/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/withoutscientificnotation/PrintDoubleWithoutScientificNotationUnitTest.java b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/withoutscientificnotation/PrintDoubleWithoutScientificNotationUnitTest.java new file mode 100644 index 0000000000..a9e78c76a0 --- /dev/null +++ b/core-java-modules/core-java-numbers-7/src/test/java/com/baeldung/withoutscientificnotation/PrintDoubleWithoutScientificNotationUnitTest.java @@ -0,0 +1,113 @@ +package com.baeldung.withoutscientificnotation; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.util.Locale; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class PrintDoubleWithoutScientificNotationUnitTest { + + private final PrintStream standardOut = System.out; + private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); + + @BeforeEach + public void setUp() { + System.setOut(new PrintStream(outputStreamCaptor)); + Locale.setDefault(Locale.US); + } + + @AfterEach + public void tearDown() { + System.setOut(standardOut); + } + + @Test + void givenLargeNumber_whenPrintWithDecimalFormat_thenOutputIsWithoutScientificNotation() { + + DecimalFormat df = new DecimalFormat("#.###########"); + double largeNumber = 256450000d; + System.out.println("Large Number: " + df.format(largeNumber)); + + Assertions.assertEquals("Large Number: 256450000", outputStreamCaptor.toString() + .trim()); + } + + @Test + void givenSmallNumber_whenPrintWithDecimalFormat_thenOutputIsWithoutScientificNotation() { + + DecimalFormat df = new DecimalFormat("#.###########"); + double smallNumber = 0.0000046d; + System.out.println("Small Number: " + df.format(smallNumber)); + + Assertions.assertEquals("Small Number: 0.0000046", outputStreamCaptor.toString() + .trim()); + } + + @Test + void givenLargeNumber_whenPrintWithPrintf_thenOutputIsWithoutScientificNotation() { + + double largeNumber = 256450000d; + System.out.printf("Large Number: %.7f", largeNumber); + + Assertions.assertEquals("Large Number: 256450000.0000000", outputStreamCaptor.toString() + .trim()); + } + + @Test + void givenSmallNumber_whenPrintWithPrintf_thenOutputIsWithoutScientificNotation() { + + double smallNumber = 0.0000046d; + System.out.printf("Small Number: %.7f", smallNumber); + + Assertions.assertEquals("Small Number: 0.0000046", outputStreamCaptor.toString() + .trim()); + } + + @Test + void givenLargeNumber_whenPrintWithBigDecimal_thenOutputIsWithoutScientificNotation() { + + double largeNumber = 256450000d; + System.out.println("Large Number: " + BigDecimal.valueOf(largeNumber).toPlainString()); + + Assertions.assertEquals("Large Number: 256450000", outputStreamCaptor.toString() + .trim()); + } + + @Test + void givenSmallNumber_whenPrintWithBigDecimal_thenOutputIsWithoutScientificNotation() { + + double smallNumber = 0.0000046d; + System.out.println("Small Number: " + BigDecimal.valueOf(smallNumber).toPlainString()); + + Assertions.assertEquals("Small Number: 0.0000046", outputStreamCaptor.toString() + .trim()); + } + + @Test + void givenLargeNumber_whenPrintWithStringFormat_thenOutputIsWithoutScientificNotation() { + + double largeNumber = 256450000d; + String formattedLargeNumber = String.format("%.7f", largeNumber); + System.out.println("Large Number: " + formattedLargeNumber); + + Assertions.assertEquals("Large Number: 256450000.0000000", outputStreamCaptor.toString() + .trim()); + } + + @Test + void givenSmallNumber_whenPrintWithStringFormat_thenOutputIsWithoutScientificNotation() { + + double smallNumber = 0.0000046d; + String formattedSmallNumber = String.format("%.7f", smallNumber); + System.out.println("Small Number: " + formattedSmallNumber); + + Assertions.assertEquals("Small Number: 0.0000046", outputStreamCaptor.toString() + .trim()); + } +} diff --git a/core-java-modules/core-java-numbers-conversions/README.md b/core-java-modules/core-java-numbers-conversions/README.md index dead88f025..b5f02a9d47 100644 --- a/core-java-modules/core-java-numbers-conversions/README.md +++ b/core-java-modules/core-java-numbers-conversions/README.md @@ -4,3 +4,5 @@ - [Convert int to Long in Java](https://www.baeldung.com/java-convert-int-long) - [How To Convert Double To Float In Java](https://www.baeldung.com/java-convert-double-float) - [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) diff --git a/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/CombiningUnitTest.java b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/CombiningUnitTest.java index c98eef5ed1..bef910024d 100644 --- a/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/CombiningUnitTest.java +++ b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/CombiningUnitTest.java @@ -9,7 +9,7 @@ import org.slf4j.LoggerFactory; public class CombiningUnitTest { private static final Logger LOG = LoggerFactory.getLogger(CombiningUnitTest.class); - public static final int TOP = 10000000; + public static final int TOP = 1000000; public static final double FRACTION = 0.1; @Test diff --git a/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/IfUnitTest.java b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/IfUnitTest.java index 6f80624502..3a434d942b 100644 --- a/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/IfUnitTest.java +++ b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/IfUnitTest.java @@ -12,7 +12,7 @@ import org.slf4j.LoggerFactory; public class IfUnitTest { private static final Logger LOG = LoggerFactory.getLogger(IfUnitTest.class); - public static final int TOP = 10000000; + public static final int TOP = 1000000; @Test public void majorBranchSorted() { diff --git a/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/SortingUnitTest.java b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/SortingUnitTest.java index 6af40bd57a..0def407e73 100644 --- a/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/SortingUnitTest.java +++ b/core-java-modules/core-java-perf/src/test/java/com/baeldung/branchprediction/SortingUnitTest.java @@ -11,7 +11,7 @@ import org.slf4j.LoggerFactory; public class SortingUnitTest { private static final Logger LOG = LoggerFactory.getLogger(SortingUnitTest.class); - public static final int BIG = 10000000; + public static final int BIG = 1000000; public static final int SMALL = 100000; @Test diff --git a/core-java-modules/core-java-streams-3/README.md b/core-java-modules/core-java-streams-3/README.md index 70d9e68a5e..45da963eb3 100644 --- a/core-java-modules/core-java-streams-3/README.md +++ b/core-java-modules/core-java-streams-3/README.md @@ -11,4 +11,4 @@ This module contains articles about the Stream API in Java. - [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close) - [Returning Stream vs. Collection](https://www.baeldung.com/java-return-stream-collection) - [Convert a Java Enumeration Into a Stream](https://www.baeldung.com/java-enumeration-to-stream) -- More articles: [[<-- prev>]](/../core-java-streams-2) +- More articles: [[<-- prev>]](/../core-java-streams-2) [[next -->]](/../core-java-streams-4) diff --git a/core-java-modules/core-java-streams-4/README.md b/core-java-modules/core-java-streams-4/README.md index c6717ec5fe..554649fdaa 100644 --- a/core-java-modules/core-java-streams-4/README.md +++ b/core-java-modules/core-java-streams-4/README.md @@ -10,3 +10,4 @@ - [Understanding the Difference Between Stream.of() and IntStream.range()](https://www.baeldung.com/java-stream-of-and-intstream-range) - [Check if Object Is an Array in Java](https://www.baeldung.com/java-check-if-object-is-an-array) - [Mapping an Array of Integers to Strings Using Java Streams](https://www.baeldung.com/java-stream-integer-array-to-strings) +- More articles: [[<-- prev>]](/../core-java-streams-3) [[next -->]](/../core-java-streams-5) diff --git a/core-java-modules/core-java-streams-4/pom.xml b/core-java-modules/core-java-streams-4/pom.xml index e832cc1616..383f14d573 100644 --- a/core-java-modules/core-java-streams-4/pom.xml +++ b/core-java-modules/core-java-streams-4/pom.xml @@ -71,7 +71,7 @@ io.projectreactor reactor-core - ${io.reactor3.version} + ${reactor-core.version} org.apache.commons @@ -121,7 +121,7 @@ 2.2.2 3.1.5 1.0.0-alpha-4 - 3.5.1 + 3.6.0 4.4 10.4.1 diff --git a/core-java-modules/core-java-streams-5/README.md b/core-java-modules/core-java-streams-5/README.md index dfd5a649b5..6e160e68ad 100644 --- a/core-java-modules/core-java-streams-5/README.md +++ b/core-java-modules/core-java-streams-5/README.md @@ -6,5 +6,7 @@ - [Partition a Stream in Java](https://www.baeldung.com/java-partition-stream) - [Taking Every N-th Element from Finite and Infinite Streams in Java](https://www.baeldung.com/java-nth-element-finite-infinite-streams) - [Modifying Objects Within Stream While Iterating](https://www.baeldung.com/java-stream-modify-objects-during-iteration) -- [Convert a Stream into a Map or Multimap in Java](https://www.baeldung.com/java-convert-stream-map-multimap) - [How to Avoid NoSuchElementException in Stream API](https://www.baeldung.com/java-streams-api-avoid-nosuchelementexception) +- [Get Index of First Element Matching Boolean Using Java Streams](https://www.baeldung.com/java-streams-find-first-match-index) +- [Handling NullPointerException in findFirst() When the First Element Is Null](https://www.baeldung.com/java-handle-nullpointerexception-findfirst-first-null) +- More articles: [[<-- prev>]](/../core-java-streams-4) diff --git a/core-java-modules/core-java-streams-5/pom.xml b/core-java-modules/core-java-streams-5/pom.xml index 33cd69f761..bb1703dada 100644 --- a/core-java-modules/core-java-streams-5/pom.xml +++ b/core-java-modules/core-java-streams-5/pom.xml @@ -67,7 +67,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${maven.compiler.source} ${maven.compiler.target} diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/findfirstnullpointerexception/FindFirstNullPointerExceptionUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/findfirstnullpointerexception/FindFirstNullPointerExceptionUnitTest.java new file mode 100644 index 0000000000..074aec29d6 --- /dev/null +++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/findfirstnullpointerexception/FindFirstNullPointerExceptionUnitTest.java @@ -0,0 +1,42 @@ +package com.baeldung.findfirstnullpointerexception; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Function; + +import org.junit.Test; + +public class FindFirstNullPointerExceptionUnitTest { + + private final List inputs = Arrays.asList(null, "foo", "bar"); + + @Test(expected = NullPointerException.class) + public void givenStream_whenCallingFindFirst_thenThrowNullPointerException() { + Optional firstElement = inputs.stream() + .findFirst(); + } + + @Test + public void givenStream_whenUsingOfNullableBeforeFindFirst_thenCorrect() { + Optional firstElement = inputs.stream() + .map(Optional::ofNullable) + .findFirst() + .flatMap(Function.identity()); + + assertTrue(firstElement.isEmpty()); + } + + @Test + public void givenStream_whenUsingFilterBeforeFindFirst_thenCorrect() { + Optional firstNonNullElement = inputs.stream() + .filter(Objects::nonNull) + .findFirst(); + + assertTrue(firstNonNullElement.isPresent()); + } + +} diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/firstmatchingelement/FirstMatchingElementUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/firstmatchingelement/FirstMatchingElementUnitTest.java index db9415e94b..0820138b3b 100644 --- a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/firstmatchingelement/FirstMatchingElementUnitTest.java +++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/streams/firstmatchingelement/FirstMatchingElementUnitTest.java @@ -34,7 +34,7 @@ public class FirstMatchingElementUnitTest { @Test public void whenUsingIntStream_thenFindFirstMatchingUserIndex() { - int index = IntStream.range(0, userList.size() - 1) + int index = IntStream.range(0, userList.size()) .filter(streamIndex -> searchName.equals(userList.get(streamIndex).getUserName())) .findFirst() .orElse(-1); diff --git a/core-java-modules/core-java-streams-maps/README.md b/core-java-modules/core-java-streams-maps/README.md index f9f7dffad9..8f311d91a5 100644 --- a/core-java-modules/core-java-streams-maps/README.md +++ b/core-java-modules/core-java-streams-maps/README.md @@ -1,2 +1,3 @@ ## Relevant Articles: - [Handle Duplicate Keys When Producing Map Using Java Stream](https://www.baeldung.com/java-duplicate-keys-when-producing-map-using-stream) +- [Convert a Stream into a Map or Multimap in Java](https://www.baeldung.com/java-convert-stream-map-multimap) \ No newline at end of file diff --git a/core-java-modules/core-java-streams-maps/pom.xml b/core-java-modules/core-java-streams-maps/pom.xml index 6b04897a29..8942a1f55f 100644 --- a/core-java-modules/core-java-streams-maps/pom.xml +++ b/core-java-modules/core-java-streams-maps/pom.xml @@ -46,7 +46,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${maven.compiler.source} ${maven.compiler.target} diff --git a/core-java-modules/core-java-streams-maps/src/test/java/com/baeldung/streams/streamtomapandmultimap/StreamToMapAndMultiMapUnitTest.java b/core-java-modules/core-java-streams-maps/src/test/java/com/baeldung/streams/streamtomapandmultimap/StreamToMapAndMultiMapUnitTest.java new file mode 100644 index 0000000000..6e8c26a76e --- /dev/null +++ b/core-java-modules/core-java-streams-maps/src/test/java/com/baeldung/streams/streamtomapandmultimap/StreamToMapAndMultiMapUnitTest.java @@ -0,0 +1,107 @@ +package com.baeldung.streams.streamtomapandmultimap; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.Test; + +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.ListMultimap; + +public class StreamToMapAndMultiMapUnitTest { + @Test + public void givenStringStream_whenConvertingToMapWithMerge_thenExpectedMapIsGenerated() { + Stream stringStream = Stream.of("one", "two", "three", "two"); + + Map mergedMap = stringStream.collect( + Collectors.toMap(s -> s, s -> s, (s1, s2) -> s1 + ", " + s2) + ); + + // Define the expected map + Map expectedMap = Map.of( + "one", "one", + "two", "two, two", + "three", "three" + ); + + assertEquals(expectedMap, mergedMap); + } + + @Test + public void givenStringStream_whenConvertingToMultimap_thenExpectedMultimapIsGenerated() { + Stream stringStream = Stream.of("one", "two", "three", "two"); + + ListMultimap multimap = stringStream.collect( + ArrayListMultimap::create, + (map, element) -> map.put(element, element), + ArrayListMultimap::putAll + ); + + ListMultimap expectedMultimap = ArrayListMultimap.create(); + expectedMultimap.put("one", "one"); + expectedMultimap.put("two", "two"); + expectedMultimap.put("two", "two"); + expectedMultimap.put("three", "three"); + + assertEquals(expectedMultimap, multimap); + } + + @Test + public void givenStringStream_whenConvertingToMultimapWithStreamReduce_thenExpectedMultimapIsGenerated() { + Stream stringStream = Stream.of("one", "two", "three", "two"); + + Map> multimap = stringStream.reduce( + new HashMap<>(), + (map, element) -> { + map.computeIfAbsent(element, k -> new ArrayList<>()).add(element); + return map; + }, + (map1, map2) -> { + map2.forEach((key, value) -> map1.merge(key, value, (list1, list2) -> { + list1.addAll(list2); + return list1; + })); + return map1; + } + ); + + Map> expectedMultimap = new HashMap<>(); + expectedMultimap.put("one", Collections.singletonList("one")); + expectedMultimap.put("two", Arrays.asList("two", "two")); + expectedMultimap.put("three", Collections.singletonList("three")); + + assertEquals(expectedMultimap, multimap); + } + + @Test + public void givenStringStream_whenConvertingToMapWithStreamReduce_thenExpectedMapIsGenerated() { + Stream stringStream = Stream.of("one", "two", "three", "two"); + + Map resultMap = stringStream.reduce( + new HashMap<>(), + (map, element) -> { + map.put(element, element); + return map; + }, + (map1, map2) -> { + map1.putAll(map2); + return map1; + } + ); + + Map expectedMap = new HashMap<>(); + expectedMap.put("one", "one"); + expectedMap.put("two", "two"); + expectedMap.put("three", "three"); + + assertEquals(expectedMap, resultMap); + } +} diff --git a/core-java-modules/core-java-streams/README.md b/core-java-modules/core-java-streams/README.md index adb4c1dda1..158ae84591 100644 --- a/core-java-modules/core-java-streams/README.md +++ b/core-java-modules/core-java-streams/README.md @@ -12,4 +12,5 @@ This module contains articles about the Stream API in Java. - [Counting Matches on a Stream Filter](https://www.baeldung.com/java-stream-filter-count) - [Summing Numbers with Java Streams](https://www.baeldung.com/java-stream-sum) - [How to Find All Getters Returning Null](https://www.baeldung.com/java-getters-returning-null) +- [Skip Bytes in InputStream in Java](https://www.baeldung.com/java-inputstream-skip-bytes) - More articles: [[next -->]](/../core-java-streams-2) diff --git a/core-java-modules/core-java-string-algorithms-4/README.md b/core-java-modules/core-java-string-algorithms-4/README.md new file mode 100644 index 0000000000..0651448493 --- /dev/null +++ b/core-java-modules/core-java-string-algorithms-4/README.md @@ -0,0 +1,5 @@ +## Java String Algorithms + +This module contains articles about string-related algorithms. + +### Relevant Articles: \ No newline at end of file diff --git a/core-java-modules/core-java-string-algorithms-4/pom.xml b/core-java-modules/core-java-string-algorithms-4/pom.xml new file mode 100644 index 0000000000..b374b48743 --- /dev/null +++ b/core-java-modules/core-java-string-algorithms-4/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + core-java-string-algorithms-4 + core-java-string-algorithms-4 + 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-string-algorithms-4/src/test/java/com/baeldung/string/shiftchar/ShiftCharInStringUnitTest.java b/core-java-modules/core-java-string-algorithms-4/src/test/java/com/baeldung/string/shiftchar/ShiftCharInStringUnitTest.java new file mode 100644 index 0000000000..92bbc48c98 --- /dev/null +++ b/core-java-modules/core-java-string-algorithms-4/src/test/java/com/baeldung/string/shiftchar/ShiftCharInStringUnitTest.java @@ -0,0 +1,100 @@ +package com.baeldung.string.shiftchar; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +public class ShiftCharInStringUnitTest { + + private final static String STRING = "abcdefg"; + + private final static String EXPECT_1X = "gabcdef"; + private final static String EXPECT_2X = "fgabcde"; + private final static String EXPECT_3X = "efgabcd"; + private final static String EXPECT_6X = "bcdefga"; + private final static String EXPECT_7X = "abcdefg"; + private final static String EXPECT_24X = "efgabcd"; + + private final static String B_EXPECT_1X = "bcdefga"; + private final static String B_EXPECT_2X = "cdefgab"; + private final static String B_EXPECT_3X = "defgabc"; + private final static String B_EXPECT_6X = "gabcdef"; + private final static String B_EXPECT_7X = "abcdefg"; + private final static String B_EXPECT_24X = "defgabc"; + + static String rotateString1(String s, int c, boolean forward) { + if (c < 0) { + throw new IllegalArgumentException("Rotation character count cannot be negative!"); + } + int len = s.length(); + int n = c % len; + if (n == 0) { + return s; + } + n = forward ? n : len - n; + return s.substring(len - n, len) + s.substring(0, len - n); + } + + static String rotateString2(String s, int c, boolean forward) { + if (c < 0) { + throw new IllegalArgumentException("Rotation character count cannot be negative!"); + } + int len = s.length(); + int n = c % len; + if (n == 0) { + return s; + } + String ss = s + s; + n = forward ? n : len - n; + return ss.substring(len - n, 2 * len - n); + } + + static boolean rotatedFrom(String rotated, String rotateFrom) { + return rotateFrom.length() == rotated.length() && (rotateFrom + rotateFrom).contains(rotated); + } + + @Test + void whenUsingRotateString1_thenGetExpectedResults() { + assertEquals(EXPECT_1X, rotateString1(STRING, 1, true)); + assertEquals(EXPECT_2X, rotateString1(STRING, 2, true)); + assertEquals(EXPECT_3X, rotateString1(STRING, 3, true)); + assertEquals(EXPECT_6X, rotateString1(STRING, 6, true)); + assertEquals(EXPECT_7X, rotateString1(STRING, 7, true)); + assertEquals(EXPECT_24X, rotateString1(STRING, 24, true)); + + //backward + assertEquals(B_EXPECT_1X, rotateString1(STRING, 1, false)); + assertEquals(B_EXPECT_2X, rotateString1(STRING, 2, false)); + assertEquals(B_EXPECT_3X, rotateString1(STRING, 3, false)); + assertEquals(B_EXPECT_6X, rotateString1(STRING, 6, false)); + assertEquals(B_EXPECT_7X, rotateString1(STRING, 7, false)); + assertEquals(B_EXPECT_24X, rotateString1(STRING, 24, false)); + } + + @Test + void whenUsingShiftString2_thenGetExpectedResults() { + assertEquals(EXPECT_1X, rotateString2(STRING, 1, true)); + assertEquals(EXPECT_2X, rotateString2(STRING, 2, true)); + assertEquals(EXPECT_3X, rotateString2(STRING, 3, true)); + assertEquals(EXPECT_6X, rotateString2(STRING, 6, true)); + assertEquals(EXPECT_7X, rotateString2(STRING, 7, true)); + assertEquals(EXPECT_24X, rotateString2(STRING, 24, true)); + + //backward + assertEquals(B_EXPECT_1X, rotateString2(STRING, 1, false)); + assertEquals(B_EXPECT_2X, rotateString2(STRING, 2, false)); + assertEquals(B_EXPECT_3X, rotateString2(STRING, 3, false)); + assertEquals(B_EXPECT_6X, rotateString2(STRING, 6, false)); + assertEquals(B_EXPECT_7X, rotateString2(STRING, 7, false)); + assertEquals(B_EXPECT_24X, rotateString2(STRING, 24, false)); + } + + @Test + void whenUsingRotateFrom_thenGetExpectedResults() { + assertTrue(rotatedFrom(EXPECT_7X, STRING)); + assertTrue(rotatedFrom(B_EXPECT_3X, STRING)); + assertFalse(rotatedFrom("abcefgd", STRING)); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-string-conversions-3/src/test/java/com/baeldung/stringtocharlist/StringToCharListUnitTest.java b/core-java-modules/core-java-string-conversions-3/src/test/java/com/baeldung/stringtocharlist/StringToCharListUnitTest.java new file mode 100644 index 0000000000..1cdbfb9df9 --- /dev/null +++ b/core-java-modules/core-java-string-conversions-3/src/test/java/com/baeldung/stringtocharlist/StringToCharListUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.stringtocharlist; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import com.google.common.collect.Lists; + + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class StringToCharListUnitTest { + public String inputString = "Convert a String to a List of Characters in Java"; + + @Test + public void givenString_whenUsingToCharArray_thenConvertToCharList() { + char[] charArray = inputString.toCharArray(); + + List charList = new ArrayList<>(); + for (char c : charArray) { + charList.add(c); + } + + assertEquals(inputString.length(), charList.size()); + } + + @Test + public void givenString_whenUsingMapToObj_thenConvertToCharList() { + List charList = inputString.chars() + .mapToObj(c -> (char) c) + .toList(); + + assertEquals(inputString.length(), charList.size()); + } + + @Test + public void givenString_whenUsingSplit_thenConvertToStringList() { + String[] charArray = inputString.split(""); + + List charList = Arrays.asList(charArray); + + assertEquals(inputString.length(), charList.size()); + } + + @Test + public void givenString_whenUsingGuavaLists_thenConvertToCharList() { + List charList = Lists.charactersOf(inputString); + + assertEquals(inputString.length(), charList.size()); + } + + @Test + public void givenString_whenUsingCodePoints_thenConvertToCharList() { + List charList = inputString.codePoints() + .mapToObj(c -> (char) c) + .toList(); + + assertEquals(inputString.length(), charList.size()); + } +} diff --git a/core-java-modules/core-java-string-operations-7/README.md b/core-java-modules/core-java-string-operations-7/README.md index a05485ccb9..a0460f26d2 100644 --- a/core-java-modules/core-java-string-operations-7/README.md +++ b/core-java-modules/core-java-string-operations-7/README.md @@ -6,3 +6,4 @@ - [Create a Mutable String in Java](https://www.baeldung.com/java-mutable-string) - [Check if a String Contains a Number Value in Java](https://www.baeldung.com/java-string-number-presence) - [Difference Between String isEmpty() and isBlank()](https://www.baeldung.com/java-string-isempty-vs-isblank) +- [String’s Maximum Length in Java](https://www.baeldung.com/java-strings-maximum-length) 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 33a74365bc..cea3e32f2f 100644 --- a/core-java-modules/core-java-string-operations-7/pom.xml +++ b/core-java-modules/core-java-string-operations-7/pom.xml @@ -24,6 +24,21 @@ commons-text ${commons-text.version} + + org.apache.tika + tika-core + ${apache.tika.version} + + + org.apache.tika + tika-parsers-standard-package + ${apache.tika.version} + + + com.ibm.icu + icu4j + ${icu4j.version} + org.junit.jupiter junit-jupiter @@ -60,7 +75,9 @@ 11 11 3.13.0 + 2.9.1 1.10.0 + 74.1 4.25.0 diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/aboutlength/StringLengthAndByteArrayLengthUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/aboutlength/StringLengthAndByteArrayLengthUnitTest.java new file mode 100644 index 0000000000..94c855acb9 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/aboutlength/StringLengthAndByteArrayLengthUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.aboutlength; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.nio.charset.Charset; + +import org.junit.jupiter.api.Test; + +public class StringLengthAndByteArrayLengthUnitTest { + + @Test + void whenStrWithAllAsciiChar_thenStrLengthAndBytesLengthAreEqual() { + String s = "beautiful"; + assertEquals(9, s.length()); + assertEquals(9, s.getBytes().length); + } + + @Test + void whenStrWithUnicodeChar_thenStrLengthAndBytesLengthAreNotEqual() { + assertEquals("f6", Integer.toHexString('ö')); + assertEquals("7f8e", Integer.toHexString('美')); + assertEquals("4e3d", Integer.toHexString('丽')); + + String de = "schöne"; + assertEquals(6, de.length()); + assertEquals(7, de.getBytes().length); + + String cn = "美丽"; + assertEquals(2, cn.length()); + assertEquals(6, cn.getBytes().length); + } + + @Test + void whenUsingUTF_32_thenBytesLengthIs4TimesStrLength() { + Charset UTF_32 = Charset.forName("UTF_32"); + + String en = "beautiful"; + assertEquals(9, en.length()); + assertEquals(9 * 4, en.getBytes(UTF_32).length); + + String de = "schöne"; + assertEquals(6, de.length()); + assertEquals(6 * 4, de.getBytes(UTF_32).length); + + String cn = "美丽"; + assertEquals(2, cn.length()); + assertEquals(2 * 4, cn.getBytes(UTF_32).length); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/compareany/CompareAnyBenchmark.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/compareany/CompareAnyBenchmark.java new file mode 100644 index 0000000000..c018cca718 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/compareany/CompareAnyBenchmark.java @@ -0,0 +1,98 @@ +package com.baeldung.compareany; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@Warmup(iterations = 2) +@Measurement(iterations = 5) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Fork(value = 1) +public class CompareAnyBenchmark { + private final String[] groupOfFruits = {"Apple", "Mango", "Dragon Fruit", "Water Melon", "Avocado", "Guava", "Orange"}; + private final String fruit = "Apple"; + + @Benchmark + public boolean compareWithMultipleStringsUsingStringUtils() { + return StringUtils.equalsAny(fruit, groupOfFruits); + } + + @Benchmark + public boolean compareCaseInsensitiveWithMultipleStringsUsingStringUtils() { + return StringUtils.equalsAnyIgnoreCase(fruit, groupOfFruits); + } + + @Benchmark + public boolean compareWithMultipleStringsUsingSet() { + return Set.of(groupOfFruits).contains(fruit); + } + + @Benchmark + public boolean compareWithMultipleStringsUsingList() { + return List.of(groupOfFruits).contains(fruit); + } + + @Benchmark + public boolean compareWithMultipleStringsUsingRegularExpression() { + return fruit.matches(String.join("|", groupOfFruits)); + } + + @Benchmark + public boolean compareCaseInsensitiveWithMultipleStringsUsingRegularExpression() { + return fruit.matches("(?i)" + String.join("|", groupOfFruits)); + } + + @Benchmark + public boolean compareWithMultipleStringsUsingStream() { + return Arrays.stream(groupOfFruits).anyMatch(fruit::equals); + } + + @Benchmark + public boolean compareCaseInsensitiveWithMultipleStringsUsingStream() { + return Arrays.stream(groupOfFruits).anyMatch(fruit::equalsIgnoreCase); + } + + @Benchmark + public boolean compareWithMultipleStringsUsingArrayUtils() { + return ArrayUtils.contains(groupOfFruits, fruit); + } + + @Benchmark + public boolean compareWithMultipleStringsUsingIf() { + for(String s : groupOfFruits) { + if (fruit.equals(s)) { + return true; + } + } + return false; + } + + public static void main(String[] args) throws Exception { + Options options = new OptionsBuilder().include(CompareAnyBenchmark.class.getSimpleName()) + .threads(1) + .shouldFailOnError(true) + .shouldDoGC(true) + .jvmArgs("-server") + .build(); + new Runner(options).run(); + } + +} diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/compareany/CompareAnyUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/compareany/CompareAnyUnitTest.java new file mode 100644 index 0000000000..052be2fe58 --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/compareany/CompareAnyUnitTest.java @@ -0,0 +1,150 @@ +package com.baeldung.compareany; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.junit.jupiter.api.Test; + +public class CompareAnyUnitTest { + + @Test + void givenStrings_whenCompareWithMultipleStringsUsingIf_thenSuccess() { + String presentString = "Apple"; + String notPresentString = "Avocado"; + + assertTrue(compareWithMultipleStringsUsingIf(presentString, "Mango", "Papaya", "Pineapple", "Apple")); + assertFalse(compareWithMultipleStringsUsingIf(notPresentString, "Mango", "Papaya", "Pineapple", "Apple")); + } + + @Test + void givenStrings_whenCompareWithMultipleStringsUsingArrayUtils_thenSuccess() { + String presentString = "Apple"; + String notPresentString = "Avocado"; + + assertTrue(compareWithMultipleStringsUsingArrayUtils(presentString, "Mango", "Papaya", "Pineapple", "Apple")); + assertFalse(compareWithMultipleStringsUsingArrayUtils(notPresentString, "Mango", "Papaya", "Pineapple", "Apple")); + } + + @Test + void givenStrings_whenCompareWithMultipleStringsUsingStringUtils_thenSuccess() { + String presentString = "Apple"; + String notPresentString = "Avocado"; + + assertTrue(compareWithMultipleStringsUsingStringUtils(presentString, "Mango", "Papaya", "Pineapple", "Apple")); + assertFalse(compareWithMultipleStringsUsingStringUtils(notPresentString, "Mango", "Papaya", "Pineapple", "Apple")); + } + + @Test + void givenStrings_whenCompareCaseInsensitiveWithMultipleStringsUsingStringUtils_thenSuccess() { + String presentString = "APPLE"; + String notPresentString = "AVOCADO"; + + assertTrue(compareCaseInsensitiveWithMultipleStringsUsingStringUtils(presentString, "Mango", "Papaya", "Pineapple", "Apple")); + assertFalse(compareCaseInsensitiveWithMultipleStringsUsingStringUtils(notPresentString, "Mango", "Papaya", "Pineapple", "Apple")); + } + + @Test + void givenStrings_whenCompareWithMultipleStringsUsingStream_thenSuccess() { + String presentString = "Apple"; + String notPresentString = "Avocado"; + + assertTrue(compareWithMultipleStringsUsingStream(presentString, "Mango", "Papaya", "Pineapple", "Apple")); + assertFalse(compareWithMultipleStringsUsingStream(notPresentString, "Mango", "Papaya", "Pineapple", "Apple")); + } + + @Test + void givenStrings_whenCompareCaseInsensitiveWithMultipleStringsUsingStream_thenSuccess() { + String presentString = "APPLE"; + String notPresentString = "AVOCADO"; + + assertTrue(compareCaseInsensitiveWithMultipleStringsUsingStream(presentString, "Mango", "Papaya", "Pineapple", "Apple")); + assertFalse(compareCaseInsensitiveWithMultipleStringsUsingStream(notPresentString, "Mango", "Papaya", "Pineapple", "Apple")); + } + + @Test + void givenStrings_whenCompareWithMultipleStringsUsingSet_thenSuccess() { + String presentString = "Apple"; + String notPresentString = "Avocado"; + + assertTrue(compareWithMultipleStringsUsingSet(presentString, "Mango", "Papaya", "Pineapple", "Apple")); + assertFalse(compareWithMultipleStringsUsingSet(notPresentString, "Mango", "Papaya", "Pineapple", "Apple")); + } + + @Test + void givenStrings_whenCompareWithMultipleStringsUsingList_thenSuccess() { + String presentString = "Apple"; + String notPresentString = "Avocado"; + + assertTrue(compareWithMultipleStringsUsingList(presentString, "Mango", "Papaya", "Pineapple", "Apple")); + assertFalse(compareWithMultipleStringsUsingList(notPresentString, "Mango", "Papaya", "Pineapple", "Apple")); + } + + @Test + void givenStrings_whenCompareWithMultipleStringsUsingRegularExpression_thenSuccess() { + String presentString = "Apple"; + String notPresentString = "Avocado"; + + assertTrue(compareWithMultipleStringsUsingRegularExpression(presentString, "Mango", "Papaya", "Pineapple", "Apple")); + assertFalse(compareWithMultipleStringsUsingRegularExpression(notPresentString, "Mango", "Papaya", "Pineapple", "Apple")); + } + + @Test + void givenStrings_whenCompareCaseInsensitiveWithMultipleStringsUsingRegularExpression_thenSuccess() { + String presentString = "APPLE"; + String notPresentString = "AVOCADO"; + + assertTrue(compareCaseInsensitiveWithMultipleStringsUsingRegularExpression(presentString, "Mango", "Papaya", "Pineapple", "Apple")); + assertFalse(compareCaseInsensitiveWithMultipleStringsUsingRegularExpression(notPresentString, "Mango", "Papaya", "Pineapple", "Apple")); + } + + private boolean compareWithMultipleStringsUsingIf(String str, String... strs) { + for (String s : strs) { + if (str.equals(s)) { + return true; + } + } + return false; + } + + private boolean compareWithMultipleStringsUsingStringUtils(String str, String... strs) { + return StringUtils.equalsAny(str, strs); + } + + private boolean compareCaseInsensitiveWithMultipleStringsUsingStringUtils(String str, String... strs) { + return StringUtils.equalsAnyIgnoreCase(str, strs); + } + + private boolean compareWithMultipleStringsUsingSet(String str, String... strs) { + return Set.of(strs).contains(str); + } + + private boolean compareWithMultipleStringsUsingList(String str, String... strs) { + return List.of(strs).contains(str); + } + + private boolean compareWithMultipleStringsUsingRegularExpression(String str, String... strs) { + return str.matches(String.join("|", strs)); + } + + private boolean compareCaseInsensitiveWithMultipleStringsUsingRegularExpression(String str, String... strs) { + return str.matches("(?i)" + String.join("|", strs)); + } + + private boolean compareWithMultipleStringsUsingStream(String str, String... strs) { + return Arrays.stream(strs).anyMatch(str::equals); + } + + private boolean compareCaseInsensitiveWithMultipleStringsUsingStream(String str, String... strs) { + return Arrays.stream(strs).anyMatch(str::equalsIgnoreCase); + } + + private boolean compareWithMultipleStringsUsingArrayUtils(String str, String... strs) { + return ArrayUtils.contains(strs, str); + } +} diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/stringbuilderhaschar/CheckIfStringBuilderContainsCharUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/stringbuilderhaschar/CheckIfStringBuilderContainsCharUnitTest.java new file mode 100644 index 0000000000..8d95b5533a --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/stringbuilderhaschar/CheckIfStringBuilderContainsCharUnitTest.java @@ -0,0 +1,44 @@ +package com.baeldung.stringbuilderhaschar; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class CheckIfStringBuilderContainsCharUnitTest { + + StringBuilder stringBuilder = new StringBuilder("Welcome to Baeldung Java Tutorial!"); + char targetChar = 'o'; + + @Test + public void givenStringBuilder_whenUsingIndexOfMethod_thenCheckIfSCharExists() { + int index = stringBuilder.indexOf(String.valueOf(targetChar)); + assertTrue(index != -1); + } + + @Test + public void givenStringBuilder_whenUsingContainsMethod_thenCheckIfSCharExists() { + boolean containsChar = stringBuilder.toString().contains(String.valueOf(targetChar)); + assertTrue(containsChar); + } + + @Test + public void givenStringBuilder_whenUsingJavaStream_thenCheckIfSCharExists() { + boolean charFound = stringBuilder.chars().anyMatch(c -> c == targetChar); + + assertTrue(charFound); + } + + @Test + public void givenStringBuilder_whenUsingIterations_thenCheckIfSCharExists() { + boolean charFound = false; + + for (int i = 0; i < stringBuilder.length(); i++) { + if (stringBuilder.charAt(i) == targetChar) { + charFound = true; + break; + } + } + + assertTrue(charFound); + } +} diff --git a/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/utf8validation/UTF8ValidationUnitTest.java b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/utf8validation/UTF8ValidationUnitTest.java new file mode 100644 index 0000000000..7e737bad1d --- /dev/null +++ b/core-java-modules/core-java-string-operations-7/src/test/java/com/baeldung/utf8validation/UTF8ValidationUnitTest.java @@ -0,0 +1,108 @@ +package com.baeldung.utf8validation; + +import com.ibm.icu.text.CharsetDetector; +import com.ibm.icu.text.CharsetMatch; +import org.apache.tika.detect.EncodingDetector; +import org.apache.tika.metadata.Metadata; +import org.apache.tika.parser.txt.UniversalEncodingDetector; +import org.junit.jupiter.api.Test; + +import java.io.*; +import java.nio.CharBuffer; +import java.nio.charset.*; + +import static org.junit.jupiter.api.Assertions.*; + +class UTF8ValidationUnitTest { + + private static final String UTF8_STRING = "Hello 你好"; + + private static final byte[] UTF8_BYTES = UTF8_STRING.getBytes(StandardCharsets.UTF_8); + + private static final byte[] INVALID_UTF8_BYTES = {(byte) 0xF0, (byte) 0xC1, (byte) 0x8C, (byte) 0xBC, (byte) 0xD1}; + + private static final InputStream ENGLISH_INPUTSTREAM = new ByteArrayInputStream("Hello".getBytes(StandardCharsets.UTF_8)); + + private static final InputStream UTF8_INPUTSTREAM = new ByteArrayInputStream(UTF8_BYTES); + + private static final InputStream INVALID_UTF8_INPUTSTREAM = new ByteArrayInputStream(INVALID_UTF8_BYTES); + + @Test + void whenConvertValidUTF8BytesToString_thenReturnExpectedString() { + String decodedStr = new String(UTF8_BYTES, StandardCharsets.UTF_8); + assertEquals(UTF8_STRING, decodedStr); + } + + @Test + void whenConvertInvalidUTF8BytesToString_thenReturnReplacementCharacters() { + String decodedStr = new String(INVALID_UTF8_BYTES, StandardCharsets.UTF_8); + assertEquals("�����", decodedStr); + } + + @Test + void whenDecodeValidUTF8Bytes_thenSucceeds() throws CharacterCodingException { + + CharsetDecoder charsetDecoder = StandardCharsets.UTF_8.newDecoder(); + CharBuffer decodedCharBuffer = charsetDecoder.decode(java.nio.ByteBuffer.wrap(UTF8_BYTES)); + assertEquals(UTF8_STRING, decodedCharBuffer.toString()); + } + + @Test + void whenDecodeInvalidUTF8Bytes_thenThrowsMalformedInputException() { + + CharsetDecoder charsetDecoder = StandardCharsets.UTF_8.newDecoder(); + assertThrows(MalformedInputException.class,() -> {charsetDecoder.decode(java.nio.ByteBuffer.wrap(INVALID_UTF8_BYTES));}); + } + + @Test + void whenValidateValidInputStreamByTika_thenReturnsUTF8() throws IOException { + + EncodingDetector encodingDetector = new UniversalEncodingDetector(); + Charset detectedCharset = encodingDetector.detect(UTF8_INPUTSTREAM, new Metadata()); + assertEquals(StandardCharsets.UTF_8, detectedCharset); + } + + @Test + void whenValidateValidEnglishInputStreamByTika_thenReturnsISO_88591_1() throws IOException { + + EncodingDetector encodingDetector = new UniversalEncodingDetector(); + Charset detectedCharset = encodingDetector.detect(ENGLISH_INPUTSTREAM, new Metadata()); + assertEquals(StandardCharsets.ISO_8859_1, detectedCharset); + } + + @Test + void whenValidateInvalidInputStreamByTika_thenReturnsNull() throws IOException { + + EncodingDetector encodingDetector = new UniversalEncodingDetector(); + Charset detectedCharset = encodingDetector.detect(INVALID_UTF8_INPUTSTREAM, new Metadata()); + assertNull(detectedCharset); + } + + @Test + void whenValidateValidInputStreamByICU4J_thenReturnsUTF8() throws IOException { + + CharsetDetector detector = new CharsetDetector(); + detector.setText(UTF8_INPUTSTREAM); + CharsetMatch charsetMatch = detector.detect(); + assertEquals(StandardCharsets.UTF_8.name(), charsetMatch.getName()); + } + + @Test + void whenValidateValidEnglishInputStreamByICU4J_thenReturnsISO_8859_1() throws IOException { + + CharsetDetector detector = new CharsetDetector(); + detector.setText(ENGLISH_INPUTSTREAM); + CharsetMatch charsetMatch = detector.detect(); + assertEquals(StandardCharsets.ISO_8859_1.name(), charsetMatch.getName()); + } + + @Test + void whenValidateValidInputStreamByICU4J_thenReturnsNotEqualToUTF_8() throws IOException { + + CharsetDetector detector = new CharsetDetector(); + detector.setText(INVALID_UTF8_INPUTSTREAM); + CharsetMatch charsetMatch = detector.detect(); + assertNotEquals(StandardCharsets.UTF_8.name(), charsetMatch.getName()); + } + +} \ No newline at end of file diff --git a/core-java-modules/core-java-strings/README.md b/core-java-modules/core-java-strings/README.md index e782793fea..82dfcca884 100644 --- a/core-java-modules/core-java-strings/README.md +++ b/core-java-modules/core-java-strings/README.md @@ -16,3 +16,4 @@ Listed here there are only those articles that does not fit into other core-java - [Reuse StringBuilder for Efficiency](https://www.baeldung.com/java-reuse-stringbuilder-for-efficiency) - [How to Iterate Over the String Characters in Java](https://www.baeldung.com/java-iterate-string-characters) - [Passing Strings by Reference in Java](https://www.baeldung.com/java-method-pass-string-reference) +- [String vs StringBuffer Comparison in Java](https://www.baeldung.com/java-string-vs-stringbuffer) diff --git a/core-java-modules/core-java-sun/src/test/java/com/baeldung/extractjava/ExtractJavaLiveTest.java b/core-java-modules/core-java-sun/src/test/java/com/baeldung/extractjava/ExtractJavaLiveTest.java new file mode 100644 index 0000000000..02904ad2fc --- /dev/null +++ b/core-java-modules/core-java-sun/src/test/java/com/baeldung/extractjava/ExtractJavaLiveTest.java @@ -0,0 +1,94 @@ +package com.baeldung.extractjava; + +import com.sun.source.tree.ClassTree; +import com.sun.source.tree.CompilationUnitTree; +import com.sun.source.tree.MethodTree; +import com.sun.source.tree.Tree; +import com.sun.source.util.JavacTask; +import com.sun.source.util.SimpleTreeVisitor; +import org.junit.Test; + +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.ToolProvider; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +public class ExtractJavaLiveTest { + @Test + public void visitTypeDeclsForClasses() throws Exception { + CompilationUnitTree compilationUnitTree = parseFile(); + + for (Tree tree : compilationUnitTree.getTypeDecls()) { + tree.accept(new SimpleTreeVisitor() { + @Override + public Object visitClass(ClassTree classTree, Object o) { + System.out.println("Found class: " + classTree.getSimpleName()); + return null; + } + }, null); + } + } + + @Test + public void iterateTypeDeclsForClasses() throws Exception { + CompilationUnitTree compilationUnitTree = parseFile(); + + for (Tree tree : compilationUnitTree.getTypeDecls()) { + if (tree.getKind() == Tree.Kind.CLASS) { + ClassTree classTree = (ClassTree) tree; + System.out.println("Found class: " + classTree.getSimpleName()); + } + } + } + + @Test + public void visitMethodsForClass() throws Exception { + CompilationUnitTree compilationUnitTree = parseFile(); + + for (Tree tree : compilationUnitTree.getTypeDecls()) { + if (tree.getKind() == Tree.Kind.CLASS) { + ClassTree classTree = (ClassTree) tree; + visitClassMethods(classTree); + } + } + + } + + private void visitClassMethods(ClassTree classTree) { + for (Tree member : classTree.getMembers()) { + member.accept(new SimpleTreeVisitor(){ + @Override + public Object visitMethod(MethodTree methodTree, Object o) { + System.out.println("Found method: " + classTree.getSimpleName() + "." + methodTree.getName()); + System.out.println("Return value: " + methodTree.getReturnType()); + System.out.println("Parameters: " + methodTree.getParameters()); + + for (Tree statement : methodTree.getBody().getStatements()) { + System.out.println("Found statement: " + statement); + } + + return null; + } + }, null); + } + } + + private static CompilationUnitTree parseFile() throws IOException { + String filename = "src/test/java/com/baeldung/extractjava/ExtractJavaUnitTest.java"; + + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + + StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, StandardCharsets.UTF_8); + Iterable compilationUnits = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(new File(filename))); + + JavacTask javacTask = (JavacTask) compiler.getTask(null, fileManager, null, null, null, compilationUnits); + Iterable compilationUnitTrees = javacTask.parse(); + + CompilationUnitTree compilationUnitTree = compilationUnitTrees.iterator().next(); + return compilationUnitTree; + } +} diff --git a/core-java-modules/core-java-swing/target/classes/org/example/Main.class b/core-java-modules/core-java-swing/target/classes/org/example/Main.class deleted file mode 100644 index 5914458bc4..0000000000 Binary files a/core-java-modules/core-java-swing/target/classes/org/example/Main.class and /dev/null differ diff --git a/java-rmi/README.md b/core-java-modules/java-rmi/README.md similarity index 100% rename from java-rmi/README.md rename to core-java-modules/java-rmi/README.md diff --git a/java-rmi/pom.xml b/core-java-modules/java-rmi/pom.xml similarity index 75% rename from java-rmi/pom.xml rename to core-java-modules/java-rmi/pom.xml index 2256883f84..aa864b49c7 100644 --- a/java-rmi/pom.xml +++ b/core-java-modules/java-rmi/pom.xml @@ -9,9 +9,9 @@ jar - com.baeldung - parent-modules - 1.0.0-SNAPSHOT + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT \ No newline at end of file diff --git a/java-rmi/src/main/java/com/baeldung/rmi/Message.java b/core-java-modules/java-rmi/src/main/java/com/baeldung/rmi/Message.java similarity index 100% rename from java-rmi/src/main/java/com/baeldung/rmi/Message.java rename to core-java-modules/java-rmi/src/main/java/com/baeldung/rmi/Message.java diff --git a/java-rmi/src/main/java/com/baeldung/rmi/MessengerService.java b/core-java-modules/java-rmi/src/main/java/com/baeldung/rmi/MessengerService.java similarity index 100% rename from java-rmi/src/main/java/com/baeldung/rmi/MessengerService.java rename to core-java-modules/java-rmi/src/main/java/com/baeldung/rmi/MessengerService.java diff --git a/java-rmi/src/main/java/com/baeldung/rmi/MessengerServiceImpl.java b/core-java-modules/java-rmi/src/main/java/com/baeldung/rmi/MessengerServiceImpl.java similarity index 100% rename from java-rmi/src/main/java/com/baeldung/rmi/MessengerServiceImpl.java rename to core-java-modules/java-rmi/src/main/java/com/baeldung/rmi/MessengerServiceImpl.java diff --git a/antlr/src/main/resources/logback.xml b/core-java-modules/java-rmi/src/main/resources/logback.xml similarity index 100% rename from antlr/src/main/resources/logback.xml rename to core-java-modules/java-rmi/src/main/resources/logback.xml diff --git a/java-rmi/src/test/java/com/baeldung/rmi/JavaRMIIntegrationTest.java b/core-java-modules/java-rmi/src/test/java/com/baeldung/rmi/JavaRMIIntegrationTest.java similarity index 100% rename from java-rmi/src/test/java/com/baeldung/rmi/JavaRMIIntegrationTest.java rename to core-java-modules/java-rmi/src/test/java/com/baeldung/rmi/JavaRMIIntegrationTest.java diff --git a/java-spi/README.md b/core-java-modules/java-spi/README.md similarity index 100% rename from java-spi/README.md rename to core-java-modules/java-spi/README.md diff --git a/java-spi/exchange-rate-api/pom.xml b/core-java-modules/java-spi/exchange-rate-api/pom.xml similarity index 100% rename from java-spi/exchange-rate-api/pom.xml rename to core-java-modules/java-spi/exchange-rate-api/pom.xml diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/ExchangeRate.java b/core-java-modules/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/ExchangeRate.java similarity index 100% rename from java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/ExchangeRate.java rename to core-java-modules/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/ExchangeRate.java diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/Quote.java b/core-java-modules/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/Quote.java similarity index 100% rename from java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/Quote.java rename to core-java-modules/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/Quote.java diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/QuoteManager.java b/core-java-modules/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/QuoteManager.java similarity index 100% rename from java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/QuoteManager.java rename to core-java-modules/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/QuoteManager.java diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/exception/ProviderNotFoundException.java b/core-java-modules/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/exception/ProviderNotFoundException.java similarity index 100% rename from java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/exception/ProviderNotFoundException.java rename to core-java-modules/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/exception/ProviderNotFoundException.java diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/spi/ExchangeRateProvider.java b/core-java-modules/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/spi/ExchangeRateProvider.java similarity index 100% rename from java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/spi/ExchangeRateProvider.java rename to core-java-modules/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/spi/ExchangeRateProvider.java diff --git a/apache-tika/src/main/resources/logback.xml b/core-java-modules/java-spi/exchange-rate-api/src/main/resources/logback.xml similarity index 100% rename from apache-tika/src/main/resources/logback.xml rename to core-java-modules/java-spi/exchange-rate-api/src/main/resources/logback.xml diff --git a/java-spi/exchange-rate-app/pom.xml b/core-java-modules/java-spi/exchange-rate-app/pom.xml similarity index 100% rename from java-spi/exchange-rate-app/pom.xml rename to core-java-modules/java-spi/exchange-rate-app/pom.xml diff --git a/java-spi/exchange-rate-app/src/main/java/com/baeldung/rate/app/MainApp.java b/core-java-modules/java-spi/exchange-rate-app/src/main/java/com/baeldung/rate/app/MainApp.java similarity index 100% rename from java-spi/exchange-rate-app/src/main/java/com/baeldung/rate/app/MainApp.java rename to core-java-modules/java-spi/exchange-rate-app/src/main/java/com/baeldung/rate/app/MainApp.java diff --git a/asciidoctor/src/main/resources/logback.xml b/core-java-modules/java-spi/exchange-rate-app/src/main/resources/logback.xml similarity index 100% rename from asciidoctor/src/main/resources/logback.xml rename to core-java-modules/java-spi/exchange-rate-app/src/main/resources/logback.xml diff --git a/java-spi/exchange-rate-impl/pom.xml b/core-java-modules/java-spi/exchange-rate-impl/pom.xml similarity index 100% rename from java-spi/exchange-rate-impl/pom.xml rename to core-java-modules/java-spi/exchange-rate-impl/pom.xml diff --git a/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooFinanceExchangeRateProvider.java b/core-java-modules/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooFinanceExchangeRateProvider.java similarity index 100% rename from java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooFinanceExchangeRateProvider.java rename to core-java-modules/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooFinanceExchangeRateProvider.java diff --git a/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java b/core-java-modules/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java similarity index 100% rename from java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java rename to core-java-modules/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java diff --git a/java-spi/exchange-rate-impl/src/main/resources/META-INF/services/com.baeldung.rate.spi.ExchangeRateProvider b/core-java-modules/java-spi/exchange-rate-impl/src/main/resources/META-INF/services/com.baeldung.rate.spi.ExchangeRateProvider similarity index 100% rename from java-spi/exchange-rate-impl/src/main/resources/META-INF/services/com.baeldung.rate.spi.ExchangeRateProvider rename to core-java-modules/java-spi/exchange-rate-impl/src/main/resources/META-INF/services/com.baeldung.rate.spi.ExchangeRateProvider diff --git a/asm/src/main/resources/logback.xml b/core-java-modules/java-spi/exchange-rate-impl/src/main/resources/logback.xml similarity index 100% rename from asm/src/main/resources/logback.xml rename to core-java-modules/java-spi/exchange-rate-impl/src/main/resources/logback.xml diff --git a/java-spi/pom.xml b/core-java-modules/java-spi/pom.xml similarity index 79% rename from java-spi/pom.xml rename to core-java-modules/java-spi/pom.xml index fac6409b9f..48538f03b5 100644 --- a/java-spi/pom.xml +++ b/core-java-modules/java-spi/pom.xml @@ -8,9 +8,9 @@ pom - com.baeldung - parent-modules - 1.0.0-SNAPSHOT + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT diff --git a/java-websocket/README.md b/core-java-modules/java-websocket/README.md similarity index 100% rename from java-websocket/README.md rename to core-java-modules/java-websocket/README.md diff --git a/java-websocket/pom.xml b/core-java-modules/java-websocket/pom.xml similarity index 87% rename from java-websocket/pom.xml rename to core-java-modules/java-websocket/pom.xml index fd97fd9db3..8d8e57b765 100644 --- a/java-websocket/pom.xml +++ b/core-java-modules/java-websocket/pom.xml @@ -8,9 +8,9 @@ war - com.baeldung - parent-modules - 1.0.0-SNAPSHOT + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT diff --git a/java-websocket/src/main/java/com/baeldung/model/Message.java b/core-java-modules/java-websocket/src/main/java/com/baeldung/model/Message.java similarity index 100% rename from java-websocket/src/main/java/com/baeldung/model/Message.java rename to core-java-modules/java-websocket/src/main/java/com/baeldung/model/Message.java diff --git a/java-websocket/src/main/java/com/baeldung/websocket/ChatEndpoint.java b/core-java-modules/java-websocket/src/main/java/com/baeldung/websocket/ChatEndpoint.java similarity index 100% rename from java-websocket/src/main/java/com/baeldung/websocket/ChatEndpoint.java rename to core-java-modules/java-websocket/src/main/java/com/baeldung/websocket/ChatEndpoint.java diff --git a/java-websocket/src/main/java/com/baeldung/websocket/MessageDecoder.java b/core-java-modules/java-websocket/src/main/java/com/baeldung/websocket/MessageDecoder.java similarity index 100% rename from java-websocket/src/main/java/com/baeldung/websocket/MessageDecoder.java rename to core-java-modules/java-websocket/src/main/java/com/baeldung/websocket/MessageDecoder.java diff --git a/java-websocket/src/main/java/com/baeldung/websocket/MessageEncoder.java b/core-java-modules/java-websocket/src/main/java/com/baeldung/websocket/MessageEncoder.java similarity index 100% rename from java-websocket/src/main/java/com/baeldung/websocket/MessageEncoder.java rename to core-java-modules/java-websocket/src/main/java/com/baeldung/websocket/MessageEncoder.java diff --git a/java-rmi/src/main/resources/logback.xml b/core-java-modules/java-websocket/src/main/resources/logback.xml similarity index 100% rename from java-rmi/src/main/resources/logback.xml rename to core-java-modules/java-websocket/src/main/resources/logback.xml diff --git a/java-websocket/src/main/webapp/WEB-INF/beans.xml b/core-java-modules/java-websocket/src/main/webapp/WEB-INF/beans.xml similarity index 100% rename from java-websocket/src/main/webapp/WEB-INF/beans.xml rename to core-java-modules/java-websocket/src/main/webapp/WEB-INF/beans.xml diff --git a/java-websocket/src/main/webapp/WEB-INF/web.xml b/core-java-modules/java-websocket/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from java-websocket/src/main/webapp/WEB-INF/web.xml rename to core-java-modules/java-websocket/src/main/webapp/WEB-INF/web.xml diff --git a/java-websocket/src/main/webapp/index.html b/core-java-modules/java-websocket/src/main/webapp/index.html similarity index 100% rename from java-websocket/src/main/webapp/index.html rename to core-java-modules/java-websocket/src/main/webapp/index.html diff --git a/java-websocket/src/main/webapp/style.css b/core-java-modules/java-websocket/src/main/webapp/style.css similarity index 100% rename from java-websocket/src/main/webapp/style.css rename to core-java-modules/java-websocket/src/main/webapp/style.css diff --git a/java-websocket/src/main/webapp/websocket.js b/core-java-modules/java-websocket/src/main/webapp/websocket.js similarity index 100% rename from java-websocket/src/main/webapp/websocket.js rename to core-java-modules/java-websocket/src/main/webapp/websocket.js diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index d20a1650b9..7b26afbfd5 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java + parent-modules + 1.0.0-SNAPSHOT + .. @@ -65,7 +65,6 @@ core-java-streams-5 core-java-streams-collect core-java-streams-maps - core-java-string-algorithms-3 core-java-string-operations-4 @@ -155,6 +154,7 @@ core-java-lang-syntax core-java-lang-syntax-2 core-java-locale + core-java-loops core-java-networking core-java-networking-2 core-java-networking-4 @@ -184,6 +184,8 @@ core-java-streams-3 core-java-string-algorithms core-java-string-algorithms-2 + core-java-string-algorithms-3 + core-java-string-algorithms-4 core-java-string-apis core-java-swing @@ -208,6 +210,9 @@ core-java-datetime-conversion core-java-httpclient java-native + java-rmi + java-spi + java-websocket diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml index 8097d4fefa..115ba7565c 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -33,7 +33,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${maven.compiler.source} ${maven.compiler.target} @@ -43,7 +42,6 @@ - 3.10.0 6.53.0 11 11 diff --git a/di-modules/dagger/pom.xml b/di-modules/dagger/pom.xml index 59811c7c86..b751253d4a 100644 --- a/di-modules/dagger/pom.xml +++ b/di-modules/dagger/pom.xml @@ -27,7 +27,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} diff --git a/docker-modules/docker-containers/pom.xml b/docker-modules/docker-containers/pom.xml index 79bf0aee72..f8b903c87d 100644 --- a/docker-modules/docker-containers/pom.xml +++ b/docker-modules/docker-containers/pom.xml @@ -27,6 +27,7 @@ io.projectreactor reactor-test + ${reactor.version} test @@ -45,7 +46,7 @@ com.google.cloud.tools jib-maven-plugin - 2.7.1 + ${jib-maven-plugin.version} docker-demo-jib @@ -55,4 +56,10 @@ + + 3.6.0 + 2.7.1 + + + \ No newline at end of file diff --git a/jib/README.md b/docker-modules/jib/README.md similarity index 100% rename from jib/README.md rename to docker-modules/jib/README.md diff --git a/jib/pom.xml b/docker-modules/jib/pom.xml similarity index 96% rename from jib/pom.xml rename to docker-modules/jib/pom.xml index 2bdaa258f5..451f855481 100644 --- a/jib/pom.xml +++ b/docker-modules/jib/pom.xml @@ -10,7 +10,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 diff --git a/jib/src/main/java/com/baeldung/Application.java b/docker-modules/jib/src/main/java/com/baeldung/Application.java similarity index 100% rename from jib/src/main/java/com/baeldung/Application.java rename to docker-modules/jib/src/main/java/com/baeldung/Application.java diff --git a/jib/src/main/java/com/baeldung/Greeting.java b/docker-modules/jib/src/main/java/com/baeldung/Greeting.java similarity index 100% rename from jib/src/main/java/com/baeldung/Greeting.java rename to docker-modules/jib/src/main/java/com/baeldung/Greeting.java diff --git a/jib/src/main/java/com/baeldung/GreetingController.java b/docker-modules/jib/src/main/java/com/baeldung/GreetingController.java similarity index 100% rename from jib/src/main/java/com/baeldung/GreetingController.java rename to docker-modules/jib/src/main/java/com/baeldung/GreetingController.java diff --git a/kaniko/README.md b/docker-modules/kaniko/README.md similarity index 100% rename from kaniko/README.md rename to docker-modules/kaniko/README.md diff --git a/kaniko/dockerfile b/docker-modules/kaniko/dockerfile similarity index 100% rename from kaniko/dockerfile rename to docker-modules/kaniko/dockerfile diff --git a/kaniko/pod.yaml b/docker-modules/kaniko/pod.yaml similarity index 100% rename from kaniko/pod.yaml rename to docker-modules/kaniko/pod.yaml diff --git a/kaniko/volume-claim.yaml b/docker-modules/kaniko/volume-claim.yaml similarity index 100% rename from kaniko/volume-claim.yaml rename to docker-modules/kaniko/volume-claim.yaml diff --git a/kaniko/volume.yaml b/docker-modules/kaniko/volume.yaml similarity index 100% rename from kaniko/volume.yaml rename to docker-modules/kaniko/volume.yaml diff --git a/docker-modules/pom.xml b/docker-modules/pom.xml index 4eeab746eb..bf35ef23ab 100644 --- a/docker-modules/pom.xml +++ b/docker-modules/pom.xml @@ -22,6 +22,8 @@ docker-spring-boot docker-spring-boot-postgres docker-java-jar + jib + \ No newline at end of file diff --git a/guava-modules/pom.xml b/guava-modules/pom.xml index d5b01d3402..aa5a383663 100644 --- a/guava-modules/pom.xml +++ b/guava-modules/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java + parent-modules + 1.0.0-SNAPSHOT diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/EmptyObject.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/EmptyObject.java new file mode 100644 index 0000000000..fa62e1c42c --- /dev/null +++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/EmptyObject.java @@ -0,0 +1,5 @@ +package com.baeldung.exceptions; + +public class EmptyObject { + +} diff --git a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java index 026fd6719f..c680aec703 100644 --- a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java +++ b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java @@ -2,13 +2,15 @@ package com.baeldung.mappingexception; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.notNullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; +import com.baeldung.exceptions.EmptyObject; +import com.baeldung.exceptions.Person; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.SerializationFeature; import org.junit.Test; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; @@ -73,4 +75,18 @@ public class JacksonMappingExceptionUnitTest { assertEquals(Arrays.asList("Amsterdam", "Tamassint"), country.getCities()); } + @Test + public void givenEmptyBean_whenSerializing_thenCorrect() throws JsonProcessingException { + // Create an ObjectMapper + ObjectMapper objectMapper = new ObjectMapper(); + // Disable fail_on_empty_beans during serialization + objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + // Create an empty object + EmptyObject emptyObject = new EmptyObject(); + // Serialize the empty object + String json = objectMapper.writeValueAsString(emptyObject); + // Verify that serialization is successful + assertEquals("{}", json); + } + } diff --git a/jackson-modules/pom.xml b/jackson-modules/pom.xml index 196d0997b5..58c58164e8 100644 --- a/jackson-modules/pom.xml +++ b/jackson-modules/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java + parent-modules + 1.0.0-SNAPSHOT diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml index daa6504709..900c80a5e7 100644 --- a/jackson-simple/pom.xml +++ b/jackson-simple/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java + parent-modules + 1.0.0-SNAPSHOT diff --git a/java-blockchain/pom.xml b/java-blockchain/pom.xml index d45d2bf573..422867176f 100644 --- a/java-blockchain/pom.xml +++ b/java-blockchain/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java + parent-modules + 1.0.0-SNAPSHOT diff --git a/java-jdi/pom.xml b/java-jdi/pom.xml index e7b2326e21..22d7743998 100644 --- a/java-jdi/pom.xml +++ b/java-jdi/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java + parent-modules + 1.0.0-SNAPSHOT diff --git a/jetbrains/pom.xml b/jetbrains/pom.xml index ec46dc54f0..78d8b36b77 100644 --- a/jetbrains/pom.xml +++ b/jetbrains/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java + parent-modules + 1.0.0-SNAPSHOT diff --git a/jhipster-6/bookstore-monolith/pom.xml b/jhipster-6/bookstore-monolith/pom.xml index 0db1f46b1e..2ef093fadb 100644 --- a/jhipster-6/bookstore-monolith/pom.xml +++ b/jhipster-6/bookstore-monolith/pom.xml @@ -1162,7 +1162,7 @@ 3.1.0 - 3.11.0 + 3.12.1 2.10 3.0.0-M1 2.2.1 diff --git a/jhipster-modules/README.md b/jhipster-modules/README.md index 11c3d5397f..2aae8a5697 100644 --- a/jhipster-modules/README.md +++ b/jhipster-modules/README.md @@ -1,7 +1,5 @@ ## JHipster -This module contains articles about JHipster. - -### Relevant articles: - +This module contains articles about JHipster. +Relevant articles are listed in the nested module folders. diff --git a/jhipster-modules/jhipster-microservice/car-app/pom.xml b/jhipster-modules/jhipster-microservice/car-app/pom.xml index f345688939..069a1f6848 100644 --- a/jhipster-modules/jhipster-microservice/car-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/car-app/pom.xml @@ -23,13 +23,13 @@ 0.4.13 1.2 5.2.8.Final - 2.6.0 + 5.1.0 0.7.9 1.8 3.21.0-GA 1.0.0 1.1.0 - 0.7.0 + 0.12.3 1.0.0 3.6 2.0.0 @@ -216,7 +216,7 @@ io.jsonwebtoken - jjwt + jjwt-api ${jjwt.version} diff --git a/jhipster-modules/jhipster-microservice/car-app/src/main/java/com/car/app/security/jwt/TokenProvider.java b/jhipster-modules/jhipster-microservice/car-app/src/main/java/com/car/app/security/jwt/TokenProvider.java index 3908bfa8f3..028f34e3f0 100644 --- a/jhipster-modules/jhipster-microservice/car-app/src/main/java/com/car/app/security/jwt/TokenProvider.java +++ b/jhipster-modules/jhipster-microservice/car-app/src/main/java/com/car/app/security/jwt/TokenProvider.java @@ -70,7 +70,7 @@ public class TokenProvider { public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() - .setSigningKey(secretKey) + .setSigningKey(secretKey).build() .parseClaimsJws(token) .getBody(); @@ -86,7 +86,7 @@ public class TokenProvider { public boolean validateToken(String authToken) { try { - Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken); + Jwts.parser().setSigningKey(secretKey).build().parseClaimsJws(authToken); return true; } catch (SignatureException e) { log.info("Invalid JWT signature."); diff --git a/jhipster-modules/jhipster-microservice/dealer-app/pom.xml b/jhipster-modules/jhipster-microservice/dealer-app/pom.xml index 056bd60f33..43f9b046c7 100644 --- a/jhipster-modules/jhipster-microservice/dealer-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/dealer-app/pom.xml @@ -23,12 +23,12 @@ 0.4.13 1.2 5.2.8.Final - 2.6.0 + 5.1.0 0.7.9 3.21.0-GA 1.0.0 1.1.0 - 0.7.0 + 0.12.3 1.0.0 3.6 2.0.0 @@ -215,7 +215,7 @@ io.jsonwebtoken - jjwt + jjwt-api ${jjwt.version} diff --git a/jhipster-modules/jhipster-microservice/dealer-app/src/main/java/com/dealer/app/security/jwt/TokenProvider.java b/jhipster-modules/jhipster-microservice/dealer-app/src/main/java/com/dealer/app/security/jwt/TokenProvider.java index 47a5bf75af..38cee99e01 100644 --- a/jhipster-modules/jhipster-microservice/dealer-app/src/main/java/com/dealer/app/security/jwt/TokenProvider.java +++ b/jhipster-modules/jhipster-microservice/dealer-app/src/main/java/com/dealer/app/security/jwt/TokenProvider.java @@ -70,7 +70,7 @@ public class TokenProvider { public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() - .setSigningKey(secretKey) + .setSigningKey(secretKey).build() .parseClaimsJws(token) .getBody(); @@ -86,7 +86,7 @@ public class TokenProvider { public boolean validateToken(String authToken) { try { - Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken); + Jwts.parser().setSigningKey(secretKey).build().parseClaimsJws(authToken); return true; } catch (SignatureException e) { log.info("Invalid JWT signature."); diff --git a/jhipster-modules/jhipster-microservice/gateway-app/pom.xml b/jhipster-modules/jhipster-microservice/gateway-app/pom.xml index b90f22f009..90d703b8c7 100644 --- a/jhipster-modules/jhipster-microservice/gateway-app/pom.xml +++ b/jhipster-modules/jhipster-microservice/gateway-app/pom.xml @@ -26,12 +26,12 @@ 1.3 1.2 5.2.8.Final - 2.6.0 + 5.1.0 0.7.9 3.21.0-GA 1.0.0 1.1.0 - 0.7.0 + 0.12.3 1.0.0 3.6 2.0.0 @@ -243,7 +243,7 @@ io.jsonwebtoken - jjwt + jjwt-api ${jjwt.version} diff --git a/jhipster-modules/jhipster-microservice/gateway-app/src/main/java/com/gateway/security/jwt/TokenProvider.java b/jhipster-modules/jhipster-microservice/gateway-app/src/main/java/com/gateway/security/jwt/TokenProvider.java index 5ffb55f33e..14d343c0d7 100644 --- a/jhipster-modules/jhipster-microservice/gateway-app/src/main/java/com/gateway/security/jwt/TokenProvider.java +++ b/jhipster-modules/jhipster-microservice/gateway-app/src/main/java/com/gateway/security/jwt/TokenProvider.java @@ -70,7 +70,7 @@ public class TokenProvider { public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() - .setSigningKey(secretKey) + .setSigningKey(secretKey).build() .parseClaimsJws(token) .getBody(); @@ -86,7 +86,7 @@ public class TokenProvider { public boolean validateToken(String authToken) { try { - Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken); + Jwts.parser().setSigningKey(secretKey).build().parseClaimsJws(authToken); return true; } catch (SignatureException e) { log.info("Invalid JWT signature."); diff --git a/jhipster-modules/jhipster-monolithic/pom.xml b/jhipster-modules/jhipster-monolithic/pom.xml index fbcee8f1ff..f1ee479756 100644 --- a/jhipster-modules/jhipster-monolithic/pom.xml +++ b/jhipster-modules/jhipster-monolithic/pom.xml @@ -122,7 +122,7 @@ io.jsonwebtoken - jjwt + jjwt-api ${jjwt.version} @@ -892,12 +892,12 @@ 2.2.1 2.2.3 5.2.8.Final - 2.6.0 + 5.1.0 0.7.9 3.21.0-GA 1.0.0 1.1.0 - 0.7.0 + 0.12.3 1.1.3 3.6 2.0.0 diff --git a/jhipster-modules/jhipster-monolithic/src/main/java/com/baeldung/security/jwt/TokenProvider.java b/jhipster-modules/jhipster-monolithic/src/main/java/com/baeldung/security/jwt/TokenProvider.java index 3ba4d7c793..095663065b 100644 --- a/jhipster-modules/jhipster-monolithic/src/main/java/com/baeldung/security/jwt/TokenProvider.java +++ b/jhipster-modules/jhipster-monolithic/src/main/java/com/baeldung/security/jwt/TokenProvider.java @@ -70,7 +70,7 @@ public class TokenProvider { public Authentication getAuthentication(String token) { Claims claims = Jwts.parser() - .setSigningKey(secretKey) + .setSigningKey(secretKey).build() .parseClaimsJws(token) .getBody(); @@ -86,7 +86,7 @@ public class TokenProvider { public boolean validateToken(String authToken) { try { - Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken); + Jwts.parser().setSigningKey(secretKey).build().parseClaimsJws(authToken); return true; } catch (SignatureException e) { log.info("Invalid JWT signature."); diff --git a/jmh/README.md b/jmh/README.md index 3cfe847a3c..2e249c779c 100644 --- a/jmh/README.md +++ b/jmh/README.md @@ -7,3 +7,4 @@ This module contains articles about the Java Microbenchmark Harness (JMH). - [Microbenchmarking with Java](https://www.baeldung.com/java-microbenchmark-harness) - [A Guide to False Sharing and @Contended](https://www.baeldung.com/java-false-sharing-contended) - [Performance Comparison of boolean[] vs BitSet](https://www.baeldung.com/java-boolean-array-bitset-performance) +- [How to Warm Up the JVM](https://www.baeldung.com/java-jvm-warmup) diff --git a/jmh/pom.xml b/jmh/pom.xml index e8a88bf301..d6a158b273 100644 --- a/jmh/pom.xml +++ b/jmh/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java + parent-modules + 1.0.0-SNAPSHOT @@ -30,6 +29,11 @@ jol-core ${jol-core.version} + + com.google.guava + guava + ${guava.version} + diff --git a/libraries/src/main/java/com/baeldung/jmh/BenchMark.java b/jmh/src/main/java/com/baeldung/jmh/BenchMark.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jmh/BenchMark.java rename to jmh/src/main/java/com/baeldung/jmh/BenchMark.java diff --git a/libraries/src/main/java/com/baeldung/jmh/JmhDemo.java b/jmh/src/main/java/com/baeldung/jmh/JmhDemo.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jmh/JmhDemo.java rename to jmh/src/main/java/com/baeldung/jmh/JmhDemo.java diff --git a/libraries/src/main/java/com/baeldung/jmh/warmup/MainApplication.java b/jmh/src/main/java/com/baeldung/jmh/warmup/MainApplication.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jmh/warmup/MainApplication.java rename to jmh/src/main/java/com/baeldung/jmh/warmup/MainApplication.java diff --git a/libraries/src/main/java/com/baeldung/jmh/warmup/ManualClassLoader.java b/jmh/src/main/java/com/baeldung/jmh/warmup/ManualClassLoader.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jmh/warmup/ManualClassLoader.java rename to jmh/src/main/java/com/baeldung/jmh/warmup/ManualClassLoader.java diff --git a/libraries/src/main/java/com/baeldung/jmh/warmup/dummy/Dummy.java b/jmh/src/main/java/com/baeldung/jmh/warmup/dummy/Dummy.java similarity index 100% rename from libraries/src/main/java/com/baeldung/jmh/warmup/dummy/Dummy.java rename to jmh/src/main/java/com/baeldung/jmh/warmup/dummy/Dummy.java diff --git a/json-modules/gson-2/README.md b/json-modules/gson-2/README.md index 3deb61f25d..912f8b0a20 100644 --- a/json-modules/gson-2/README.md +++ b/json-modules/gson-2/README.md @@ -5,4 +5,4 @@ This module contains articles about Gson ### Relevant Articles: - [Solving Gson Parsing Errors](https://www.baeldung.com/gson-parsing-errors) - [Difference between Gson @Expose and @SerializedName](https://www.baeldung.com/gson-expose-vs-serializedname) - +- [Resolving Gson’s “Multiple JSON Fields†Exception](https://www.baeldung.com/java-gson-multiple-json-fields-exception) diff --git a/json-modules/json-conversion/src/test/java/com/baeldung/bytearraytojsonandviceversa/ByteArrayToJsonAndViceVersaUnitTest.java b/json-modules/json-conversion/src/test/java/com/baeldung/bytearraytojsonandviceversa/ByteArrayToJsonAndViceVersaUnitTest.java new file mode 100644 index 0000000000..5e33a645b2 --- /dev/null +++ b/json-modules/json-conversion/src/test/java/com/baeldung/bytearraytojsonandviceversa/ByteArrayToJsonAndViceVersaUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.bytearraytojsonandviceversa; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class ByteArrayToJsonAndViceVersaUnitTest { + + byte[] byteArray = {34, 123, 92, 34, 110, 97, 109, 101, 92, 34, 58, 92, 34, 65, 108, 105, 99, 101, 92, 34, 44, 92, 34, 97, 103, 101, 92, 34, 58, 50, 53, 44, 92, 34, 105, 115, 83, 116, 117, 100, 101, 110, 116, 92, 34, 58, 116, 114, 117, 101, 44, 92, 34, 104, 111, 98, 98, 105, 101, 115, 92, 34, 58, 91, 92, 34, 114, 101, 97, 100, 105, 110, 103, 92, 34, 44, 92, 34, 112, 97, 105, 110, 116, 105, 110, 103, 92, 34, 93, 44, 92, 34, 97, 100, 100, 114, 101, 115, 115, 92, 34, 58, 123, 92, 34, 99, 105, 116, 121, 92, 34, 58, 92, 34, 83, 109, 97, 108, 108, 118, 105, 108, 108, 101, 92, 34, 44, 92, 34, 122, 105, 112, 99, 111, 100, 101, 92, 34, 58, 92, 34, 49, 50, 51, 52, 53, 92, 34, 125, 125, 34}; + String jsonString = "{\"name\":\"Alice\",\"age\":25,\"isStudent\":true,\"hobbies\":[\"reading\",\"painting\"],\"address\":{\"city\":\"Smallville\",\"zipcode\":\"12345\"}}"; + + @Test + void givenByteArray_whenConvertingToJsonUsingJackson_thenJsonString() throws Exception { + ObjectMapper objectMapper = new ObjectMapper(); + String actualJsonString = objectMapper.readValue(byteArray, String.class); + + assertEquals(jsonString, actualJsonString); + } + + @Test + void givenByteArray_whenConvertingToJsonUsingGson_thenJsonString() { + Gson gson = new Gson(); + String jsonStringFromByteArray = new String(byteArray, StandardCharsets.UTF_8); + String actualJsonString = gson.fromJson(jsonStringFromByteArray, String.class); + + assertEquals(jsonString, actualJsonString); + } + + @Test + void givenJsonString_whenConvertingToByteArrayUsingJackson_thenByteArray() throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + byte[] actualByteArray = objectMapper.writeValueAsBytes(jsonString); + + assertEquals(Arrays.toString(byteArray), Arrays.toString(actualByteArray)); + } + + @Test + void givenJsonString_whenConvertingToByteArrayUsingGson_thenByteArray() { + Gson gson = new Gson(); + byte[] actualByteArray = gson.toJson(jsonString).getBytes(); + + assertEquals(Arrays.toString(byteArray), Arrays.toString(actualByteArray)); + } +} diff --git a/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java b/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToObjectNodeUnitTest.java similarity index 86% rename from json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java rename to json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToObjectNodeUnitTest.java index 38d097e5b8..15927b6008 100644 --- a/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToJsonObjectUnitTest.java +++ b/json-modules/json-conversion/src/test/java/com/baeldung/jsonnodetojsonobject/JsonNodeToObjectNodeUnitTest.java @@ -9,7 +9,7 @@ import org.junit.Test; import static org.junit.Assert.*; -public class JsonNodeToJsonObjectUnitTest { +public class JsonNodeToObjectNodeUnitTest { public static String jsonString = "{\"name\": \"John\", \"gender\": \"male\", \"company\": \"Baeldung\", \"isEmployee\": true, \"age\": 30}"; @@ -18,7 +18,7 @@ public class JsonNodeToJsonObjectUnitTest { ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(jsonString); - ObjectNode objectNode = objectMapper.createObjectNode().setAll((ObjectNode) jsonNode); + ObjectNode objectNode = (ObjectNode) jsonNode; assertEquals("John", objectNode.get("name").asText()); assertEquals("male", objectNode.get("gender").asText()); diff --git a/json-modules/json/README.md b/json-modules/json/README.md index d643914fc7..d6e1b400f5 100644 --- a/json-modules/json/README.md +++ b/json-modules/json/README.md @@ -12,4 +12,5 @@ This module contains articles about JSON. - [Iterating Over an Instance of org.json.JSONObject](https://www.baeldung.com/jsonobject-iteration) - [Escape JSON String in Java](https://www.baeldung.com/java-json-escaping) - [Reducing JSON Data Size](https://www.baeldung.com/json-reduce-data-size) +- [How to Convert JsonNode to ObjectNode](https://www.baeldung.com/java-jackson-jsonnode-objectnode) - More Articles: [[next -->]](../json-2) diff --git a/kubernetes-modules/jkube-demo/pom.xml b/kubernetes-modules/jkube-demo/pom.xml index 6fedc0f24a..fe75a0cc14 100644 --- a/kubernetes-modules/jkube-demo/pom.xml +++ b/kubernetes-modules/jkube-demo/pom.xml @@ -3,17 +3,19 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + com.baeldung + jkube-demo + 0.0.1-SNAPSHOT + jkube-demo + jkube-demo + com.baeldung parent-boot-2 0.0.1-SNAPSHOT ../../parent-boot-2 - com.baeldung - jkube-demo - 0.0.1-SNAPSHOT - jkube-demo - jkube-demo + org.springframework.boot diff --git a/kubernetes-modules/k8s-admission-controller/pom.xml b/kubernetes-modules/k8s-admission-controller/pom.xml index 4c41bf7ca0..6a1d695f8d 100644 --- a/kubernetes-modules/k8s-admission-controller/pom.xml +++ b/kubernetes-modules/k8s-admission-controller/pom.xml @@ -33,6 +33,7 @@ io.projectreactor reactor-test + ${reactor.version} test @@ -79,4 +80,9 @@ + + 3.6.0 + + + \ No newline at end of file diff --git a/kubernetes-modules/kubernetes-spring/pom.xml b/kubernetes-modules/kubernetes-spring/pom.xml index 64322055d1..a9c780d59d 100644 --- a/kubernetes-modules/kubernetes-spring/pom.xml +++ b/kubernetes-modules/kubernetes-spring/pom.xml @@ -33,6 +33,7 @@ io.projectreactor reactor-test + ${reactor.version} test @@ -46,4 +47,8 @@ + + + 3.6.0 + \ No newline at end of file diff --git a/lagom/greeting-impl/bin/classes/application.conf b/lagom/greeting-impl/bin/classes/application.conf deleted file mode 100644 index 3fd21ae72b..0000000000 --- a/lagom/greeting-impl/bin/classes/application.conf +++ /dev/null @@ -1 +0,0 @@ -play.modules.enabled += com.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file diff --git a/lagom/greeting-impl/src/main/resources/application.conf b/lagom/greeting-impl/src/main/resources/application.conf deleted file mode 100644 index 3fd21ae72b..0000000000 --- a/lagom/greeting-impl/src/main/resources/application.conf +++ /dev/null @@ -1 +0,0 @@ -play.modules.enabled += com.baeldung.lagom.helloworld.greeting.impl.GreetingServiceModule \ No newline at end of file diff --git a/lagom/weather-impl/src/main/resources/application.conf b/lagom/weather-impl/src/main/resources/application.conf deleted file mode 100644 index 53d2dff8f2..0000000000 --- a/lagom/weather-impl/src/main/resources/application.conf +++ /dev/null @@ -1 +0,0 @@ -play.modules.enabled += com.baeldung.lagom.helloworld.weather.impl.WeatherServiceModule \ No newline at end of file diff --git a/libraries-2/README.md b/libraries-2/README.md index 8dae12a1cf..16c04cb7ad 100644 --- a/libraries-2/README.md +++ b/libraries-2/README.md @@ -10,13 +10,9 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m ### Relevant articles - [A Guide to jBPM with Java](https://www.baeldung.com/jbpm-java) - [Guide to Classgraph Library](https://www.baeldung.com/classgraph) -- [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program) -- [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors) - [Templating with Handlebars](https://www.baeldung.com/handlebars) - [A Guide to Crawler4j](https://www.baeldung.com/crawler4j) -- [Key Value Store with Chronicle Map](https://www.baeldung.com/java-chronicle-map) -- [Guide to MapDB](https://www.baeldung.com/mapdb) - [A Guide to Apache Mesos](https://www.baeldung.com/apache-mesos) -- [JasperReports with Spring](https://www.baeldung.com/spring-jasper) +- [Guide to MapDB](https://www.baeldung.com/mapdb) - More articles [[<-- prev]](/libraries) [[next -->]](/libraries-3) diff --git a/libraries-2/pom.xml b/libraries-2/pom.xml index d9b0545d54..e472628c2b 100644 --- a/libraries-2/pom.xml +++ b/libraries-2/pom.xml @@ -13,16 +13,6 @@ - - org.mapdb - mapdb - ${mapdb.version} - - - com.pivovarit - parallel-collectors - ${parallel-collectors.version} - io.github.classgraph classgraph @@ -41,27 +31,11 @@ - - info.picocli - picocli - ${picocli.version} - org.springframework.boot spring-boot-starter ${spring-boot-starter.version} - - net.openhft - chronicle-map - ${chronicle.map.version} - - - com.sun.java - tools - - - edu.uci.ics crawler4j @@ -83,17 +57,6 @@ mesos ${mesos.library.version} - - net.sf.jasperreports - jasperreports - ${jasperreports.version} - - - commons-logging - commons-logging - - - org.hsqldb hsqldb @@ -114,6 +77,11 @@ je 18.3.12 + + org.mapdb + mapdb + ${mapdb.version} + @@ -121,10 +89,6 @@ org.apache.maven.plugins maven-surefire-plugin - ${maven-surefire-plugin.version} - - --add-exports=java.base/jdk.internal.ref=ALL-UNNAMED --add-exports=java.base/sun.nio.ch=ALL-UNNAMED --add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED - @@ -133,14 +97,10 @@ 3.0.8 4.8.153 7.20.0.Final - 4.7.0 - 3.24ea1 4.4.0 2.7.8 1.11.0 - 1.1.0 4.3.1 - 6.20.0 5.3.25 2.7.1 diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java index 6f5141b054..a286ed7ea8 100644 --- a/libraries-2/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/mapdb/CollectionsUnitTest.java @@ -1,14 +1,14 @@ package com.baeldung.mapdb; +import static junit.framework.Assert.assertEquals; + +import java.util.NavigableSet; + import org.junit.Test; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.Serializer; -import java.util.NavigableSet; - -import static junit.framework.Assert.assertEquals; - public class CollectionsUnitTest { @Test diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java index 3b7cac04fb..80d5375445 100644 --- a/libraries-2/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/mapdb/HTreeMapUnitTest.java @@ -1,12 +1,12 @@ package com.baeldung.mapdb; -import org.jetbrains.annotations.NotNull; -import org.junit.Test; -import org.mapdb.*; +import static org.junit.jupiter.api.Assertions.assertEquals; -import java.io.IOException; - -import static junit.framework.Assert.assertEquals; +import org.junit.jupiter.api.Test; +import org.mapdb.DB; +import org.mapdb.DBMaker; +import org.mapdb.HTreeMap; +import org.mapdb.Serializer; public class HTreeMapUnitTest { diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java index 952efd0639..89c40fe625 100644 --- a/libraries-2/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/mapdb/HelloBaeldungUnitTest.java @@ -1,25 +1,25 @@ package com.baeldung.mapdb; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.HTreeMap; -import java.util.concurrent.ConcurrentMap; - -import static junit.framework.Assert.assertEquals; - public class HelloBaeldungUnitTest { @Test public void givenInMemoryDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() { - DB db = DBMaker.memoryDB().make(); + DB db = DBMaker.memoryDB() + .make(); String welcomeMessageKey = "Welcome Message"; String welcomeMessageString = "Hello Baeldung!"; - HTreeMap myMap = db.hashMap("myMap").createOrOpen(); + HTreeMap myMap = db.hashMap("myMap") + .createOrOpen(); myMap.put(welcomeMessageKey, welcomeMessageString); String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey); @@ -32,12 +32,14 @@ public class HelloBaeldungUnitTest { @Test public void givenInFileDBInstantiateCorrectly_whenDataSavedAndRetrieved_checkRetrievalCorrect() { - DB db = DBMaker.fileDB("file.db").make(); + DB db = DBMaker.fileDB("file.db") + .make(); String welcomeMessageKey = "Welcome Message"; String welcomeMessageString = "Hello Baeldung!"; - HTreeMap myMap = db.hashMap("myMap").createOrOpen(); + HTreeMap myMap = db.hashMap("myMap") + .createOrOpen(); myMap.put(welcomeMessageKey, welcomeMessageString); String welcomeMessageFromDB = (String) myMap.get(welcomeMessageKey); diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java index 9c53f9c792..c761f877ab 100644 --- a/libraries-2/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/mapdb/InMemoryModesUnitTest.java @@ -1,13 +1,13 @@ package com.baeldung.mapdb; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; import org.mapdb.DB; import org.mapdb.DBMaker; import org.mapdb.HTreeMap; import org.mapdb.Serializer; -import static junit.framework.Assert.assertEquals; - public class InMemoryModesUnitTest { @Test diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java index 83ba917393..6b6b3942d2 100644 --- a/libraries-2/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/mapdb/SortedTableMapUnitTest.java @@ -1,13 +1,13 @@ package com.baeldung.mapdb; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; import org.mapdb.Serializer; import org.mapdb.SortedTableMap; import org.mapdb.volume.MappedFileVol; import org.mapdb.volume.Volume; -import static junit.framework.Assert.assertEquals; - public class SortedTableMapUnitTest { private static final String VOLUME_LOCATION = "sortedTableMapVol.db"; diff --git a/libraries-2/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java b/libraries-2/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java index 4de9db10e8..5a053b4422 100644 --- a/libraries-2/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java +++ b/libraries-2/src/test/java/com/baeldung/mapdb/TransactionsUnitTest.java @@ -1,13 +1,13 @@ package com.baeldung.mapdb; -import org.junit.Test; -import org.mapdb.DB; -import org.mapdb.DBMaker; -import org.mapdb.Serializer; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.NavigableSet; -import static junit.framework.Assert.assertEquals; +import org.junit.jupiter.api.Test; +import org.mapdb.DB; +import org.mapdb.DBMaker; +import org.mapdb.Serializer; public class TransactionsUnitTest { diff --git a/libraries-3/README.md b/libraries-3/README.md index 99b1b60a0a..3416805ad1 100644 --- a/libraries-3/README.md +++ b/libraries-3/README.md @@ -8,12 +8,7 @@ The code examples related to different libraries are each in their own module. Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases. ### Relevant Articles: -- [Parsing Command-Line Parameters with JCommander](https://www.baeldung.com/jcommander-parsing-command-line-parameters) -- [Guide to the Cactoos Library](https://www.baeldung.com/java-cactoos) -- [Parsing Command-Line Parameters with Airline](https://www.baeldung.com/java-airline) -- [Introduction to cache2k](https://www.baeldung.com/java-cache2k) - [Introduction to the jcabi-aspects AOP Annotations Library](https://www.baeldung.com/java-jcabi-aspects) -- [Introduction to Takes](https://www.baeldung.com/java-takes) - [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) - [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro) - [Intro to Structurizr](https://www.baeldung.com/structurizr) diff --git a/libraries-3/pom.xml b/libraries-3/pom.xml index 9923e46267..ae8ebb43f3 100644 --- a/libraries-3/pom.xml +++ b/libraries-3/pom.xml @@ -13,32 +13,11 @@ - - com.beust - jcommander - ${jcommander.version} - org.projectlombok lombok ${lombok.version} - - com.github.rvesse - airline - ${airline.version} - - - org.cactoos - cactoos - ${cactoos.version} - - - org.cache2k - cache2k-base-bom - ${cache2k.version} - pom - com.jcabi jcabi-aspects @@ -50,21 +29,6 @@ ${aspectjrt.version} runtime - - org.takes - takes - ${takes.version} - - - org.apache.httpcomponents - httpcore - ${httpcore.version} - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - org.apache.velocity velocity-engine-core @@ -125,7 +89,7 @@ javax.annotation javax.annotation-api - 1.3.2 + ${javax.annotation-api.version} @@ -159,10 +123,6 @@ org.apache.maven.plugins maven-compiler-plugin - - 11 - 11 - @@ -173,59 +133,13 @@ - - - reload - - - - src/main/resources - true - - - src/main/webapp - true - - - - - org.codehaus.mojo - exec-maven-plugin - - - start-server - pre-integration-test - - java - - - - - com.baeldung.takes.TakesApp - false - - --port=${port} - - - - - - - - 1.78 - 0.43 - 2.7.2 - 1.2.3.Final 0.22.6 1.9.20.1 0.14.1 1.9.20.1 1.9.20.1 - 1.19 - 4.4.13 - 4.5.12 2.2 0.3.0 2.8 @@ -233,6 +147,7 @@ 1.0.0 2.5.6 0.9.6 + 1.3.2 \ No newline at end of file diff --git a/libraries-4/README.md b/libraries-4/README.md index 0dee9f1c1e..03ea3d7a77 100644 --- a/libraries-4/README.md +++ b/libraries-4/README.md @@ -8,13 +8,7 @@ The code examples related to different libraries are each in their own module. Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases. ### Relevant articles -- [Quick Guide to RSS with Rome](https://www.baeldung.com/rome-rss) -- [Introduction to PCollections](https://www.baeldung.com/java-pcollections) -- [Introduction to Eclipse Collections](https://www.baeldung.com/eclipse-collections) -- [DistinctBy in the Java Stream API](https://www.baeldung.com/java-streams-distinct-by) - [Introduction to NoException](https://www.baeldung.com/no-exception) -- [Spring Yarg Integration](https://www.baeldung.com/spring-yarg) -- [Delete a Directory Recursively in Java](https://www.baeldung.com/java-delete-directory) - [Guide to JDeferred](https://www.baeldung.com/jdeferred) - [Introduction to MBassador](https://www.baeldung.com/mbassador) - [Using Pairs in Java](https://www.baeldung.com/java-pairs) diff --git a/libraries-4/pom.xml b/libraries-4/pom.xml index 3949d50875..165f017d89 100644 --- a/libraries-4/pom.xml +++ b/libraries-4/pom.xml @@ -17,22 +17,6 @@ jdeferred-core ${jdeferred.version} - - org.eclipse.collections - eclipse-collections - ${eclipse-collections.version} - - - com.haulmont.yarg - yarg - ${yarg.version} - - - org.olap4j - olap4j - - - org.olap4j olap4j @@ -48,11 +32,6 @@ noexception ${noexception.version} - - rome - rome - ${rome.version} - org.springframework spring-web @@ -68,16 +47,6 @@ servlet-api ${javax.servlet.version} - - io.vavr - vavr - ${vavr.version} - - - org.pcollections - pcollections - ${pcollections.version} - org.awaitility awaitility @@ -119,22 +88,27 @@ jackson-annotations ${jackson-annotations.version} + + io.vavr + vavr + ${vavr.version} + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + 2.14.2 2.14.2 1.2.6 - 8.2.0 1.1.0 - 2.0.12 1.3.1 - 1.0 4.3.8.RELEASE 2.5 3.2.0-m7 - 0.9.0 - 2.1.2 3.0.0 0.6.5 3.0.0 @@ -142,6 +116,7 @@ 1.2.0 19 10.3.0 + 0.9.0 \ No newline at end of file diff --git a/libraries-5/README.md b/libraries-5/README.md index f1e749b293..6b61a7a43c 100644 --- a/libraries-5/README.md +++ b/libraries-5/README.md @@ -8,14 +8,8 @@ The code examples related to different libraries are each in their own module. Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases. ### Relevant articles -- [Introduction to Caffeine](https://www.baeldung.com/java-caching-caffeine) -- [Introduction to StreamEx](https://www.baeldung.com/streamex) - [A Docker Guide for Java](https://www.baeldung.com/docker-java-api) -- [Introduction to Akka Actors in Java](https://www.baeldung.com/akka-actors-java) -- [A Guide to Byte Buddy](https://www.baeldung.com/byte-buddy) - [Introduction to jOOL](https://www.baeldung.com/jool) -- [Consumer Driven Contracts with Pact](https://www.baeldung.com/pact-junit-consumer-driven-contracts) - [Introduction to Atlassian Fugue](https://www.baeldung.com/java-fugue) - [Publish and Receive Messages with Nats Java Client](https://www.baeldung.com/nats-java-client) -- [Java Concurrency Utility with JCTools](https://www.baeldung.com/java-concurrency-jc-tools) - More articles [[<-- prev]](/libraries-4) [[next -->]](/libraries-6) diff --git a/libraries-5/pom.xml b/libraries-5/pom.xml index a043b4bfa8..a15679502d 100644 --- a/libraries-5/pom.xml +++ b/libraries-5/pom.xml @@ -6,64 +6,17 @@ libraries-5 + parent-modules com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../parent-boot-2 + 1.0.0-SNAPSHOT - - org.springframework - spring-web - org.jooq jool ${jool.version} - - au.com.dius - pact-jvm-provider-junit5_2.12 - ${pact.version} - - - au.com.dius - pact-jvm-consumer-junit5_2.12 - ${pact.version} - test - - - org.springframework.boot - spring-boot-starter-web - - - - com.typesafe.akka - akka-actor_${scala.version} - ${typesafe-akka.version} - - - com.typesafe.akka - akka-testkit_${scala.version} - ${typesafe-akka.version} - test - - - one.util - streamex - ${streamex.version} - - - net.bytebuddy - byte-buddy - ${byte-buddy.version} - - - net.bytebuddy - byte-buddy-agent - ${byte-buddy.version} - com.github.docker-java @@ -84,18 +37,6 @@ - - - com.github.ben-manes.caffeine - caffeine - ${caffeine.version} - - - com.google.code.findbugs - jsr305 - ${findbugs.version} - test - io.atlassian.fugue @@ -107,45 +48,14 @@ jnats ${jnats.version} - - org.jctools - jctools-core - ${jctools.version} - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - - - org.apache.maven.plugins - maven-surefire-plugin - - - target/mypacts - - - - - - - 3.6.3 0.9.12 - 4.3.8.RELEASE 2.12 - 2.5.11 - 0.8.1 3.0.14 - 3.1.8 - 3.0.2 4.5.1 1.0 - 2.1.2 \ No newline at end of file diff --git a/libraries-6/README.md b/libraries-6/README.md index bbebcbc1e0..4be655f850 100644 --- a/libraries-6/README.md +++ b/libraries-6/README.md @@ -10,12 +10,9 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m ### Relevant articles - [Introduction to JavaPoet](https://www.baeldung.com/java-poet) - [Guide to Resilience4j](https://www.baeldung.com/resilience4j) -- [Implementing a FTP-Client in Java](https://www.baeldung.com/java-ftp-client) - [Introduction to Functional Java](https://www.baeldung.com/java-functional-library) -- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) - [Guide to Simple Binary Encoding](https://www.baeldung.com/java-sbe) - [Java-R Integration](https://www.baeldung.com/java-r-integration) - [Using libphonenumber to Validate Phone Numbers](https://www.baeldung.com/java-libphonenumber) - [Apache Commons Collections vs Google Guava](https://www.baeldung.com/apache-commons-collections-vs-guava) -- [Guide to Using ModelMapper](https://www.baeldung.com/java-modelmapper) -- More articles [[<-- prev]](/libraries-5) +- More articles [[<-- prev]](/libraries-5) [[next -->]](/libraries-7) diff --git a/libraries-6/pom.xml b/libraries-6/pom.xml index f073ca424c..e9b90fa597 100644 --- a/libraries-6/pom.xml +++ b/libraries-6/pom.xml @@ -17,11 +17,6 @@ functionaljava-java8 ${functionaljava.version} - - com.codepoetics - protonpack - ${protonpack.version} - io.github.resilience4j resilience4j-circuitbreaker @@ -47,12 +42,6 @@ javapoet ${javapoet.version} - - org.mockftpserver - MockFtpServer - ${mockftpserver.version} - test - org.apache.commons commons-lang3 @@ -68,11 +57,6 @@ guava ${guava.version} - - commons-net - commons-net - ${commons-net.version} - commons-io commons-io @@ -100,11 +84,6 @@ libphonenumber ${libphonenumber.version} - - org.modelmapper - modelmapper - ${org.modelmapper.version} - org.agrona agrona @@ -195,16 +174,12 @@ 1.10.0 - 2.7.1 4.8.1 2.1.0 - 1.15 - 3.6 3.5-beta72 3.0 1.8.1 8.12.9 - 3.2.0 1.17.1 1.6.0 1.27.0 diff --git a/libraries-7/README.md b/libraries-7/README.md new file mode 100644 index 0000000000..c56d52aa3e --- /dev/null +++ b/libraries-7/README.md @@ -0,0 +1,12 @@ +## Libraries-7 + +This module contains articles about various Java libraries. +These are small libraries that are relatively easy to use and do not require any separate module of their own. + +The code examples related to different libraries are each in their own module. + +Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases. + +### Relevant articles +- [Find Files by Extension in Specified Directory in Java](https://www.baeldung.com/java-recursive-search-directory-extension-match) +- More articles [[<-- prev]](/libraries-6) diff --git a/libraries-7/pom.xml b/libraries-7/pom.xml new file mode 100644 index 0000000000..40c4785d40 --- /dev/null +++ b/libraries-7/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + libraries-7 + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + + commons-io + commons-io + ${commons-io.version} + + + + \ No newline at end of file diff --git a/libraries-7/src/main/java/com/baeldung/findfiles/FindFileApacheUtils.java b/libraries-7/src/main/java/com/baeldung/findfiles/FindFileApacheUtils.java new file mode 100644 index 0000000000..408d2dcf36 --- /dev/null +++ b/libraries-7/src/main/java/com/baeldung/findfiles/FindFileApacheUtils.java @@ -0,0 +1,29 @@ +package com.baeldung.findfiles; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Iterator; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.filefilter.TrueFileFilter; +import org.apache.commons.io.filefilter.WildcardFileFilter; + +public class FindFileApacheUtils { + + private FindFileApacheUtils() { + } + + public static Iterator find(Path startPath, String extension) { + if (!Files.isDirectory(startPath)) { + throw new IllegalArgumentException("Provided path is not a directory: " + startPath); + } + + if (!extension.startsWith(".")) + extension = "." + extension; + + return FileUtils.iterateFiles(startPath.toFile(), WildcardFileFilter.builder() + .setWildcards("*" + extension) + .get(), TrueFileFilter.INSTANCE); + } +} diff --git a/libraries-7/src/main/java/com/baeldung/findfiles/FindFileJava2Utils.java b/libraries-7/src/main/java/com/baeldung/findfiles/FindFileJava2Utils.java new file mode 100644 index 0000000000..8982f918f5 --- /dev/null +++ b/libraries-7/src/main/java/com/baeldung/findfiles/FindFileJava2Utils.java @@ -0,0 +1,34 @@ +package com.baeldung.findfiles; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +public class FindFileJava2Utils { + + private FindFileJava2Utils() { + } + + public static List find(File startPath, String extension) { + if (!startPath.isDirectory()) { + throw new IllegalArgumentException("Provided path is not a directory: " + startPath); + } + + List matches = new ArrayList<>(); + + File[] files = startPath.listFiles(); + if (files == null) + return matches; + + MatchExtensionPredicate filter = new MatchExtensionPredicate(extension); + for (File file : files) { + if (file.isDirectory()) { + matches.addAll(find(file, extension)); + } else if (filter.test(file.toPath())) { + matches.add(file); + } + } + + return matches; + } +} diff --git a/libraries-7/src/main/java/com/baeldung/findfiles/FindFileJava7Utils.java b/libraries-7/src/main/java/com/baeldung/findfiles/FindFileJava7Utils.java new file mode 100644 index 0000000000..6d2cc4f946 --- /dev/null +++ b/libraries-7/src/main/java/com/baeldung/findfiles/FindFileJava7Utils.java @@ -0,0 +1,44 @@ +package com.baeldung.findfiles; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.List; + +public class FindFileJava7Utils { + + private FindFileJava7Utils() { + } + + public static List find(Path startPath, String extension) throws IOException { + if (!Files.isDirectory(startPath)) { + throw new IllegalArgumentException("Provided path is not a directory: " + startPath); + } + + final List matches = new ArrayList<>(); + MatchExtensionPredicate filter = new MatchExtensionPredicate(extension); + + Files.walkFileTree(startPath, new SimpleFileVisitor() { + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) { + if (filter.test(file)) { + matches.add(file); + } + + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) { + return FileVisitResult.CONTINUE; + } + }); + + return matches; + } +} diff --git a/libraries-7/src/main/java/com/baeldung/findfiles/FindFileJava8Utils.java b/libraries-7/src/main/java/com/baeldung/findfiles/FindFileJava8Utils.java new file mode 100644 index 0000000000..b265bebe7d --- /dev/null +++ b/libraries-7/src/main/java/com/baeldung/findfiles/FindFileJava8Utils.java @@ -0,0 +1,21 @@ +package com.baeldung.findfiles; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.function.Consumer; + +public class FindFileJava8Utils { + + private FindFileJava8Utils() { + } + + public static void find(Path startPath, String extension, Consumer consumer) throws IOException { + if (!Files.isDirectory(startPath)) { + throw new IllegalArgumentException("Provided path is not a directory: " + startPath); + } + + MatchExtensionPredicate filter = new MatchExtensionPredicate(extension); + Files.walkFileTree(startPath, new SimpleFileConsumerVisitor(filter, consumer)); + } +} diff --git a/libraries-7/src/main/java/com/baeldung/findfiles/MatchExtensionPredicate.java b/libraries-7/src/main/java/com/baeldung/findfiles/MatchExtensionPredicate.java new file mode 100644 index 0000000000..351cdd0590 --- /dev/null +++ b/libraries-7/src/main/java/com/baeldung/findfiles/MatchExtensionPredicate.java @@ -0,0 +1,26 @@ +package com.baeldung.findfiles; + +import java.nio.file.Path; +import java.util.function.Predicate; + +public class MatchExtensionPredicate implements Predicate { + + private final String extension; + + public MatchExtensionPredicate(String extension) { + if (!extension.startsWith(".")) + extension = "." + extension; + this.extension = extension.toLowerCase(); + } + + @Override + public boolean test(Path path) { + if (path == null) + return false; + + return path.getFileName() + .toString() + .toLowerCase() + .endsWith(extension); + } +} diff --git a/libraries-7/src/main/java/com/baeldung/findfiles/SimpleFileConsumerVisitor.java b/libraries-7/src/main/java/com/baeldung/findfiles/SimpleFileConsumerVisitor.java new file mode 100644 index 0000000000..632499d279 --- /dev/null +++ b/libraries-7/src/main/java/com/baeldung/findfiles/SimpleFileConsumerVisitor.java @@ -0,0 +1,33 @@ +package com.baeldung.findfiles; + +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.function.Consumer; +import java.util.function.Predicate; + +public class SimpleFileConsumerVisitor extends SimpleFileVisitor { + + private final Predicate filter; + private final Consumer consumer; + + public SimpleFileConsumerVisitor(MatchExtensionPredicate filter, Consumer consumer) { + this.filter = filter; + this.consumer = consumer; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) { + if (filter.test(file)) + consumer.accept(file); + + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { + return FileVisitResult.CONTINUE; + } +} diff --git a/libraries-7/src/test/java/com/baeldung/findfiles/FindFileUtilsIntegrationTest.java b/libraries-7/src/test/java/com/baeldung/findfiles/FindFileUtilsIntegrationTest.java new file mode 100644 index 0000000000..ddd7b7e155 --- /dev/null +++ b/libraries-7/src/test/java/com/baeldung/findfiles/FindFileUtilsIntegrationTest.java @@ -0,0 +1,79 @@ +package com.baeldung.findfiles; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.commons.io.FileUtils; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +public class FindFileUtilsIntegrationTest { + + private static final String TEST_EXTENSION = ".test"; + private static final String OTHER_EXTENSION = ".other"; + + private static final List TEST_FILES = new ArrayList<>(); + private static final List OTHER_FILES = new ArrayList<>(); + + private static Path TEST_DIR; + + @BeforeAll + static void setup() throws IOException { + TEST_DIR = Files.createTempDirectory(null); + + final Path nestedDir = TEST_DIR.resolve("sub-dir"); + Files.createDirectories(nestedDir); + + TEST_FILES.add(Files.createFile(TEST_DIR.resolve("a" + TEST_EXTENSION))); + OTHER_FILES.add(Files.createFile(TEST_DIR.resolve("a" + OTHER_EXTENSION))); + + TEST_FILES.add(Files.createFile(nestedDir.resolve("b" + TEST_EXTENSION))); + OTHER_FILES.add(Files.createFile(nestedDir.resolve("b" + OTHER_EXTENSION))); + } + + @AfterAll + static void cleanUp() { + FileUtils.deleteQuietly(TEST_DIR.toFile()); + } + + @Test + void whenFindFilesWithJava2_thenOnlyMatchingFilesFound() { + List matches = FindFileJava2Utils.find(TEST_DIR.toFile(), TEST_EXTENSION); + + assertEquals(TEST_FILES.size(), matches.size()); + } + + @Test + void whenFindFilesWithJava7_thenOnlyMatchingFilesFound() throws IOException { + List matches = FindFileJava7Utils.find(TEST_DIR, TEST_EXTENSION); + + assertEquals(TEST_FILES.size(), matches.size()); + } + + @Test + void whenFindFilesWithJava8_thenOnlyMatchingFilesFound() throws IOException { + final AtomicInteger matches = new AtomicInteger(0); + FindFileJava8Utils.find(TEST_DIR, TEST_EXTENSION, path -> matches.incrementAndGet()); + + assertEquals(TEST_FILES.size(), matches.get()); + } + + @Test + void whenFindFilesWithApache_thenOnlyMatchingFilesFound() { + final AtomicInteger matches = new AtomicInteger(0); + Iterator iterator = FindFileApacheUtils.find(TEST_DIR, TEST_EXTENSION); + + iterator.forEachRemaining(file -> matches.incrementAndGet()); + + assertEquals(TEST_FILES.size(), matches.get()); + } +} diff --git a/libraries-ai/README.md b/libraries-ai/README.md index 01ec9b1d68..8c211ea1a2 100644 --- a/libraries-ai/README.md +++ b/libraries-ai/README.md @@ -1,2 +1,3 @@ ## Relevant Articles - [Overview of NLP Libraries in Java](https://www.baeldung.com/java-nlp-libraries) +- [Introduction to Neuroph](https://www.baeldung.com/neuroph) diff --git a/libraries-ai/pom.xml b/libraries-ai/pom.xml index 48b26e5a31..aa2ef19b45 100644 --- a/libraries-ai/pom.xml +++ b/libraries-ai/pom.xml @@ -23,11 +23,17 @@ opennlp-tools ${opennlp-tools.version} + + org.beykery + neuroph + ${neuroph.version} + 4.5.3 2.1.1 + 2.92 \ No newline at end of file diff --git a/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java b/libraries-ai/src/main/java/neuroph/NeurophXOR.java similarity index 98% rename from libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java rename to libraries-ai/src/main/java/neuroph/NeurophXOR.java index 4cb11c3c05..63ce1c6e16 100644 --- a/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java +++ b/libraries-ai/src/main/java/neuroph/NeurophXOR.java @@ -1,4 +1,4 @@ -package com.baeldung.neuroph; +package neuroph; import org.neuroph.core.Layer; import org.neuroph.core.NeuralNetwork; diff --git a/libraries/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java b/libraries-ai/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java similarity index 94% rename from libraries/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java rename to libraries-ai/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java index ea5c09a4d8..6e6bad8142 100644 --- a/libraries/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java +++ b/libraries-ai/src/test/java/com/baeldung/neuroph/XORIntegrationTest.java @@ -1,11 +1,13 @@ package com.baeldung.neuroph; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.junit.After; import org.junit.Before; import org.junit.Test; import org.neuroph.core.NeuralNetwork; -import static org.junit.Assert.*; +import neuroph.NeurophXOR; public class XORIntegrationTest { private NeuralNetwork ann = null; diff --git a/libraries-apache-commons-2/README.md b/libraries-apache-commons-2/README.md index 180c84b31c..70a872dea4 100644 --- a/libraries-apache-commons-2/README.md +++ b/libraries-apache-commons-2/README.md @@ -5,4 +5,5 @@ This module contains articles about Apache Commons libraries. ### Relevant articles - [Extracting a Tar File in Java](https://www.baeldung.com/java-extract-tar-file) - [Convert a String with Unicode Encoding to a String of Letters](https://www.baeldung.com/java-convert-string-unicode-encoding) +- - More articles: [[<--prev]](../libraries-apache-commons) diff --git a/libraries-apache-commons-2/pom.xml b/libraries-apache-commons-2/pom.xml index ee9b51e6cc..c555b83273 100644 --- a/libraries-apache-commons-2/pom.xml +++ b/libraries-apache-commons-2/pom.xml @@ -33,6 +33,17 @@ commons-text ${apache-commons-text.version} + + commons-net + commons-net + ${commons-net.version} + + + org.mockftpserver + MockFtpServer + ${mockftpserver.version} + test + @@ -40,6 +51,8 @@ 1.10.13 2.9.0 1.10.0 + 3.6 + 2.7.1 \ No newline at end of file diff --git a/libraries-6/src/main/java/com/baeldung/ftp/FtpClient.java b/libraries-apache-commons-2/src/main/java/com/baeldung/commons/ftp/FtpClient.java similarity index 90% rename from libraries-6/src/main/java/com/baeldung/ftp/FtpClient.java rename to libraries-apache-commons-2/src/main/java/com/baeldung/commons/ftp/FtpClient.java index f885ff13b3..412f0726a7 100644 --- a/libraries-6/src/main/java/com/baeldung/ftp/FtpClient.java +++ b/libraries-apache-commons-2/src/main/java/com/baeldung/commons/ftp/FtpClient.java @@ -1,15 +1,19 @@ -package com.baeldung.ftp; +package com.baeldung.commons.ftp; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Arrays; +import java.util.Collection; +import java.util.stream.Collectors; import org.apache.commons.net.PrintCommandListener; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; -import java.io.*; -import java.util.Arrays; -import java.util.Collection; -import java.util.stream.Collectors; - class FtpClient { private final String server; diff --git a/libraries-6/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java b/libraries-apache-commons-2/src/test/java/com/baeldung/commons/ftp/FtpClientIntegrationTest.java similarity index 98% rename from libraries-6/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java rename to libraries-apache-commons-2/src/test/java/com/baeldung/commons/ftp/FtpClientIntegrationTest.java index 43da69f96d..4bbebc0ea1 100644 --- a/libraries-6/src/test/java/com/baeldung/ftp/FtpClientIntegrationTest.java +++ b/libraries-apache-commons-2/src/test/java/com/baeldung/commons/ftp/FtpClientIntegrationTest.java @@ -1,4 +1,11 @@ -package com.baeldung.ftp; +package com.baeldung.commons.ftp; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Collection; import org.junit.After; import org.junit.Before; @@ -10,13 +17,6 @@ import org.mockftpserver.fake.filesystem.FileEntry; import org.mockftpserver.fake.filesystem.FileSystem; import org.mockftpserver.fake.filesystem.UnixFakeFileSystem; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.Collection; - -import static org.assertj.core.api.Assertions.assertThat; - public class FtpClientIntegrationTest { private FakeFtpServer fakeFtpServer; diff --git a/libraries-6/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java b/libraries-apache-commons-2/src/test/java/com/baeldung/commons/ftp/JdkFtpClientIntegrationTest.java similarity index 93% rename from libraries-6/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java rename to libraries-apache-commons-2/src/test/java/com/baeldung/commons/ftp/JdkFtpClientIntegrationTest.java index ef6809b02d..905bc4906a 100644 --- a/libraries-6/src/test/java/com/baeldung/ftp/JdkFtpClientIntegrationTest.java +++ b/libraries-apache-commons-2/src/test/java/com/baeldung/commons/ftp/JdkFtpClientIntegrationTest.java @@ -1,4 +1,13 @@ -package com.baeldung.ftp; +package com.baeldung.commons.ftp; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; import org.junit.After; import org.junit.Before; @@ -10,18 +19,6 @@ import org.mockftpserver.fake.filesystem.FileEntry; import org.mockftpserver.fake.filesystem.FileSystem; import org.mockftpserver.fake.filesystem.UnixFakeFileSystem; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLConnection; -import java.nio.file.Files; -import java.util.Collection; - -import static org.assertj.core.api.Assertions.assertThat; - public class JdkFtpClientIntegrationTest { private FakeFtpServer fakeFtpServer; diff --git a/libraries-6/src/test/resources/ftp/baz.txt b/libraries-apache-commons-2/src/test/resources/ftp/baz.txt similarity index 100% rename from libraries-6/src/test/resources/ftp/baz.txt rename to libraries-apache-commons-2/src/test/resources/ftp/baz.txt diff --git a/libraries-bytecode/.gitignore b/libraries-bytecode/.gitignore new file mode 100644 index 0000000000..e594daf27a --- /dev/null +++ b/libraries-bytecode/.gitignore @@ -0,0 +1,9 @@ +*.class + +# Folders # +/gensrc +/target + +# Packaged files # +*.jar +/bin/ diff --git a/libraries-bytecode/README.md b/libraries-bytecode/README.md new file mode 100644 index 0000000000..cc30511ad1 --- /dev/null +++ b/libraries-bytecode/README.md @@ -0,0 +1,9 @@ +## Server + +This module contains articles about bytecode libraries. + +### Relevant Articles: + +- [Introduction to Javassist](https://www.baeldung.com/javassist) +- [A Guide to Byte Buddy](https://www.baeldung.com/byte-buddy) +- [A Guide to Java Bytecode Manipulation with ASM](https://www.baeldung.com/java-asm) \ No newline at end of file diff --git a/libraries-bytecode/pom.xml b/libraries-bytecode/pom.xml new file mode 100644 index 0000000000..f21911d77e --- /dev/null +++ b/libraries-bytecode/pom.xml @@ -0,0 +1,85 @@ + + + 4.0.0 + libraries-bytecode + 0.0.1-SNAPSHOT + libraries-bytecode + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.javassist + javassist + ${javaassist.version} + + + net.bytebuddy + byte-buddy + ${byte-buddy.version} + + + net.bytebuddy + byte-buddy-agent + ${byte-buddy.version} + + + org.ow2.asm + asm + ${asm.version} + + + org.ow2.asm + asm-util + ${asm.version} + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + --add-exports=java.base/jdk.internal.ref=ALL-UNNAMED + --add-exports=java.base/sun.nio.ch=ALL-UNNAMED + --add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + --add-opens=jdk.compiler/com.sun.tools.javac=ALL-UNNAMED + --add-opens=java.base/java.lang=ALL-UNNAMED + --add-opens=java.base/java.lang.reflect=ALL-UNNAMED + --add-opens=java.base/java.io=ALL-UNNAMED + --add-opens=java.base/java.util=ALL-UNNAMED + + + + + org.apache.maven.plugins + maven-jar-plugin + ${maven-jar-plugin.version} + + + + + com.baeldung.examples.asm.instrumentation.Premain + + + + + + + + + + 3.29.2-GA + 5.2 + + + \ No newline at end of file diff --git a/asm/src/main/java/com/baeldung/examples/asm/CustomClassWriter.java b/libraries-bytecode/src/main/java/com/baeldung/asm/CustomClassWriter.java similarity index 96% rename from asm/src/main/java/com/baeldung/examples/asm/CustomClassWriter.java rename to libraries-bytecode/src/main/java/com/baeldung/asm/CustomClassWriter.java index d41a1a16a3..f05a753320 100644 --- a/asm/src/main/java/com/baeldung/examples/asm/CustomClassWriter.java +++ b/libraries-bytecode/src/main/java/com/baeldung/asm/CustomClassWriter.java @@ -1,160 +1,160 @@ -package com.baeldung.examples.asm; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.objectweb.asm.ClassReader; -import org.objectweb.asm.ClassVisitor; -import org.objectweb.asm.ClassWriter; -import org.objectweb.asm.FieldVisitor; -import org.objectweb.asm.MethodVisitor; -import static org.objectweb.asm.Opcodes.ACC_PUBLIC; -import static org.objectweb.asm.Opcodes.ACC_STATIC; -import static org.objectweb.asm.Opcodes.ASM4; -import static org.objectweb.asm.Opcodes.V1_5; -import org.objectweb.asm.Type; -import org.objectweb.asm.util.TraceClassVisitor; - -/** - * - * @author baeldung - * @param - */ -public class CustomClassWriter { - - ClassReader reader; - ClassWriter writer; - AddFieldAdapter addFieldAdapter; - AddInterfaceAdapter addInterfaceAdapter; - PublicizeMethodAdapter pubMethAdapter; - final static String CLASSNAME = "java.lang.Integer"; - final static String CLONEABLE = "java/lang/Cloneable"; - - public CustomClassWriter() { - - try { - reader = new ClassReader(CLASSNAME); - writer = new ClassWriter(reader, 0); - - } catch (IOException ex) { - Logger.getLogger(CustomClassWriter.class.getName()).log(Level.SEVERE, null, ex); - } - } - - public CustomClassWriter(byte[] contents) { - reader = new ClassReader(contents); - writer = new ClassWriter(reader, 0); - } - - public static void main(String[] args) { - CustomClassWriter ccw = new CustomClassWriter(); - ccw.publicizeMethod(); - } - - public byte[] addField() { - addFieldAdapter = new AddFieldAdapter("aNewBooleanField", org.objectweb.asm.Opcodes.ACC_PUBLIC, writer); - reader.accept(addFieldAdapter, 0); - return writer.toByteArray(); - } - - public byte[] publicizeMethod() { - pubMethAdapter = new PublicizeMethodAdapter(writer); - reader.accept(pubMethAdapter, 0); - return writer.toByteArray(); - } - - public byte[] addInterface() { - addInterfaceAdapter = new AddInterfaceAdapter(writer); - reader.accept(addInterfaceAdapter, 0); - return writer.toByteArray(); - } - - public class AddInterfaceAdapter extends ClassVisitor { - - public AddInterfaceAdapter(ClassVisitor cv) { - super(ASM4, cv); - } - - @Override - public void visit(int version, int access, String name, - String signature, String superName, String[] interfaces) { - String[] holding = new String[interfaces.length + 1]; - holding[holding.length - 1] = CLONEABLE; - System.arraycopy(interfaces, 0, holding, 0, interfaces.length); - - cv.visit(V1_5, access, name, signature, superName, holding); - } - - } - - public class PublicizeMethodAdapter extends ClassVisitor { - - final Logger logger = Logger.getLogger("PublicizeMethodAdapter"); - TraceClassVisitor tracer; - PrintWriter pw = new PrintWriter(System.out); - - public PublicizeMethodAdapter(ClassVisitor cv) { - super(ASM4, cv); - this.cv = cv; - tracer = new TraceClassVisitor(cv, pw); - } - - @Override - public MethodVisitor visitMethod(int access, - String name, - String desc, - String signature, - String[] exceptions) { - - if (name.equals("toUnsignedString0")) { - logger.info("Visiting unsigned method"); - return tracer.visitMethod(ACC_PUBLIC + ACC_STATIC, name, desc, signature, exceptions); - } - return tracer.visitMethod(access, name, desc, signature, exceptions); - - } - - public void visitEnd() { - tracer.visitEnd(); - System.out.println(tracer.p.getText()); - } - - } - - public class AddFieldAdapter extends ClassVisitor { - - String fieldName; - int access; - boolean isFieldPresent; - - public AddFieldAdapter(String fieldName, int access, ClassVisitor cv) { - super(ASM4, cv); - this.cv = cv; - this.access = access; - this.fieldName = fieldName; - } - - @Override - public FieldVisitor visitField(int access, String name, String desc, - String signature, Object value) { - if (name.equals(fieldName)) { - isFieldPresent = true; - } - return cv.visitField(access, name, desc, signature, value); - } - - @Override - public void visitEnd() { - if (!isFieldPresent) { - FieldVisitor fv = cv.visitField(access, fieldName, Type.BOOLEAN_TYPE.toString(), null, null); - if (fv != null) { - fv.visitEnd(); - } - } - cv.visitEnd(); - } - - } - -} +package com.baeldung.asm; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; +import org.objectweb.asm.FieldVisitor; +import org.objectweb.asm.MethodVisitor; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ASM4; +import static org.objectweb.asm.Opcodes.V1_5; +import org.objectweb.asm.Type; +import org.objectweb.asm.util.TraceClassVisitor; + +/** + * + * @author baeldung + * @param + */ +public class CustomClassWriter { + + ClassReader reader; + ClassWriter writer; + AddFieldAdapter addFieldAdapter; + AddInterfaceAdapter addInterfaceAdapter; + PublicizeMethodAdapter pubMethAdapter; + final static String CLASSNAME = "java.lang.Integer"; + final static String CLONEABLE = "java/lang/Cloneable"; + + public CustomClassWriter() { + + try { + reader = new ClassReader(CLASSNAME); + writer = new ClassWriter(reader, 0); + + } catch (IOException ex) { + Logger.getLogger(CustomClassWriter.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public CustomClassWriter(byte[] contents) { + reader = new ClassReader(contents); + writer = new ClassWriter(reader, 0); + } + + public static void main(String[] args) { + CustomClassWriter ccw = new CustomClassWriter(); + ccw.publicizeMethod(); + } + + public byte[] addField() { + addFieldAdapter = new AddFieldAdapter("aNewBooleanField", org.objectweb.asm.Opcodes.ACC_PUBLIC, writer); + reader.accept(addFieldAdapter, 0); + return writer.toByteArray(); + } + + public byte[] publicizeMethod() { + pubMethAdapter = new PublicizeMethodAdapter(writer); + reader.accept(pubMethAdapter, 0); + return writer.toByteArray(); + } + + public byte[] addInterface() { + addInterfaceAdapter = new AddInterfaceAdapter(writer); + reader.accept(addInterfaceAdapter, 0); + return writer.toByteArray(); + } + + public class AddInterfaceAdapter extends ClassVisitor { + + public AddInterfaceAdapter(ClassVisitor cv) { + super(ASM4, cv); + } + + @Override + public void visit(int version, int access, String name, + String signature, String superName, String[] interfaces) { + String[] holding = new String[interfaces.length + 1]; + holding[holding.length - 1] = CLONEABLE; + System.arraycopy(interfaces, 0, holding, 0, interfaces.length); + + cv.visit(V1_5, access, name, signature, superName, holding); + } + + } + + public class PublicizeMethodAdapter extends ClassVisitor { + + final Logger logger = Logger.getLogger("PublicizeMethodAdapter"); + TraceClassVisitor tracer; + PrintWriter pw = new PrintWriter(System.out); + + public PublicizeMethodAdapter(ClassVisitor cv) { + super(ASM4, cv); + this.cv = cv; + tracer = new TraceClassVisitor(cv, pw); + } + + @Override + public MethodVisitor visitMethod(int access, + String name, + String desc, + String signature, + String[] exceptions) { + + if (name.equals("toUnsignedString0")) { + logger.info("Visiting unsigned method"); + return tracer.visitMethod(ACC_PUBLIC + ACC_STATIC, name, desc, signature, exceptions); + } + return tracer.visitMethod(access, name, desc, signature, exceptions); + + } + + public void visitEnd() { + tracer.visitEnd(); + System.out.println(tracer.p.getText()); + } + + } + + public class AddFieldAdapter extends ClassVisitor { + + String fieldName; + int access; + boolean isFieldPresent; + + public AddFieldAdapter(String fieldName, int access, ClassVisitor cv) { + super(ASM4, cv); + this.cv = cv; + this.access = access; + this.fieldName = fieldName; + } + + @Override + public FieldVisitor visitField(int access, String name, String desc, + String signature, Object value) { + if (name.equals(fieldName)) { + isFieldPresent = true; + } + return cv.visitField(access, name, desc, signature, value); + } + + @Override + public void visitEnd() { + if (!isFieldPresent) { + FieldVisitor fv = cv.visitField(access, fieldName, Type.BOOLEAN_TYPE.toString(), null, null); + if (fv != null) { + fv.visitEnd(); + } + } + cv.visitEnd(); + } + + } + +} diff --git a/asm/src/main/java/com/baeldung/examples/asm/instrumentation/Premain.java b/libraries-bytecode/src/main/java/com/baeldung/asm/instrumentation/Premain.java similarity index 88% rename from asm/src/main/java/com/baeldung/examples/asm/instrumentation/Premain.java rename to libraries-bytecode/src/main/java/com/baeldung/asm/instrumentation/Premain.java index a3e69b6785..502137bd3d 100644 --- a/asm/src/main/java/com/baeldung/examples/asm/instrumentation/Premain.java +++ b/libraries-bytecode/src/main/java/com/baeldung/asm/instrumentation/Premain.java @@ -1,6 +1,6 @@ -package com.baeldung.examples.asm.instrumentation; +package com.baeldung.asm.instrumentation; -import com.baeldung.examples.asm.CustomClassWriter; +import com.baeldung.asm.CustomClassWriter; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; diff --git a/libraries-5/src/main/java/com/baeldung/bytebuddy/Bar.java b/libraries-bytecode/src/main/java/com/baeldung/bytebuddy/Bar.java similarity index 100% rename from libraries-5/src/main/java/com/baeldung/bytebuddy/Bar.java rename to libraries-bytecode/src/main/java/com/baeldung/bytebuddy/Bar.java diff --git a/libraries-5/src/main/java/com/baeldung/bytebuddy/Foo.java b/libraries-bytecode/src/main/java/com/baeldung/bytebuddy/Foo.java similarity index 100% rename from libraries-5/src/main/java/com/baeldung/bytebuddy/Foo.java rename to libraries-bytecode/src/main/java/com/baeldung/bytebuddy/Foo.java diff --git a/libraries/src/main/java/com/baeldung/javasisst/Point.java b/libraries-bytecode/src/main/java/com/baeldung/javasisst/Point.java similarity index 100% rename from libraries/src/main/java/com/baeldung/javasisst/Point.java rename to libraries-bytecode/src/main/java/com/baeldung/javasisst/Point.java diff --git a/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java b/libraries-bytecode/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java similarity index 100% rename from libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java rename to libraries-bytecode/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java diff --git a/java-spi/exchange-rate-api/src/main/resources/logback.xml b/libraries-bytecode/src/main/resources/logback.xml similarity index 100% rename from java-spi/exchange-rate-api/src/main/resources/logback.xml rename to libraries-bytecode/src/main/resources/logback.xml diff --git a/libraries-5/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java b/libraries-bytecode/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java similarity index 93% rename from libraries-5/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java rename to libraries-bytecode/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java index 5f721025c3..398e873223 100644 --- a/libraries-5/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java +++ b/libraries-bytecode/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java @@ -1,5 +1,16 @@ package com.baeldung.bytebuddy; +import static net.bytebuddy.matcher.ElementMatchers.isDeclaredBy; +import static net.bytebuddy.matcher.ElementMatchers.named; +import static net.bytebuddy.matcher.ElementMatchers.returns; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import org.junit.Test; + import net.bytebuddy.ByteBuddy; import net.bytebuddy.agent.ByteBuddyAgent; import net.bytebuddy.dynamic.DynamicType; @@ -8,14 +19,6 @@ import net.bytebuddy.dynamic.loading.ClassReloadingStrategy; import net.bytebuddy.implementation.FixedValue; import net.bytebuddy.implementation.MethodDelegation; import net.bytebuddy.matcher.ElementMatchers; -import org.junit.Test; - -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -import static net.bytebuddy.matcher.ElementMatchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; public class ByteBuddyUnitTest { diff --git a/libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java b/libraries-bytecode/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java rename to libraries-bytecode/src/test/java/com/baeldung/javassist/JavasisstUnitTest.java diff --git a/libraries-cli/.gitignore b/libraries-cli/.gitignore new file mode 100644 index 0000000000..e594daf27a --- /dev/null +++ b/libraries-cli/.gitignore @@ -0,0 +1,9 @@ +*.class + +# Folders # +/gensrc +/target + +# Packaged files # +*.jar +/bin/ diff --git a/libraries-cli/README.md b/libraries-cli/README.md new file mode 100644 index 0000000000..b31bb2853d --- /dev/null +++ b/libraries-cli/README.md @@ -0,0 +1,9 @@ +## Server + +This module contains articles about cli libraries. + +### Relevant Articles: + +- [Create a Java Command Line Program with Picocli](https://www.baeldung.com/java-picocli-create-command-line-program) +- [Parsing Command-Line Parameters with JCommander](https://www.baeldung.com/jcommander-parsing-command-line-parameters) +- [Parsing Command-Line Parameters with Airline](https://www.baeldung.com/java-airline) \ No newline at end of file diff --git a/libraries-cli/pom.xml b/libraries-cli/pom.xml new file mode 100644 index 0000000000..d204f3c735 --- /dev/null +++ b/libraries-cli/pom.xml @@ -0,0 +1,69 @@ + + + 4.0.0 + libraries-cli + 0.0.1-SNAPSHOT + libraries-cli + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter + ${spring-boot-starter.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + info.picocli + picocli + ${picocli.version} + + + com.beust + jcommander + ${jcommander.version} + + + com.github.rvesse + airline + ${airline.version} + + + org.projectlombok + lombok + ${lombok.version} + + + + + + + + + + + 4.7.0 + 1.78 + 2.7.2 + 2.7.8 + 5.3.25 + + + \ No newline at end of file diff --git a/libraries-3/src/main/java/com/baeldung/airline/CommandLine.java b/libraries-cli/src/main/java/com/baeldung/airline/CommandLine.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/airline/CommandLine.java rename to libraries-cli/src/main/java/com/baeldung/airline/CommandLine.java diff --git a/libraries-3/src/main/java/com/baeldung/airline/DatabaseSetupCommand.java b/libraries-cli/src/main/java/com/baeldung/airline/DatabaseSetupCommand.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/airline/DatabaseSetupCommand.java rename to libraries-cli/src/main/java/com/baeldung/airline/DatabaseSetupCommand.java diff --git a/libraries-3/src/main/java/com/baeldung/airline/LoggingCommand.java b/libraries-cli/src/main/java/com/baeldung/airline/LoggingCommand.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/airline/LoggingCommand.java rename to libraries-cli/src/main/java/com/baeldung/airline/LoggingCommand.java diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/helloworld/HelloWorldApp.java b/libraries-cli/src/main/java/com/baeldung/jcommander/helloworld/HelloWorldApp.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/jcommander/helloworld/HelloWorldApp.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/helloworld/HelloWorldApp.java diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/UsageBasedBillingApp.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/UsageBasedBillingApp.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/UsageBasedBillingApp.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/UsageBasedBillingApp.java diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommand.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommand.java similarity index 99% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommand.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommand.java index ea6b18af53..a28066ac3d 100644 --- a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommand.java +++ b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommand.java @@ -1,5 +1,10 @@ package com.baeldung.jcommander.usagebilling.cli; +import static com.baeldung.jcommander.usagebilling.cli.UsageBasedBilling.FETCH_CMD; +import static com.baeldung.jcommander.usagebilling.service.FetchCurrentChargesService.getDefault; + +import java.util.List; + import com.baeldung.jcommander.usagebilling.cli.splitter.ColonParameterSplitter; import com.baeldung.jcommander.usagebilling.cli.validator.UUIDValidator; import com.baeldung.jcommander.usagebilling.model.CurrentChargesRequest; @@ -7,13 +12,9 @@ import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse; import com.baeldung.jcommander.usagebilling.service.FetchCurrentChargesService; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; + import lombok.Getter; -import java.util.List; - -import static com.baeldung.jcommander.usagebilling.cli.UsageBasedBilling.*; -import static com.baeldung.jcommander.usagebilling.service.FetchCurrentChargesService.getDefault; - @Parameters( commandNames = { FETCH_CMD }, commandDescription = "Fetch charges for a customer in the current month, can be itemized or aggregated" diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommand.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommand.java similarity index 99% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommand.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommand.java index d3516b19d3..5c12ac665c 100644 --- a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommand.java +++ b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommand.java @@ -1,5 +1,11 @@ package com.baeldung.jcommander.usagebilling.cli; +import static com.baeldung.jcommander.usagebilling.cli.UsageBasedBilling.SUBMIT_CMD; +import static com.baeldung.jcommander.usagebilling.service.SubmitUsageService.getDefault; + +import java.math.BigDecimal; +import java.time.Instant; + import com.baeldung.jcommander.usagebilling.cli.converter.ISO8601TimestampConverter; import com.baeldung.jcommander.usagebilling.cli.validator.UUIDValidator; import com.baeldung.jcommander.usagebilling.model.UsageRequest; @@ -7,14 +13,9 @@ import com.baeldung.jcommander.usagebilling.model.UsageRequest.PricingType; import com.baeldung.jcommander.usagebilling.service.SubmitUsageService; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; + import lombok.Getter; -import java.math.BigDecimal; -import java.time.Instant; - -import static com.baeldung.jcommander.usagebilling.cli.UsageBasedBilling.*; -import static com.baeldung.jcommander.usagebilling.service.SubmitUsageService.getDefault; - @Parameters( commandNames = { SUBMIT_CMD }, commandDescription = "Submit usage for a given customer and subscription, accepts one usage item" diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/UsageBasedBilling.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/UsageBasedBilling.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/UsageBasedBilling.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/UsageBasedBilling.java diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/converter/ISO8601TimestampConverter.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/converter/ISO8601TimestampConverter.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/converter/ISO8601TimestampConverter.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/converter/ISO8601TimestampConverter.java index e54865a811..c173f62684 100644 --- a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/converter/ISO8601TimestampConverter.java +++ b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/converter/ISO8601TimestampConverter.java @@ -1,7 +1,6 @@ package com.baeldung.jcommander.usagebilling.cli.converter; -import com.beust.jcommander.ParameterException; -import com.beust.jcommander.converters.BaseConverter; +import static java.lang.String.format; import java.time.Instant; import java.time.LocalDateTime; @@ -9,7 +8,8 @@ import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; -import static java.lang.String.format; +import com.beust.jcommander.ParameterException; +import com.beust.jcommander.converters.BaseConverter; public class ISO8601TimestampConverter extends BaseConverter { diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/splitter/ColonParameterSplitter.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/splitter/ColonParameterSplitter.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/splitter/ColonParameterSplitter.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/splitter/ColonParameterSplitter.java index f24c028123..1e73b54045 100644 --- a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/splitter/ColonParameterSplitter.java +++ b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/splitter/ColonParameterSplitter.java @@ -1,10 +1,10 @@ package com.baeldung.jcommander.usagebilling.cli.splitter; -import com.beust.jcommander.converters.IParameterSplitter; +import static java.util.Arrays.asList; import java.util.List; -import static java.util.Arrays.asList; +import com.beust.jcommander.converters.IParameterSplitter; public class ColonParameterSplitter implements IParameterSplitter { diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/validator/UUIDValidator.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/validator/UUIDValidator.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/validator/UUIDValidator.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/validator/UUIDValidator.java index a72912f7d0..f8d9f81203 100644 --- a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/cli/validator/UUIDValidator.java +++ b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/cli/validator/UUIDValidator.java @@ -1,10 +1,10 @@ package com.baeldung.jcommander.usagebilling.cli.validator; +import java.util.regex.Pattern; + import com.beust.jcommander.IParameterValidator; import com.beust.jcommander.ParameterException; -import java.util.regex.Pattern; - public class UUIDValidator implements IParameterValidator { private static final String UUID_REGEX = diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesRequest.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesRequest.java similarity index 70% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesRequest.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesRequest.java index 93dd7a5732..c57805b784 100644 --- a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesRequest.java +++ b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesRequest.java @@ -1,9 +1,13 @@ package com.baeldung.jcommander.usagebilling.model; -import lombok.*; - import java.util.List; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + @NoArgsConstructor(access = AccessLevel.PACKAGE) @AllArgsConstructor(access = AccessLevel.PACKAGE) @Builder diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesResponse.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesResponse.java similarity index 91% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesResponse.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesResponse.java index 865a6e4a3d..46fb86ba78 100644 --- a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesResponse.java +++ b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/model/CurrentChargesResponse.java @@ -1,11 +1,15 @@ package com.baeldung.jcommander.usagebilling.model; -import lombok.*; - import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + @NoArgsConstructor(access = AccessLevel.PACKAGE) @AllArgsConstructor(access = AccessLevel.PACKAGE) @Builder diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/UsageRequest.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/model/UsageRequest.java similarity index 89% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/UsageRequest.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/model/UsageRequest.java index 2785474acf..07da8ee4b5 100644 --- a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/model/UsageRequest.java +++ b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/model/UsageRequest.java @@ -1,10 +1,14 @@ package com.baeldung.jcommander.usagebilling.model; -import lombok.*; - import java.math.BigDecimal; import java.time.Instant; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + @NoArgsConstructor(access = AccessLevel.PACKAGE) @AllArgsConstructor(access = AccessLevel.PACKAGE) @Builder diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultFetchCurrentChargesService.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultFetchCurrentChargesService.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultFetchCurrentChargesService.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultFetchCurrentChargesService.java index 6436d49875..e1c5e25856 100644 --- a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultFetchCurrentChargesService.java +++ b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultFetchCurrentChargesService.java @@ -1,13 +1,5 @@ package com.baeldung.jcommander.usagebilling.service; -import com.baeldung.jcommander.usagebilling.model.CurrentChargesRequest; -import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse; -import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse.LineItem; - -import java.math.BigDecimal; -import java.util.List; -import java.util.UUID; - import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Arrays.fill; @@ -15,6 +7,14 @@ import static java.util.Collections.emptyList; import static java.util.concurrent.ThreadLocalRandom.current; import static java.util.stream.Collectors.toList; +import java.math.BigDecimal; +import java.util.List; +import java.util.UUID; + +import com.baeldung.jcommander.usagebilling.model.CurrentChargesRequest; +import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse; +import com.baeldung.jcommander.usagebilling.model.CurrentChargesResponse.LineItem; + class DefaultFetchCurrentChargesService implements FetchCurrentChargesService { @Override diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultSubmitUsageService.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultSubmitUsageService.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultSubmitUsageService.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultSubmitUsageService.java index 44ac9e9ed7..fb214c9ab9 100644 --- a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultSubmitUsageService.java +++ b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/service/DefaultSubmitUsageService.java @@ -1,9 +1,9 @@ package com.baeldung.jcommander.usagebilling.service; -import com.baeldung.jcommander.usagebilling.model.UsageRequest; - import java.util.UUID; +import com.baeldung.jcommander.usagebilling.model.UsageRequest; + class DefaultSubmitUsageService implements SubmitUsageService { @Override diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/FetchCurrentChargesService.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/service/FetchCurrentChargesService.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/FetchCurrentChargesService.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/service/FetchCurrentChargesService.java diff --git a/libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/SubmitUsageService.java b/libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/service/SubmitUsageService.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/jcommander/usagebilling/service/SubmitUsageService.java rename to libraries-cli/src/main/java/com/baeldung/jcommander/usagebilling/service/SubmitUsageService.java diff --git a/libraries-2/src/main/java/com/baeldung/picocli/git/Application.java b/libraries-cli/src/main/java/com/baeldung/picocli/git/Application.java similarity index 99% rename from libraries-2/src/main/java/com/baeldung/picocli/git/Application.java rename to libraries-cli/src/main/java/com/baeldung/picocli/git/Application.java index 04af524e45..80c132d637 100644 --- a/libraries-2/src/main/java/com/baeldung/picocli/git/Application.java +++ b/libraries-cli/src/main/java/com/baeldung/picocli/git/Application.java @@ -1,13 +1,15 @@ package com.baeldung.picocli.git; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + import com.baeldung.picocli.git.commands.programmative.GitCommand; import com.baeldung.picocli.git.commands.subcommands.GitAddCommand; import com.baeldung.picocli.git.commands.subcommands.GitCommitCommand; import com.baeldung.picocli.git.commands.subcommands.GitConfigCommand; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.CommandLineRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; + import picocli.CommandLine; @SpringBootApplication diff --git a/libraries-2/src/main/java/com/baeldung/picocli/git/commands/declarative/GitCommand.java b/libraries-cli/src/main/java/com/baeldung/picocli/git/commands/declarative/GitCommand.java similarity index 99% rename from libraries-2/src/main/java/com/baeldung/picocli/git/commands/declarative/GitCommand.java rename to libraries-cli/src/main/java/com/baeldung/picocli/git/commands/declarative/GitCommand.java index f3c690a3e6..fbd7907eb8 100644 --- a/libraries-2/src/main/java/com/baeldung/picocli/git/commands/declarative/GitCommand.java +++ b/libraries-cli/src/main/java/com/baeldung/picocli/git/commands/declarative/GitCommand.java @@ -1,14 +1,15 @@ package com.baeldung.picocli.git.commands.declarative; -import com.baeldung.picocli.git.model.ConfigElement; -import com.baeldung.picocli.git.commands.subcommands.GitAddCommand; -import com.baeldung.picocli.git.commands.subcommands.GitCommitCommand; -import com.baeldung.picocli.git.commands.subcommands.GitConfigCommand; -import picocli.CommandLine; - import static picocli.CommandLine.*; import static picocli.CommandLine.Command; +import com.baeldung.picocli.git.commands.subcommands.GitAddCommand; +import com.baeldung.picocli.git.commands.subcommands.GitCommitCommand; +import com.baeldung.picocli.git.commands.subcommands.GitConfigCommand; +import com.baeldung.picocli.git.model.ConfigElement; + +import picocli.CommandLine; + @Command( name = "git", subcommands = { diff --git a/libraries-2/src/main/java/com/baeldung/picocli/git/commands/methods/GitCommand.java b/libraries-cli/src/main/java/com/baeldung/picocli/git/commands/methods/GitCommand.java similarity index 100% rename from libraries-2/src/main/java/com/baeldung/picocli/git/commands/methods/GitCommand.java rename to libraries-cli/src/main/java/com/baeldung/picocli/git/commands/methods/GitCommand.java index 2c3e440b8b..74993a50fe 100644 --- a/libraries-2/src/main/java/com/baeldung/picocli/git/commands/methods/GitCommand.java +++ b/libraries-cli/src/main/java/com/baeldung/picocli/git/commands/methods/GitCommand.java @@ -1,9 +1,9 @@ package com.baeldung.picocli.git.commands.methods; -import picocli.CommandLine; - import static picocli.CommandLine.Command; +import picocli.CommandLine; + @Command(name = "git") public class GitCommand implements Runnable { public static void main(String[] args) { diff --git a/libraries-2/src/main/java/com/baeldung/picocli/git/commands/programmative/GitCommand.java b/libraries-cli/src/main/java/com/baeldung/picocli/git/commands/programmative/GitCommand.java similarity index 99% rename from libraries-2/src/main/java/com/baeldung/picocli/git/commands/programmative/GitCommand.java rename to libraries-cli/src/main/java/com/baeldung/picocli/git/commands/programmative/GitCommand.java index 81ecfd78be..fabd0e4cc7 100644 --- a/libraries-2/src/main/java/com/baeldung/picocli/git/commands/programmative/GitCommand.java +++ b/libraries-cli/src/main/java/com/baeldung/picocli/git/commands/programmative/GitCommand.java @@ -1,13 +1,15 @@ package com.baeldung.picocli.git.commands.programmative; -import com.baeldung.picocli.git.commands.subcommands.GitAddCommand; -import com.baeldung.picocli.git.commands.subcommands.GitCommitCommand; -import org.springframework.stereotype.Component; -import picocli.CommandLine; - import static picocli.CommandLine.Command; import static picocli.CommandLine.RunLast; +import org.springframework.stereotype.Component; + +import com.baeldung.picocli.git.commands.subcommands.GitAddCommand; +import com.baeldung.picocli.git.commands.subcommands.GitCommitCommand; + +import picocli.CommandLine; + @Command(name = "git") @Component public class GitCommand implements Runnable { diff --git a/libraries-2/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitAddCommand.java b/libraries-cli/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitAddCommand.java similarity index 100% rename from libraries-2/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitAddCommand.java rename to libraries-cli/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitAddCommand.java index 803cd8dc7d..f87e55a5cc 100644 --- a/libraries-2/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitAddCommand.java +++ b/libraries-cli/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitAddCommand.java @@ -1,11 +1,11 @@ package com.baeldung.picocli.git.commands.subcommands; -import org.springframework.stereotype.Component; +import static picocli.CommandLine.*; import java.nio.file.Path; import java.util.List; -import static picocli.CommandLine.*; +import org.springframework.stereotype.Component; @Command( name = "add" diff --git a/libraries-2/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitCommitCommand.java b/libraries-cli/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitCommitCommand.java similarity index 100% rename from libraries-2/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitCommitCommand.java rename to libraries-cli/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitCommitCommand.java index df4928983c..f2136f9c39 100644 --- a/libraries-2/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitCommitCommand.java +++ b/libraries-cli/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitCommitCommand.java @@ -1,10 +1,10 @@ package com.baeldung.picocli.git.commands.subcommands; -import org.springframework.stereotype.Component; - import static picocli.CommandLine.Command; import static picocli.CommandLine.Option; +import org.springframework.stereotype.Component; + @Command( name = "commit" ) diff --git a/libraries-2/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitConfigCommand.java b/libraries-cli/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitConfigCommand.java similarity index 99% rename from libraries-2/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitConfigCommand.java rename to libraries-cli/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitConfigCommand.java index 80e14c0121..6ba803140a 100644 --- a/libraries-2/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitConfigCommand.java +++ b/libraries-cli/src/main/java/com/baeldung/picocli/git/commands/subcommands/GitConfigCommand.java @@ -1,11 +1,12 @@ package com.baeldung.picocli.git.commands.subcommands; -import com.baeldung.picocli.git.model.ConfigElement; -import org.springframework.stereotype.Component; - import static picocli.CommandLine.Command; import static picocli.CommandLine.Parameters; +import org.springframework.stereotype.Component; + +import com.baeldung.picocli.git.model.ConfigElement; + @Command( name = "config" ) diff --git a/libraries-2/src/main/java/com/baeldung/picocli/git/model/ConfigElement.java b/libraries-cli/src/main/java/com/baeldung/picocli/git/model/ConfigElement.java similarity index 100% rename from libraries-2/src/main/java/com/baeldung/picocli/git/model/ConfigElement.java rename to libraries-cli/src/main/java/com/baeldung/picocli/git/model/ConfigElement.java diff --git a/libraries-2/src/main/java/com/baeldung/picocli/helloworld/HelloWorldCommand.java b/libraries-cli/src/main/java/com/baeldung/picocli/helloworld/HelloWorldCommand.java similarity index 100% rename from libraries-2/src/main/java/com/baeldung/picocli/helloworld/HelloWorldCommand.java rename to libraries-cli/src/main/java/com/baeldung/picocli/helloworld/HelloWorldCommand.java index 97a861e2f0..2df8ac0a5b 100644 --- a/libraries-2/src/main/java/com/baeldung/picocli/helloworld/HelloWorldCommand.java +++ b/libraries-cli/src/main/java/com/baeldung/picocli/helloworld/HelloWorldCommand.java @@ -1,9 +1,9 @@ package com.baeldung.picocli.helloworld; -import picocli.CommandLine; - import static picocli.CommandLine.Command; +import picocli.CommandLine; + @Command( name = "hello", description = "Says hello" diff --git a/java-spi/exchange-rate-app/src/main/resources/logback.xml b/libraries-cli/src/main/resources/logback.xml similarity index 100% rename from java-spi/exchange-rate-app/src/main/resources/logback.xml rename to libraries-cli/src/main/resources/logback.xml diff --git a/libraries-3/src/test/java/com/baeldung/jcommander/helloworld/HelloWorldAppUnitTest.java b/libraries-cli/src/test/java/com/baeldung/jcommander/helloworld/HelloWorldAppUnitTest.java similarity index 99% rename from libraries-3/src/test/java/com/baeldung/jcommander/helloworld/HelloWorldAppUnitTest.java rename to libraries-cli/src/test/java/com/baeldung/jcommander/helloworld/HelloWorldAppUnitTest.java index 48b3ac2896..c73e8e9d48 100644 --- a/libraries-3/src/test/java/com/baeldung/jcommander/helloworld/HelloWorldAppUnitTest.java +++ b/libraries-cli/src/test/java/com/baeldung/jcommander/helloworld/HelloWorldAppUnitTest.java @@ -1,9 +1,10 @@ package com.baeldung.jcommander.helloworld; -import com.beust.jcommander.JCommander; +import static org.junit.Assert.assertEquals; + import org.junit.Test; -import static org.junit.Assert.assertEquals; +import com.beust.jcommander.JCommander; public class HelloWorldAppUnitTest { diff --git a/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommandUnitTest.java b/libraries-cli/src/test/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommandUnitTest.java similarity index 99% rename from libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommandUnitTest.java rename to libraries-cli/src/test/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommandUnitTest.java index b639661c39..aba4585f6e 100644 --- a/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommandUnitTest.java +++ b/libraries-cli/src/test/java/com/baeldung/jcommander/usagebilling/cli/FetchCurrentChargesCommandUnitTest.java @@ -1,11 +1,12 @@ package com.baeldung.jcommander.usagebilling.cli; -import com.beust.jcommander.JCommander; -import org.junit.Test; - import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.junit.Assert.assertThat; +import org.junit.Test; + +import com.beust.jcommander.JCommander; + public class FetchCurrentChargesCommandUnitTest { private JCommander jc = JCommander.newBuilder() diff --git a/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommandUnitTest.java b/libraries-cli/src/test/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommandUnitTest.java similarity index 95% rename from libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommandUnitTest.java rename to libraries-cli/src/test/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommandUnitTest.java index d6ce132053..a4d8273638 100644 --- a/libraries-3/src/test/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommandUnitTest.java +++ b/libraries-cli/src/test/java/com/baeldung/jcommander/usagebilling/cli/SubmitUsageCommandUnitTest.java @@ -1,12 +1,11 @@ package com.baeldung.jcommander.usagebilling.cli; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.Test; + import com.beust.jcommander.JCommander; import com.beust.jcommander.ParameterException; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; public class SubmitUsageCommandUnitTest { diff --git a/libraries-concurrency/README.md b/libraries-concurrency/README.md index d1ffe81fa8..8808335a5b 100644 --- a/libraries-concurrency/README.md +++ b/libraries-concurrency/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Intro to Coroutines with Quasar](https://www.baeldung.com/java-quasar-coroutines) +- [Java Concurrency Utility with JCTools](https://www.baeldung.com/java-concurrency-jc-tools) diff --git a/libraries-concurrency/pom.xml b/libraries-concurrency/pom.xml index 8b0ccdd5ec..31bce1a982 100644 --- a/libraries-concurrency/pom.xml +++ b/libraries-concurrency/pom.xml @@ -28,6 +28,16 @@ quasar-reactive-streams ${quasar.version} + + org.jctools + jctools-core + ${jctools.version} + + + org.openjdk.jmh + jmh-core + ${jmh-core.version} + @@ -77,6 +87,7 @@ 0.8.0 + 2.1.2 \ No newline at end of file diff --git a/libraries-5/src/main/java/com/baeldung/jctools/MpmcBenchmark.java b/libraries-concurrency/src/main/java/com/baeldung/jctools/MpmcBenchmark.java similarity index 77% rename from libraries-5/src/main/java/com/baeldung/jctools/MpmcBenchmark.java rename to libraries-concurrency/src/main/java/com/baeldung/jctools/MpmcBenchmark.java index 7b754bf709..d448bb74b6 100644 --- a/libraries-5/src/main/java/com/baeldung/jctools/MpmcBenchmark.java +++ b/libraries-concurrency/src/main/java/com/baeldung/jctools/MpmcBenchmark.java @@ -1,14 +1,27 @@ package com.baeldung.jctools; -import org.jctools.queues.MpmcArrayQueue; -import org.jctools.queues.atomic.MpmcAtomicArrayQueue; -import org.openjdk.jmh.annotations.*; -import org.openjdk.jmh.infra.Control; - import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; +import org.jctools.queues.MpmcArrayQueue; +import org.jctools.queues.atomic.MpmcAtomicArrayQueue; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Group; +import org.openjdk.jmh.annotations.GroupThreads; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Control; + @BenchmarkMode(Mode.SampleTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @Fork(1) diff --git a/libraries-5/src/main/java/com/baeldung/jctools/README.md b/libraries-concurrency/src/main/java/com/baeldung/jctools/README.md similarity index 100% rename from libraries-5/src/main/java/com/baeldung/jctools/README.md rename to libraries-concurrency/src/main/java/com/baeldung/jctools/README.md diff --git a/libraries-5/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java b/libraries-concurrency/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java similarity index 98% rename from libraries-5/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java rename to libraries-concurrency/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java index a5dacdbdac..28f42650e9 100644 --- a/libraries-5/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java +++ b/libraries-concurrency/src/test/java/com/baeldung/jctools/JCToolsUnitTest.java @@ -1,20 +1,19 @@ package com.baeldung.jctools; -import org.assertj.core.api.Assertions; -import org.jctools.queues.SpscArrayQueue; -import org.jctools.queues.SpscChunkedArrayQueue; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.IntConsumer; import java.util.stream.Collectors; import java.util.stream.IntStream; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import org.assertj.core.api.Assertions; +import org.jctools.queues.SpscArrayQueue; +import org.jctools.queues.SpscChunkedArrayQueue; +import org.junit.Test; public class JCToolsUnitTest { diff --git a/libraries-data-3/README.md b/libraries-data-3/README.md new file mode 100644 index 0000000000..e6f02bf2aa --- /dev/null +++ b/libraries-data-3/README.md @@ -0,0 +1,15 @@ +## Data Libraries + +This module contains articles about libraries for data processing in Java. + +### Relevant articles +- [Introduction to Javatuples](https://www.baeldung.com/java-tuples) +- [Software Transactional Memory in Java Using Multiverse](https://www.baeldung.com/java-multiverse-stm) +- [Key Value Store with Chronicle Map](https://www.baeldung.com/java-chronicle-map) +- [Guide to the Cactoos Library](https://www.baeldung.com/java-cactoos) +- [Introduction to cache2k](https://www.baeldung.com/java-cache2k) +- [Introduction to PCollections](https://www.baeldung.com/java-pcollections) +- [Introduction to Eclipse Collections](https://www.baeldung.com/eclipse-collections) +- [Introduction to Caffeine](https://www.baeldung.com/java-caching-caffeine) +- [Guide to Using ModelMapper](https://www.baeldung.com/java-modelmapper) +- More articles: [[<-- prev]](/../libraries-data-2) diff --git a/libraries-data-3/pom.xml b/libraries-data-3/pom.xml new file mode 100644 index 0000000000..536939d435 --- /dev/null +++ b/libraries-data-3/pom.xml @@ -0,0 +1,101 @@ + + + 4.0.0 + libraries-data-3 + libraries-data-3 + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.javatuples + javatuples + ${javatuples.version} + + + org.multiverse + multiverse-core + ${multiverse.version} + + + net.openhft + chronicle-map + ${chronicle.map.version} + + + com.sun.java + tools + + + + + org.cactoos + cactoos + ${cactoos.version} + + + org.cache2k + cache2k-base-bom + ${cache2k.version} + pom + + + org.pcollections + pcollections + ${pcollections.version} + + + org.eclipse.collections + eclipse-collections + ${eclipse-collections.version} + + + com.github.ben-manes.caffeine + caffeine + ${caffeine.version} + + + com.google.code.findbugs + jsr305 + ${findbugs.version} + test + + + org.modelmapper + modelmapper + ${org.modelmapper.version} + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + --add-exports=java.base/jdk.internal.ref=ALL-UNNAMED --add-exports=java.base/sun.nio.ch=ALL-UNNAMED --add-exports=jdk.unsupported/sun.misc=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-opens=jdk.compiler/com.sun.tools.javac=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED + + + + + + + 1.2 + 0.7.0 + 3.24ea1 + 0.43 + 1.2.3.Final + 2.1.2 + 8.2.0 + 3.1.8 + 3.0.2 + 3.2.0 + + + diff --git a/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelper.java b/libraries-data-3/src/main/java/com/baeldung/cache2k/ProductHelper.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/cache2k/ProductHelper.java rename to libraries-data-3/src/main/java/com/baeldung/cache2k/ProductHelper.java diff --git a/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperUsingLoader.java b/libraries-data-3/src/main/java/com/baeldung/cache2k/ProductHelperUsingLoader.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperUsingLoader.java rename to libraries-data-3/src/main/java/com/baeldung/cache2k/ProductHelperUsingLoader.java diff --git a/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperWithEventListener.java b/libraries-data-3/src/main/java/com/baeldung/cache2k/ProductHelperWithEventListener.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperWithEventListener.java rename to libraries-data-3/src/main/java/com/baeldung/cache2k/ProductHelperWithEventListener.java diff --git a/libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperWithExpiry.java b/libraries-data-3/src/main/java/com/baeldung/cache2k/ProductHelperWithExpiry.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/cache2k/ProductHelperWithExpiry.java rename to libraries-data-3/src/main/java/com/baeldung/cache2k/ProductHelperWithExpiry.java diff --git a/libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java b/libraries-data-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java rename to libraries-data-3/src/main/java/com/baeldung/cactoos/CactoosCollectionUtils.java diff --git a/libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java b/libraries-data-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java rename to libraries-data-3/src/main/java/com/baeldung/cactoos/CactoosStringUtils.java diff --git a/libraries-5/src/main/java/com/baeldung/caffeine/DataObject.java b/libraries-data-3/src/main/java/com/baeldung/caffeine/DataObject.java similarity index 100% rename from libraries-5/src/main/java/com/baeldung/caffeine/DataObject.java rename to libraries-data-3/src/main/java/com/baeldung/caffeine/DataObject.java diff --git a/libraries-4/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java b/libraries-data-3/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java similarity index 100% rename from libraries-4/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java rename to libraries-data-3/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java diff --git a/libraries-4/src/main/java/com/baeldung/eclipsecollections/Student.java b/libraries-data-3/src/main/java/com/baeldung/eclipsecollections/Student.java similarity index 100% rename from libraries-4/src/main/java/com/baeldung/eclipsecollections/Student.java rename to libraries-data-3/src/main/java/com/baeldung/eclipsecollections/Student.java diff --git a/libraries-6/src/main/java/com/baeldung/modelmapper/domain/Game.java b/libraries-data-3/src/main/java/com/baeldung/modelmapper/domain/Game.java similarity index 100% rename from libraries-6/src/main/java/com/baeldung/modelmapper/domain/Game.java rename to libraries-data-3/src/main/java/com/baeldung/modelmapper/domain/Game.java diff --git a/libraries-6/src/main/java/com/baeldung/modelmapper/domain/GameMode.java b/libraries-data-3/src/main/java/com/baeldung/modelmapper/domain/GameMode.java similarity index 100% rename from libraries-6/src/main/java/com/baeldung/modelmapper/domain/GameMode.java rename to libraries-data-3/src/main/java/com/baeldung/modelmapper/domain/GameMode.java diff --git a/libraries-6/src/main/java/com/baeldung/modelmapper/domain/GameSettings.java b/libraries-data-3/src/main/java/com/baeldung/modelmapper/domain/GameSettings.java similarity index 100% rename from libraries-6/src/main/java/com/baeldung/modelmapper/domain/GameSettings.java rename to libraries-data-3/src/main/java/com/baeldung/modelmapper/domain/GameSettings.java diff --git a/libraries-6/src/main/java/com/baeldung/modelmapper/domain/Player.java b/libraries-data-3/src/main/java/com/baeldung/modelmapper/domain/Player.java similarity index 100% rename from libraries-6/src/main/java/com/baeldung/modelmapper/domain/Player.java rename to libraries-data-3/src/main/java/com/baeldung/modelmapper/domain/Player.java diff --git a/libraries-6/src/main/java/com/baeldung/modelmapper/dto/GameDTO.java b/libraries-data-3/src/main/java/com/baeldung/modelmapper/dto/GameDTO.java similarity index 99% rename from libraries-6/src/main/java/com/baeldung/modelmapper/dto/GameDTO.java rename to libraries-data-3/src/main/java/com/baeldung/modelmapper/dto/GameDTO.java index 1c8111809c..07e3ba4903 100644 --- a/libraries-6/src/main/java/com/baeldung/modelmapper/dto/GameDTO.java +++ b/libraries-data-3/src/main/java/com/baeldung/modelmapper/dto/GameDTO.java @@ -1,8 +1,9 @@ package com.baeldung.modelmapper.dto; -import com.baeldung.modelmapper.domain.GameMode; import java.util.List; +import com.baeldung.modelmapper.domain.GameMode; + public class GameDTO { private Long id; diff --git a/libraries-6/src/main/java/com/baeldung/modelmapper/dto/PlayerDTO.java b/libraries-data-3/src/main/java/com/baeldung/modelmapper/dto/PlayerDTO.java similarity index 100% rename from libraries-6/src/main/java/com/baeldung/modelmapper/dto/PlayerDTO.java rename to libraries-data-3/src/main/java/com/baeldung/modelmapper/dto/PlayerDTO.java diff --git a/libraries-6/src/main/java/com/baeldung/modelmapper/repository/GameRepository.java b/libraries-data-3/src/main/java/com/baeldung/modelmapper/repository/GameRepository.java similarity index 99% rename from libraries-6/src/main/java/com/baeldung/modelmapper/repository/GameRepository.java rename to libraries-data-3/src/main/java/com/baeldung/modelmapper/repository/GameRepository.java index 80b861c981..2b33e8fba6 100644 --- a/libraries-6/src/main/java/com/baeldung/modelmapper/repository/GameRepository.java +++ b/libraries-data-3/src/main/java/com/baeldung/modelmapper/repository/GameRepository.java @@ -1,9 +1,10 @@ package com.baeldung.modelmapper.repository; -import com.baeldung.modelmapper.domain.Game; import java.util.ArrayList; import java.util.List; +import com.baeldung.modelmapper.domain.Game; + /** * Sample in-memory Game Repository */ diff --git a/libraries/src/main/java/com/baeldung/stm/Account.java b/libraries-data-3/src/main/java/com/baeldung/stm/Account.java similarity index 100% rename from libraries/src/main/java/com/baeldung/stm/Account.java rename to libraries-data-3/src/main/java/com/baeldung/stm/Account.java diff --git a/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/cache2k/ProductHelperUnitTest.java similarity index 100% rename from libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/cache2k/ProductHelperUnitTest.java diff --git a/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperUsingLoaderUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/cache2k/ProductHelperUsingLoaderUnitTest.java similarity index 100% rename from libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperUsingLoaderUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/cache2k/ProductHelperUsingLoaderUnitTest.java diff --git a/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperWithEventListenerUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/cache2k/ProductHelperWithEventListenerUnitTest.java similarity index 100% rename from libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperWithEventListenerUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/cache2k/ProductHelperWithEventListenerUnitTest.java diff --git a/libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperWithExpiryUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/cache2k/ProductHelperWithExpiryUnitTest.java similarity index 100% rename from libraries-3/src/test/java/com/baeldung/cache2k/ProductHelperWithExpiryUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/cache2k/ProductHelperWithExpiryUnitTest.java diff --git a/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java similarity index 100% rename from libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java index c6bcbd7df7..a57c5def6e 100644 --- a/libraries-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java +++ b/libraries-data-3/src/test/java/com/baeldung/cactoos/CactoosCollectionUtilsUnitTest.java @@ -3,8 +3,8 @@ package com.baeldung.cactoos; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; -import java.util.List; import java.util.ArrayList; +import java.util.List; import org.junit.Test; diff --git a/libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java similarity index 100% rename from libraries-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/cactoos/CactoosStringUtilsUnitTest.java diff --git a/libraries-5/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java similarity index 92% rename from libraries-5/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java index 65c441c50d..db7e12d78c 100644 --- a/libraries-5/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java +++ b/libraries-data-3/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java @@ -1,6 +1,8 @@ package com.baeldung.caffeine; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import java.util.Arrays; import java.util.Map; @@ -11,7 +13,11 @@ import javax.annotation.Nonnull; import org.junit.Assert; import org.junit.Test; -import com.github.benmanes.caffeine.cache.*; +import com.github.benmanes.caffeine.cache.AsyncLoadingCache; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.Expiry; +import com.github.benmanes.caffeine.cache.LoadingCache; public class CaffeineUnitTest { diff --git a/libraries-2/src/test/java/com/baeldung/chroniclemap/ChronicleMapUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/chroniclemap/ChronicleMapUnitTest.java similarity index 97% rename from libraries-2/src/test/java/com/baeldung/chroniclemap/ChronicleMapUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/chroniclemap/ChronicleMapUnitTest.java index 7f36a9abdb..6b3898419a 100644 --- a/libraries-2/src/test/java/com/baeldung/chroniclemap/ChronicleMapUnitTest.java +++ b/libraries-data-3/src/test/java/com/baeldung/chroniclemap/ChronicleMapUnitTest.java @@ -1,132 +1,132 @@ -package com.baeldung.chroniclemap; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - -import java.io.File; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import net.openhft.chronicle.core.values.LongValue; -import net.openhft.chronicle.map.ChronicleMap; -import net.openhft.chronicle.map.ExternalMapQueryContext; -import net.openhft.chronicle.map.MapEntry; -import net.openhft.chronicle.values.Values; - -public class ChronicleMapUnitTest { - - static ChronicleMap persistedCountryMap = null; - - static ChronicleMap inMemoryCountryMap = null; - - static ChronicleMap> multiMap = null; - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @BeforeClass - public static void init() { - try { - inMemoryCountryMap = ChronicleMap.of(LongValue.class, CharSequence.class) - .name("country-map") - .entries(50) - .averageValue("America") - .create(); - - persistedCountryMap = ChronicleMap.of(LongValue.class, CharSequence.class) - .name("country-map") - .entries(50) - .averageValue("America") - .createPersistedTo(new File(System.getProperty("user.home") + "/country-details.dat")); - - Set averageValue = IntStream.of(1, 2) - .boxed() - .collect(Collectors.toSet()); - multiMap = ChronicleMap.of(Integer.class, (Class>) (Class) Set.class) - .name("multi-map") - .entries(50) - .averageValue(averageValue) - .create(); - - LongValue qatarKey = Values.newHeapInstance(LongValue.class); - qatarKey.setValue(1); - inMemoryCountryMap.put(qatarKey, "Qatar"); - - LongValue key = Values.newHeapInstance(LongValue.class); - key.setValue(1); - persistedCountryMap.put(key, "Romania"); - key.setValue(2); - persistedCountryMap.put(key, "India"); - - Set set1 = new HashSet<>(); - set1.add(1); - set1.add(2); - multiMap.put(1, set1); - - Set set2 = new HashSet<>(); - set2.add(3); - multiMap.put(2, set2); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void givenGetQuery_whenCalled_shouldReturnResult() { - LongValue key = Values.newHeapInstance(LongValue.class); - key.setValue(1); - CharSequence country = inMemoryCountryMap.get(key); - assertThat(country.toString(), is(equalTo("Qatar"))); - } - - @Test - public void givenGetUsingQuery_whenCalled_shouldReturnResult() { - LongValue key = Values.newHeapInstance(LongValue.class); - StringBuilder country = new StringBuilder(); - key.setValue(1); - persistedCountryMap.getUsing(key, country); - assertThat(country.toString(), is(equalTo("Romania"))); - key.setValue(2); - persistedCountryMap.getUsing(key, country); - assertThat(country.toString(), is(equalTo("India"))); - } - - @Test - public void givenMultipleKeyQuery_whenProcessed_shouldChangeTheValue() { - try (ExternalMapQueryContext, ?> fistContext = multiMap.queryContext(1)) { - try (ExternalMapQueryContext, ?> secondContext = multiMap.queryContext(2)) { - fistContext.updateLock() - .lock(); - secondContext.updateLock() - .lock(); - MapEntry> firstEntry = fistContext.entry(); - Set firstSet = firstEntry.value() - .get(); - firstSet.remove(2); - MapEntry> secondEntry = secondContext.entry(); - Set secondSet = secondEntry.value() - .get(); - secondSet.add(4); - firstEntry.doReplaceValue(fistContext.wrapValueAsData(firstSet)); - secondEntry.doReplaceValue(secondContext.wrapValueAsData(secondSet)); - } - } finally { - assertThat(multiMap.get(1) - .size(), is(equalTo(1))); - assertThat(multiMap.get(2) - .size(), is(equalTo(2))); - } - } - - @AfterClass - public static void finish() { - persistedCountryMap.close(); - inMemoryCountryMap.close(); - multiMap.close(); - } -} +package com.baeldung.chroniclemap; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import net.openhft.chronicle.core.values.LongValue; +import net.openhft.chronicle.map.ChronicleMap; +import net.openhft.chronicle.map.ExternalMapQueryContext; +import net.openhft.chronicle.map.MapEntry; +import net.openhft.chronicle.values.Values; + +public class ChronicleMapUnitTest { + + static ChronicleMap persistedCountryMap = null; + + static ChronicleMap inMemoryCountryMap = null; + + static ChronicleMap> multiMap = null; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @BeforeClass + public static void init() { + try { + inMemoryCountryMap = ChronicleMap.of(LongValue.class, CharSequence.class) + .name("country-map") + .entries(50) + .averageValue("America") + .create(); + + persistedCountryMap = ChronicleMap.of(LongValue.class, CharSequence.class) + .name("country-map") + .entries(50) + .averageValue("America") + .createPersistedTo(new File(System.getProperty("user.home") + "/country-details.dat")); + + Set averageValue = IntStream.of(1, 2) + .boxed() + .collect(Collectors.toSet()); + multiMap = ChronicleMap.of(Integer.class, (Class>) (Class) Set.class) + .name("multi-map") + .entries(50) + .averageValue(averageValue) + .create(); + + LongValue qatarKey = Values.newHeapInstance(LongValue.class); + qatarKey.setValue(1); + inMemoryCountryMap.put(qatarKey, "Qatar"); + + LongValue key = Values.newHeapInstance(LongValue.class); + key.setValue(1); + persistedCountryMap.put(key, "Romania"); + key.setValue(2); + persistedCountryMap.put(key, "India"); + + Set set1 = new HashSet<>(); + set1.add(1); + set1.add(2); + multiMap.put(1, set1); + + Set set2 = new HashSet<>(); + set2.add(3); + multiMap.put(2, set2); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void givenGetQuery_whenCalled_shouldReturnResult() { + LongValue key = Values.newHeapInstance(LongValue.class); + key.setValue(1); + CharSequence country = inMemoryCountryMap.get(key); + assertThat(country.toString(), is(equalTo("Qatar"))); + } + + @Test + public void givenGetUsingQuery_whenCalled_shouldReturnResult() { + LongValue key = Values.newHeapInstance(LongValue.class); + StringBuilder country = new StringBuilder(); + key.setValue(1); + persistedCountryMap.getUsing(key, country); + assertThat(country.toString(), is(equalTo("Romania"))); + key.setValue(2); + persistedCountryMap.getUsing(key, country); + assertThat(country.toString(), is(equalTo("India"))); + } + + @Test + public void givenMultipleKeyQuery_whenProcessed_shouldChangeTheValue() { + try (ExternalMapQueryContext, ?> fistContext = multiMap.queryContext(1)) { + try (ExternalMapQueryContext, ?> secondContext = multiMap.queryContext(2)) { + fistContext.updateLock() + .lock(); + secondContext.updateLock() + .lock(); + MapEntry> firstEntry = fistContext.entry(); + Set firstSet = firstEntry.value() + .get(); + firstSet.remove(2); + MapEntry> secondEntry = secondContext.entry(); + Set secondSet = secondEntry.value() + .get(); + secondSet.add(4); + firstEntry.doReplaceValue(fistContext.wrapValueAsData(firstSet)); + secondEntry.doReplaceValue(secondContext.wrapValueAsData(secondSet)); + } + } finally { + assertThat(multiMap.get(1) + .size(), is(equalTo(1))); + assertThat(multiMap.get(2) + .size(), is(equalTo(2))); + } + } + + @AfterClass + public static void finish() { + persistedCountryMap.close(); + inMemoryCountryMap.close(); + multiMap.close(); + } +} diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/AllSatisfyPatternUnitTest.java diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/AnySatisfyPatternUnitTest.java diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java similarity index 99% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java index ff111a6d72..878964a25f 100644 --- a/libraries-4/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java +++ b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/CollectPatternUnitTest.java @@ -1,9 +1,8 @@ package com.baeldung.eclipsecollections; +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.list.mutable.FastList; - -import org.assertj.core.api.Assertions; import org.junit.Test; public class CollectPatternUnitTest { diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/ConvertContainerToAnotherUnitTest.java diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/DetectPatternUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/DetectPatternUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/DetectPatternUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/DetectPatternUnitTest.java diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java similarity index 99% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java index b0735267ae..3f57576e5d 100644 --- a/libraries-4/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java +++ b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/FlatCollectUnitTest.java @@ -1,12 +1,11 @@ package com.baeldung.eclipsecollections; -import org.assertj.core.api.Assertions; -import org.eclipse.collections.api.list.MutableList; -import org.eclipse.collections.impl.list.mutable.FastList; - import java.util.ArrayList; import java.util.List; +import org.assertj.core.api.Assertions; +import org.eclipse.collections.api.list.MutableList; +import org.eclipse.collections.impl.list.mutable.FastList; import org.junit.Before; import org.junit.Test; diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java similarity index 95% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java index a1bd280658..3f395324c2 100644 --- a/libraries-4/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java +++ b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/ForEachPatternUnitTest.java @@ -1,7 +1,5 @@ package com.baeldung.eclipsecollections; -import static org.junit.Assert.assertEquals; - import org.eclipse.collections.api.tuple.Pair; import org.eclipse.collections.impl.map.mutable.UnifiedMap; import org.eclipse.collections.impl.tuple.Tuples; diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/InjectIntoPatternUnitTest.java diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/LazyIterationUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/LazyIterationUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/LazyIterationUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/LazyIterationUnitTest.java diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/PartitionPatternUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/PartitionPatternUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/PartitionPatternUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/PartitionPatternUnitTest.java diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/RejectPatternUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/RejectPatternUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/RejectPatternUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/RejectPatternUnitTest.java diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/SelectPatternUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/SelectPatternUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/SelectPatternUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/SelectPatternUnitTest.java diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java similarity index 99% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java index 942cdf4595..31b91c663e 100644 --- a/libraries-4/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java +++ b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/ZipUnitTest.java @@ -1,11 +1,10 @@ package com.baeldung.eclipsecollections; +import org.assertj.core.api.Assertions; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.api.tuple.Pair; import org.eclipse.collections.impl.factory.Lists; import org.eclipse.collections.impl.tuple.Tuples; - -import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; diff --git a/libraries-4/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/eclipsecollections/ZipWithIndexUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/javatuples/JavaTuplesUnitTest.java diff --git a/libraries-6/src/test/java/com/baeldung/modelmapper/ModelMapperUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/modelmapper/ModelMapperUnitTest.java similarity index 99% rename from libraries-6/src/test/java/com/baeldung/modelmapper/ModelMapperUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/modelmapper/ModelMapperUnitTest.java index 69bc4059b0..c24e3c1f96 100644 --- a/libraries-6/src/test/java/com/baeldung/modelmapper/ModelMapperUnitTest.java +++ b/libraries-data-3/src/test/java/com/baeldung/modelmapper/ModelMapperUnitTest.java @@ -5,15 +5,9 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; -import com.baeldung.modelmapper.domain.Game; -import com.baeldung.modelmapper.domain.GameMode; -import com.baeldung.modelmapper.domain.GameSettings; -import com.baeldung.modelmapper.domain.Player; -import com.baeldung.modelmapper.dto.GameDTO; -import com.baeldung.modelmapper.dto.PlayerDTO; -import com.baeldung.modelmapper.repository.GameRepository; import java.time.Instant; import java.util.Collection; + import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.modelmapper.Condition; @@ -24,6 +18,14 @@ import org.modelmapper.Provider; import org.modelmapper.TypeMap; import org.modelmapper.convention.MatchingStrategies; +import com.baeldung.modelmapper.domain.Game; +import com.baeldung.modelmapper.domain.GameMode; +import com.baeldung.modelmapper.domain.GameSettings; +import com.baeldung.modelmapper.domain.Player; +import com.baeldung.modelmapper.dto.GameDTO; +import com.baeldung.modelmapper.dto.PlayerDTO; +import com.baeldung.modelmapper.repository.GameRepository; + public class ModelMapperUnitTest { ModelMapper mapper; diff --git a/libraries-4/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java similarity index 96% rename from libraries-4/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java index 1a75624439..48bf232294 100644 --- a/libraries-4/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java +++ b/libraries-data-3/src/test/java/com/baeldung/pcollections/PCollectionsUnitTest.java @@ -1,6 +1,14 @@ package com.baeldung.pcollections; -import org.junit.Test; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; import org.pcollections.HashPMap; import org.pcollections.HashTreePMap; import org.pcollections.HashTreePSet; @@ -8,14 +16,6 @@ import org.pcollections.MapPSet; import org.pcollections.PVector; import org.pcollections.TreePVector; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - public class PCollectionsUnitTest { @Test diff --git a/libraries/src/test/java/com/baeldung/stm/AccountUnitTest.java b/libraries-data-3/src/test/java/com/baeldung/stm/AccountUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/stm/AccountUnitTest.java rename to libraries-data-3/src/test/java/com/baeldung/stm/AccountUnitTest.java index aa872ab622..c5c78f7af3 100644 --- a/libraries/src/test/java/com/baeldung/stm/AccountUnitTest.java +++ b/libraries-data-3/src/test/java/com/baeldung/stm/AccountUnitTest.java @@ -1,6 +1,7 @@ package com.baeldung.stm; -import org.junit.Test; +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.junit.Assert.assertTrue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; @@ -8,8 +9,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import static org.assertj.core.api.Java6Assertions.assertThat; -import static org.junit.Assert.assertTrue; +import org.junit.Test; public class AccountUnitTest { diff --git a/libraries-data-db/pom.xml b/libraries-data-db/pom.xml index 5f1ff489f4..7f77d40667 100644 --- a/libraries-data-db/pom.xml +++ b/libraries-data-db/pom.xml @@ -300,11 +300,12 @@ 6.0.0-release 6.0.1 3.2.1 - 5.0.1 + 5.1.0 13.15.2 2.1.3.Final 2.2.3 1.17.6 + 3.0.8 \ No newline at end of file diff --git a/libraries-data-io/pom.xml b/libraries-data-io/pom.xml index c8d895b4e5..9fc2814312 100644 --- a/libraries-data-io/pom.xml +++ b/libraries-data-io/pom.xml @@ -98,7 +98,7 @@ - 1.21 + 2.2 4.0.1 1.7.0 5.8 diff --git a/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/YAMLToJavaDeserialisationUnitTest.java b/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/YAMLToJavaDeserialisationUnitTest.java index 6f32f143a9..4c92bf41e1 100644 --- a/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/YAMLToJavaDeserialisationUnitTest.java +++ b/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/YAMLToJavaDeserialisationUnitTest.java @@ -1,15 +1,19 @@ package com.baeldung.libraries.snakeyaml; -import org.junit.Test; -import org.yaml.snakeyaml.TypeDescription; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.util.Date; import java.util.Map; -import static org.junit.Assert.*; +import org.junit.Test; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.inspector.TagInspector; public class YAMLToJavaDeserialisationUnitTest { @@ -27,7 +31,7 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObject() { - Yaml yaml = new Yaml(new Constructor(Customer.class)); + Yaml yaml = new Yaml(new Constructor(Customer.class,new LoaderOptions())); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("yaml/customer.yaml"); @@ -39,7 +43,11 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadYAMLDocumentWithAssumedClass_thenLoadCorrectJavaObject() { - Yaml yaml = new Yaml(); + LoaderOptions loaderoptions = new LoaderOptions(); + TagInspector taginspector = tag -> tag.getClassName() + .equals(Customer.class.getName()); + loaderoptions.setTagInspector(taginspector); + Yaml yaml = new Yaml(new Constructor(Customer.class, loaderoptions)); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("yaml/customer_with_type.yaml"); @@ -61,7 +69,7 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadYAMLDocumentWithTopLevelClass_thenLoadCorrectJavaObjectWithNestedObjects() { - Yaml yaml = new Yaml(new Constructor(Customer.class)); + Yaml yaml = new Yaml(new Constructor(Customer.class, new LoaderOptions())); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("yaml/customer_with_contact_details_and_address.yaml"); @@ -91,7 +99,7 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadYAMLDocumentWithTypeDescription_thenLoadCorrectJavaObjectWithCorrectGenericType() { - Constructor constructor = new Constructor(Customer.class); + Constructor constructor = new Constructor(Customer.class, new LoaderOptions()); TypeDescription customTypeDescription = new TypeDescription(Customer.class); customTypeDescription.addPropertyParameters("contactDetails", Contact.class); constructor.addTypeDescription(customTypeDescription); @@ -116,7 +124,7 @@ public class YAMLToJavaDeserialisationUnitTest { @Test public void whenLoadMultipleYAMLDocuments_thenLoadCorrectJavaObjects() { - Yaml yaml = new Yaml(new Constructor(Customer.class)); + Yaml yaml = new Yaml(new Constructor(Customer.class, new LoaderOptions())); InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("yaml/customers.yaml"); diff --git a/libraries-data/pom.xml b/libraries-data/pom.xml index 85ef01e704..bab544e203 100644 --- a/libraries-data/pom.xml +++ b/libraries-data/pom.xml @@ -97,6 +97,11 @@ + + com.h2database + h2 + 1.3.170 + com.fasterxml.jackson.core jackson-databind @@ -150,6 +155,16 @@ xstream 1.4.16 + + org.springframework.data + spring-data-jpa + 2.1.5.RELEASE + + + javax.persistence + javax.persistence-api + 2.2 + diff --git a/libraries-data/src/main/java/com/baeldung/objecthydration/User.java b/libraries-data/src/main/java/com/baeldung/objecthydration/User.java new file mode 100644 index 0000000000..9d879d62c4 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/objecthydration/User.java @@ -0,0 +1,75 @@ +package com.baeldung.objecthydration; + +import java.io.Serializable; +import java.util.Objects; + +public class User implements Serializable { + private String uId; + private String firstName; + private String lastName; + private String alias; + + public User() { + } + + public User(String firstName, String uId, String lastName, String alias) { + this.firstName = firstName; + this.uId = uId; + this.lastName = lastName; + this.alias = alias; + } + + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + User user = (User) o; + return Objects.equals(firstName, user.firstName) && Objects.equals(uId, user.uId) && Objects.equals(lastName, user.lastName) && Objects.equals(alias, user.alias); + } + + public String getuId() { + return uId; + } + + public void setuId(String uId) { + this.uId = uId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getAlias() { + return alias; + } + + public void setAlias(String alias) { + this.alias = alias; + } + + public void generateMyUser() { + this.setAlias("007"); + this.setFirstName("James"); + this.setLastName("Bond"); + this.setuId("JB"); + } + + @Override + public int hashCode() { + return Objects.hash(firstName, uId, lastName, alias); + } +} diff --git a/libraries-data/src/main/java/com/baeldung/objecthydration/UserSerialisationDeserialisation.java b/libraries-data/src/main/java/com/baeldung/objecthydration/UserSerialisationDeserialisation.java new file mode 100644 index 0000000000..c9d8c5773f --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/objecthydration/UserSerialisationDeserialisation.java @@ -0,0 +1,34 @@ +package com.baeldung.objecthydration; + +import java.io.*; + +public class UserSerialisationDeserialisation { + public void serialisedUser(User user, String outputName) { + try { + FileOutputStream fileOut = new FileOutputStream(outputName); + ObjectOutputStream out = new ObjectOutputStream(fileOut); + out.writeObject(user); + out.close(); + fileOut.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public User deserialiseUser(String serialisedFile) { + User deserializedUser = null; + try { + FileInputStream fileIn = new FileInputStream(serialisedFile); + ObjectInputStream in = new ObjectInputStream(fileIn); + deserializedUser = (User) in.readObject(); + in.close(); + fileIn.close(); + } catch (IOException | ClassNotFoundException e) { + e.printStackTrace(); + } finally { + File f = new File(serialisedFile); + f.delete(); + } + return deserializedUser; + } +} diff --git a/libraries-data/src/main/java/com/baeldung/objecthydration/entity/Book.java b/libraries-data/src/main/java/com/baeldung/objecthydration/entity/Book.java new file mode 100644 index 0000000000..3ae22cee88 --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/objecthydration/entity/Book.java @@ -0,0 +1,71 @@ +package com.baeldung.objecthydration.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "books") +public class Book { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "name") + private String name; + + @Column(name = "author") + private String author; + + @Column(name = "isbn") + private String isbn; + + // Constructors, getters, and setters + + public Book() { + // Default constructor required by Hibernate + } + + public Book(String name, String author, String isbn) { + this.name = name; + this.author = author; + this.isbn = isbn; + } + + // Getters and setters for all attributes + + 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 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; + } +} \ No newline at end of file diff --git a/libraries-data/src/main/java/com/baeldung/objecthydration/repository/BookRepository.java b/libraries-data/src/main/java/com/baeldung/objecthydration/repository/BookRepository.java new file mode 100644 index 0000000000..a8e92eab8e --- /dev/null +++ b/libraries-data/src/main/java/com/baeldung/objecthydration/repository/BookRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.objecthydration.repository; + +import com.baeldung.objecthydration.entity.Book; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface BookRepository extends JpaRepository { +} diff --git a/libraries-data/src/test/java/com/baeldung/objecthydration/HydrationUnitTest.java b/libraries-data/src/test/java/com/baeldung/objecthydration/HydrationUnitTest.java new file mode 100644 index 0000000000..317827346f --- /dev/null +++ b/libraries-data/src/test/java/com/baeldung/objecthydration/HydrationUnitTest.java @@ -0,0 +1,40 @@ +package com.baeldung.objecthydration; + +import org.junit.Assert; +import org.junit.Test; + +public class HydrationUnitTest { + + @Test + public void givenEmptyClass_whenLazilyinitialised_thenGiveNullOnGet() { + User iamUser = new User(); + Assert.assertNull(iamUser.getuId()); + } + + @Test + public void givenInitialisedClass_withLazilyInitialised_thenDoesNotGiveNullOnGet() { + User iamUser = new User(); + iamUser.setAlias("007"); + Assert.assertNotNull(iamUser.getAlias()); + } + + @Test + public void givenEmptyClass_withHydration_thenShouldHaveAllAttributesSet() { + User jamesBond = new User(); + Assert.assertNull(jamesBond.getAlias()); + + jamesBond.generateMyUser(); + Assert.assertEquals("007", jamesBond.getAlias()); + } + + @Test + public void givenUser_thenShouldPerformUserSerialisationDeserialisation() { + User iamUser = new User(); + iamUser.setAlias("007"); + UserSerialisationDeserialisation usd = new UserSerialisationDeserialisation(); + usd.serialisedUser(iamUser, "bond.ser"); + User deserialisedUser = usd.deserialiseUser("bond.ser"); + Assert.assertEquals(iamUser.getAlias(), deserialisedUser.getAlias()); + + } +} diff --git a/libraries-http-2/pom.xml b/libraries-http-2/pom.xml index b49e4b9387..5e803cde8a 100644 --- a/libraries-http-2/pom.xml +++ b/libraries-http-2/pom.xml @@ -118,7 +118,7 @@ 2.3.0 5.1.9.RELEASE 1.0.3 - 3.2.12.RELEASE + 3.6.0 1.49 diff --git a/libraries-io/README.md b/libraries-io/README.md index a9ca5df3d6..1f439b954b 100644 --- a/libraries-io/README.md +++ b/libraries-io/README.md @@ -4,3 +4,4 @@ - [Transferring a File Through SFTP in Java](https://www.baeldung.com/java-file-sftp) - [How to Create Password-Protected Zip Files and Unzip Them in Java](https://www.baeldung.com/java-password-protected-zip-unzip) - [How to Create CSV File from POJO with Custom Column Headers and Positions](https://www.baeldung.com/java-create-csv-pojo-customize-columns) +- [Delete a Directory Recursively in Java](https://www.baeldung.com/java-delete-directory) diff --git a/libraries-io/pom.xml b/libraries-io/pom.xml index 7464b9a507..eb8b8a24c6 100644 --- a/libraries-io/pom.xml +++ b/libraries-io/pom.xml @@ -5,18 +5,6 @@ 4.0.0 libraries-io libraries-io - - - - org.apache.maven.plugins - maven-compiler-plugin - - 17 - 17 - - - - com.baeldung @@ -51,8 +39,31 @@ opencsv ${opencsv.version} + + commons-io + commons-io + ${commons-io.version} + + + org.springframework + spring-web + ${spring.version} + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 17 + 17 + + + + + 0.1.55 @@ -60,9 +71,7 @@ 2.4 2.9.0 5.8 - 17 - 17 - UTF-8 + 4.3.8.RELEASE \ No newline at end of file diff --git a/libraries-4/src/test/java/com/baeldung/io/JavaDirectoryDeleteUnitTest.java b/libraries-io/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java similarity index 99% rename from libraries-4/src/test/java/com/baeldung/io/JavaDirectoryDeleteUnitTest.java rename to libraries-io/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java index c9c8242cd5..bf6c4d9e40 100644 --- a/libraries-4/src/test/java/com/baeldung/io/JavaDirectoryDeleteUnitTest.java +++ b/libraries-io/src/test/java/com/baeldung/java/io/JavaDirectoryDeleteUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.io; +package com.baeldung.java.io; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/libraries-reporting/.gitignore b/libraries-reporting/.gitignore new file mode 100644 index 0000000000..e594daf27a --- /dev/null +++ b/libraries-reporting/.gitignore @@ -0,0 +1,9 @@ +*.class + +# Folders # +/gensrc +/target + +# Packaged files # +*.jar +/bin/ diff --git a/libraries-reporting/README.md b/libraries-reporting/README.md new file mode 100644 index 0000000000..6d405911ab --- /dev/null +++ b/libraries-reporting/README.md @@ -0,0 +1,8 @@ +## Server + +This module contains articles about reporting libraries. + +### Relevant Articles: + +- [JasperReports with Spring](https://www.baeldung.com/spring-jasper) +- [Spring Yarg Integration](https://www.baeldung.com/spring-yarg) \ No newline at end of file diff --git a/libraries-reporting/pom.xml b/libraries-reporting/pom.xml new file mode 100644 index 0000000000..526f187af8 --- /dev/null +++ b/libraries-reporting/pom.xml @@ -0,0 +1,75 @@ + + + 4.0.0 + libraries-reporting + 0.0.1-SNAPSHOT + libraries-reporting + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.springframework.boot + spring-boot-starter + ${spring-boot-starter.version} + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + javax.servlet + servlet-api + ${javax.servlet.version} + + + net.sf.jasperreports + jasperreports + ${jasperreports.version} + + + commons-logging + commons-logging + + + + + com.haulmont.yarg + yarg + ${yarg.version} + + + org.olap4j + olap4j + + + + + + + 2.7.8 + 5.3.25 + 2.5 + 6.20.0 + 2.0.12 + + + \ No newline at end of file diff --git a/libraries-2/src/main/java/com/baeldung/jasperreports/Main.java b/libraries-reporting/src/main/java/com/baeldung/jasperreports/Main.java similarity index 100% rename from libraries-2/src/main/java/com/baeldung/jasperreports/Main.java rename to libraries-reporting/src/main/java/com/baeldung/jasperreports/Main.java diff --git a/libraries-2/src/main/java/com/baeldung/jasperreports/SimpleReportExporter.java b/libraries-reporting/src/main/java/com/baeldung/jasperreports/SimpleReportExporter.java similarity index 100% rename from libraries-2/src/main/java/com/baeldung/jasperreports/SimpleReportExporter.java rename to libraries-reporting/src/main/java/com/baeldung/jasperreports/SimpleReportExporter.java diff --git a/libraries-2/src/main/java/com/baeldung/jasperreports/SimpleReportFiller.java b/libraries-reporting/src/main/java/com/baeldung/jasperreports/SimpleReportFiller.java similarity index 100% rename from libraries-2/src/main/java/com/baeldung/jasperreports/SimpleReportFiller.java rename to libraries-reporting/src/main/java/com/baeldung/jasperreports/SimpleReportFiller.java diff --git a/libraries-2/src/main/java/com/baeldung/jasperreports/config/JasperRerportsSimpleConfig.java b/libraries-reporting/src/main/java/com/baeldung/jasperreports/config/JasperRerportsSimpleConfig.java similarity index 100% rename from libraries-2/src/main/java/com/baeldung/jasperreports/config/JasperRerportsSimpleConfig.java rename to libraries-reporting/src/main/java/com/baeldung/jasperreports/config/JasperRerportsSimpleConfig.java diff --git a/libraries-4/src/main/java/com/baeldung/yarg/DocumentController.java b/libraries-reporting/src/main/java/com/baeldung/yarg/DocumentController.java similarity index 99% rename from libraries-4/src/main/java/com/baeldung/yarg/DocumentController.java rename to libraries-reporting/src/main/java/com/baeldung/yarg/DocumentController.java index ff0d452108..9ae9b61ad1 100644 --- a/libraries-4/src/main/java/com/baeldung/yarg/DocumentController.java +++ b/libraries-reporting/src/main/java/com/baeldung/yarg/DocumentController.java @@ -5,6 +5,16 @@ */ package com.baeldung.yarg; +import java.io.File; +import java.io.IOException; + +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.FileUtils; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; + import com.haulmont.yarg.formatters.factory.DefaultFormatterFactory; import com.haulmont.yarg.loaders.factory.DefaultLoaderFactory; import com.haulmont.yarg.loaders.impl.JsonDataLoader; @@ -16,13 +26,6 @@ import com.haulmont.yarg.structure.ReportOutputType; import com.haulmont.yarg.structure.impl.BandBuilder; import com.haulmont.yarg.structure.impl.ReportBuilder; import com.haulmont.yarg.structure.impl.ReportTemplateBuilder; -import java.io.File; -import java.io.IOException; -import javax.servlet.http.HttpServletResponse; -import org.apache.commons.io.FileUtils; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; @RestController public class DocumentController { diff --git a/libraries-2/src/main/resources/employee-schema.sql b/libraries-reporting/src/main/resources/employee-schema.sql similarity index 100% rename from libraries-2/src/main/resources/employee-schema.sql rename to libraries-reporting/src/main/resources/employee-schema.sql diff --git a/libraries-2/src/main/resources/employeeEmailReport.jrxml b/libraries-reporting/src/main/resources/employeeEmailReport.jrxml similarity index 100% rename from libraries-2/src/main/resources/employeeEmailReport.jrxml rename to libraries-reporting/src/main/resources/employeeEmailReport.jrxml diff --git a/libraries-2/src/main/resources/employeeReport.jrxml b/libraries-reporting/src/main/resources/employeeReport.jrxml similarity index 100% rename from libraries-2/src/main/resources/employeeReport.jrxml rename to libraries-reporting/src/main/resources/employeeReport.jrxml diff --git a/java-spi/exchange-rate-impl/src/main/resources/logback.xml b/libraries-reporting/src/main/resources/logback.xml similarity index 100% rename from java-spi/exchange-rate-impl/src/main/resources/logback.xml rename to libraries-reporting/src/main/resources/logback.xml diff --git a/libraries-security/pom.xml b/libraries-security/pom.xml index 8a6dad6da2..8957996bad 100644 --- a/libraries-security/pom.xml +++ b/libraries-security/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -20,9 +20,8 @@ spring-boot-starter-web - org.springframework.security.oauth - spring-security-oauth2 - ${spring-security-oauth2.version} + org.springframework.boot + spring-boot-starter-oauth2-resource-server org.springframework @@ -68,6 +67,29 @@ jsch ${jsch.version} + + com.sun.xml.bind + jaxb-core + 2.3.0.1 + runtime + + + javax.xml.bind + jaxb-api + 2.3.1 + runtime + + + com.sun.xml.bind + jaxb-impl + 2.3.1 + runtime + + + org.springframework.security + spring-security-oauth2-authorization-server + 1.2.1 + org.apache.sshd sshd-core @@ -125,7 +147,6 @@ 1.68 0.1.55 2.5.1 - 2.4.0.RELEASE 1.4.0 diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java b/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java index 5b18567b2d..a5ff601ff5 100644 --- a/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java +++ b/libraries-security/src/main/java/com/baeldung/scribejava/ScribejavaApplication.java @@ -4,7 +4,6 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; - @SpringBootApplication @ServletComponentScan public class ScribejavaApplication { @@ -13,5 +12,4 @@ public class ScribejavaApplication { SpringApplication.run(ScribejavaApplication.class, args); } - } diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java index ffe4f0cc8a..4c63c70ef1 100644 --- a/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/GoogleController.java @@ -10,7 +10,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; @RestController public class GoogleController { diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/RBACController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/RBACController.java index 785f6228e8..0e747e2a22 100644 --- a/libraries-security/src/main/java/com/baeldung/scribejava/controller/RBACController.java +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/RBACController.java @@ -2,15 +2,14 @@ package com.baeldung.scribejava.controller; import java.io.IOException; -import javax.annotation.security.DeclareRoles; -import javax.annotation.security.RolesAllowed; -import javax.servlet.ServletException; -import javax.servlet.annotation.HttpConstraint; -import javax.servlet.annotation.ServletSecurity; -import javax.servlet.annotation.WebServlet; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.annotation.security.DeclareRoles; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.HttpConstraint; +import jakarta.servlet.annotation.ServletSecurity; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; @WebServlet(name="rbac", urlPatterns = {"/protected"}) @DeclareRoles("USER") diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java index bfcd6d960c..792b6f7020 100644 --- a/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/TwitterController.java @@ -6,7 +6,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Scanner; import java.util.concurrent.ExecutionException; diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java b/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java index 68a11250de..62aac896fc 100644 --- a/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java +++ b/libraries-security/src/main/java/com/baeldung/scribejava/controller/UserController.java @@ -10,7 +10,7 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import java.security.Principal; @RestController(value = "/user") diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java index 2c7162399b..498b258011 100644 --- a/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java +++ b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/AuthServiceConfig.java @@ -1,45 +1,103 @@ package com.baeldung.scribejava.oauth; +import java.util.UUID; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; - +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.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.oauth2.core.AuthorizationGrantType; +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.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; +import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer; +import org.springframework.security.oauth2.server.authorization.settings.ClientSettings; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; +import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher; @Configuration -@EnableAuthorizationServer -public class AuthServiceConfig extends AuthorizationServerConfigurerAdapter { +@EnableWebSecurity +public class AuthServiceConfig { - @Autowired - @Qualifier("authenticationManagerBean") - private AuthenticationManager authenticationManager; - - @Override - public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { - oauthServer.tokenKeyAccess("permitAll()") - .checkTokenAccess("isAuthenticated()"); + @Bean + public SecurityFilterChain securityFilter(HttpSecurity http) throws Exception { + http.headers( it -> it.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) + .csrf(AbstractHttpConfigurer::disable); + return http.build(); } - @Override - public void configure(ClientDetailsServiceConfigurer clients) throws Exception { - clients.inMemory() - .withClient("baeldung_api_key") - .secret("baeldung_api_secret") - .authorizedGrantTypes("password","refresh_token") - .scopes("read","write").autoApprove(true); + @Bean + public InMemoryUserDetailsManager userDetailsService() { + UserDetails user = User.withUsername("baeldung") + .password("scribejava") + .roles("USER") + .build(); + + return new InMemoryUserDetailsManager(user); + } + @Bean + public RegisteredClientRepository registeredClientRepository() { + RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString()) + .clientId("baeldung_api_key") + .clientSecret("baeldung_api_secret") + .authorizationGrantType(AuthorizationGrantType.PASSWORD) + .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) + .scope("read") + .scope("write") + .clientSettings(ClientSettings.builder().requireAuthorizationConsent(false).build()) + .build(); + + return new InMemoryRegisteredClientRepository(oidcClient); } - @Override - public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { - endpoints - .authenticationManager(authenticationManager) - .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST); + @Bean + @Order(1) + public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { + OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); + http.getConfigurer(OAuth2AuthorizationServerConfigurer.class) + .oidc(Customizer.withDefaults()); // Enable OpenID Connect 1.0 + http + // 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(); } + @Bean + @Order(2) + public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) + throws Exception { + http + .authorizeHttpRequests((authorize) -> authorize + .anyRequest().authenticated() + ) + // Form login handles the redirect to the login page from the + // authorization server filter chain + .formLogin(Customizer.withDefaults()); + + return http.build(); + } + + } diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java b/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java deleted file mode 100644 index 7aa51400ea..0000000000 --- a/libraries-security/src/main/java/com/baeldung/scribejava/oauth/WebSecurityConfig.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.baeldung.scribejava.oauth; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -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.WebSecurityConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; -import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; - -@Configuration -@EnableResourceServer -public class WebSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .headers().frameOptions().disable() - .and() - .csrf().disable(); - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication() - .withUser("baeldung") - .password("scribejava") - .roles("USER"); - } - - @Override - @Bean - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - - - @EnableResourceServer - @Configuration - public class ResourceServerConfig extends ResourceServerConfigurerAdapter { - - @Override - public void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .antMatchers("/user/me").authenticated() - .and() - .csrf().disable(); - } - } - -} diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java index fbcc39763c..497d6d469b 100644 --- a/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/GoogleService.java @@ -5,7 +5,7 @@ import com.github.scribejava.core.builder.ServiceBuilder; import com.github.scribejava.core.oauth.OAuth20Service; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; @Component public class GoogleService { diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java index 739c82172c..4397c8c7b6 100644 --- a/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/MyService.java @@ -5,7 +5,7 @@ import com.github.scribejava.core.builder.ServiceBuilder; import com.github.scribejava.core.oauth.OAuth20Service; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; @Component public class MyService { diff --git a/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java b/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java index df49f74679..c09bdf98d3 100644 --- a/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java +++ b/libraries-security/src/main/java/com/baeldung/scribejava/service/TwitterService.java @@ -5,7 +5,7 @@ import com.github.scribejava.core.builder.ServiceBuilder; import com.github.scribejava.core.oauth.OAuth10aService; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; @Component public class TwitterService { diff --git a/libraries-stream/.gitignore b/libraries-stream/.gitignore new file mode 100644 index 0000000000..e594daf27a --- /dev/null +++ b/libraries-stream/.gitignore @@ -0,0 +1,9 @@ +*.class + +# Folders # +/gensrc +/target + +# Packaged files # +*.jar +/bin/ diff --git a/libraries-stream/README.md b/libraries-stream/README.md new file mode 100644 index 0000000000..6aa5a28cd9 --- /dev/null +++ b/libraries-stream/README.md @@ -0,0 +1,11 @@ +## Server + +This module contains articles about stream libraries. + +### Relevant Articles: + +- [Merging Streams in Java](https://www.baeldung.com/java-merge-streams) +- [Guide to Java Parallel Collectors Library](https://www.baeldung.com/java-parallel-collectors) +- [DistinctBy in the Java Stream API](https://www.baeldung.com/java-streams-distinct-by) +- [Introduction to StreamEx](https://www.baeldung.com/streamex) +- [Introduction to Protonpack](https://www.baeldung.com/java-protonpack) \ No newline at end of file diff --git a/libraries-stream/pom.xml b/libraries-stream/pom.xml new file mode 100644 index 0000000000..8f00be3dab --- /dev/null +++ b/libraries-stream/pom.xml @@ -0,0 +1,59 @@ + + + 4.0.0 + libraries-stream + 0.0.1-SNAPSHOT + libraries-stream + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.jooq + jool + ${jool.version} + + + com.pivovarit + parallel-collectors + ${parallel-collectors.version} + + + io.vavr + vavr + ${vavr.version} + + + org.eclipse.collections + eclipse-collections + ${eclipse-collections.version} + + + one.util + streamex + ${streamex.version} + + + com.codepoetics + protonpack + ${protonpack.version} + + + + + 0.9.12 + 1.1.0 + 0.9.0 + 8.2.0 + 0.8.1 + 1.15 + + + \ No newline at end of file diff --git a/libraries-4/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java b/libraries-stream/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java similarity index 100% rename from libraries-4/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java rename to libraries-stream/src/main/java/com/baeldung/distinct/DistinctWithJavaFunction.java diff --git a/libraries-4/src/main/java/com/baeldung/distinct/Person.java b/libraries-stream/src/main/java/com/baeldung/distinct/Person.java similarity index 100% rename from libraries-4/src/main/java/com/baeldung/distinct/Person.java rename to libraries-stream/src/main/java/com/baeldung/distinct/Person.java diff --git a/libraries-5/src/main/java/com/baeldung/streamex/Role.java b/libraries-stream/src/main/java/com/baeldung/streamex/Role.java similarity index 100% rename from libraries-5/src/main/java/com/baeldung/streamex/Role.java rename to libraries-stream/src/main/java/com/baeldung/streamex/Role.java diff --git a/libraries-5/src/main/java/com/baeldung/streamex/StreamEX.java b/libraries-stream/src/main/java/com/baeldung/streamex/StreamEX.java similarity index 99% rename from libraries-5/src/main/java/com/baeldung/streamex/StreamEX.java rename to libraries-stream/src/main/java/com/baeldung/streamex/StreamEX.java index 56a3860f05..989b65bef6 100644 --- a/libraries-5/src/main/java/com/baeldung/streamex/StreamEX.java +++ b/libraries-stream/src/main/java/com/baeldung/streamex/StreamEX.java @@ -7,6 +7,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; + import one.util.streamex.DoubleStreamEx; import one.util.streamex.EntryStream; import one.util.streamex.IntStreamEx; diff --git a/libraries-5/src/main/java/com/baeldung/streamex/User.java b/libraries-stream/src/main/java/com/baeldung/streamex/User.java similarity index 100% rename from libraries-5/src/main/java/com/baeldung/streamex/User.java rename to libraries-stream/src/main/java/com/baeldung/streamex/User.java diff --git a/java-websocket/src/main/resources/logback.xml b/libraries-stream/src/main/resources/logback.xml similarity index 100% rename from java-websocket/src/main/resources/logback.xml rename to libraries-stream/src/main/resources/logback.xml diff --git a/libraries-4/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java b/libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java rename to libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithEclipseCollectionsUnitTest.java diff --git a/libraries-4/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java b/libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java rename to libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java index 936fd3e839..196c6603dd 100644 --- a/libraries-4/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java +++ b/libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithJavaFunctionUnitTest.java @@ -1,7 +1,7 @@ package com.baeldung.distinct; -import static org.junit.Assert.assertTrue; import static com.baeldung.distinct.DistinctWithJavaFunction.distinctByKey; +import static org.junit.Assert.assertTrue; import java.util.List; import java.util.stream.Collectors; diff --git a/libraries-4/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java b/libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java rename to libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithStreamexUnitTest.java diff --git a/libraries-4/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java b/libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java rename to libraries-stream/src/test/java/com/baeldung/distinct/DistinctWithVavrUnitTest.java diff --git a/libraries-4/src/test/java/com/baeldung/distinct/PersonDataGenerator.java b/libraries-stream/src/test/java/com/baeldung/distinct/PersonDataGenerator.java similarity index 100% rename from libraries-4/src/test/java/com/baeldung/distinct/PersonDataGenerator.java rename to libraries-stream/src/test/java/com/baeldung/distinct/PersonDataGenerator.java diff --git a/libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java b/libraries-stream/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java similarity index 100% rename from libraries-2/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java rename to libraries-stream/src/test/java/com/baeldung/parallel_collectors/ParallelCollectorsUnitTest.java diff --git a/libraries-6/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java b/libraries-stream/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java similarity index 99% rename from libraries-6/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java rename to libraries-stream/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java index c28248e52c..ed5fec254d 100644 --- a/libraries-6/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java +++ b/libraries-stream/src/test/java/com/baeldung/protonpack/ProtonpackUnitTest.java @@ -1,11 +1,9 @@ package com.baeldung.protonpack; -import com.codepoetics.protonpack.Indexed; -import com.codepoetics.protonpack.StreamUtils; -import com.codepoetics.protonpack.collectors.CollectorUtils; -import com.codepoetics.protonpack.collectors.NonUniqueValueException; -import com.codepoetics.protonpack.selectors.Selectors; -import org.junit.Test; +import static java.util.Arrays.asList; +import static java.util.Arrays.stream; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.util.List; import java.util.Optional; @@ -13,10 +11,13 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; -import static java.util.Arrays.asList; -import static java.util.Arrays.stream; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import org.junit.Test; + +import com.codepoetics.protonpack.Indexed; +import com.codepoetics.protonpack.StreamUtils; +import com.codepoetics.protonpack.collectors.CollectorUtils; +import com.codepoetics.protonpack.collectors.NonUniqueValueException; +import com.codepoetics.protonpack.selectors.Selectors; public class ProtonpackUnitTest { @Test diff --git a/libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsUnitTest.java b/libraries-stream/src/test/java/com/baeldung/stream/JoolMergeStreamsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/stream/JoolMergeStreamsUnitTest.java rename to libraries-stream/src/test/java/com/baeldung/stream/JoolMergeStreamsUnitTest.java diff --git a/libraries/src/test/java/com/baeldung/stream/MergeStreamsUnitTest.java b/libraries-stream/src/test/java/com/baeldung/stream/MergeStreamsUnitTest.java similarity index 100% rename from libraries/src/test/java/com/baeldung/stream/MergeStreamsUnitTest.java rename to libraries-stream/src/test/java/com/baeldung/stream/MergeStreamsUnitTest.java diff --git a/libraries-5/src/test/java/com/baeldung/streamex/StreamExMergeStreamsUnitTest.java b/libraries-stream/src/test/java/com/baeldung/streamex/StreamExMergeStreamsUnitTest.java similarity index 99% rename from libraries-5/src/test/java/com/baeldung/streamex/StreamExMergeStreamsUnitTest.java rename to libraries-stream/src/test/java/com/baeldung/streamex/StreamExMergeStreamsUnitTest.java index b267eaea9b..de474b825c 100644 --- a/libraries-5/src/test/java/com/baeldung/streamex/StreamExMergeStreamsUnitTest.java +++ b/libraries-stream/src/test/java/com/baeldung/streamex/StreamExMergeStreamsUnitTest.java @@ -1,13 +1,14 @@ package com.baeldung.streamex; -import one.util.streamex.StreamEx; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.junit.Assert.assertEquals; +import org.junit.Test; + +import one.util.streamex.StreamEx; public class StreamExMergeStreamsUnitTest { diff --git a/libraries-testing-2/README.md b/libraries-testing-2/README.md new file mode 100644 index 0000000000..e8fc854a13 --- /dev/null +++ b/libraries-testing-2/README.md @@ -0,0 +1,8 @@ +## Testing + +This module contains articles about test libraries. + +### Relevant articles + +- [Consumer Driven Contracts with Pact](https://www.baeldung.com/pact-junit-consumer-driven-contracts) +- - More articles: [[<-- prev]](../libraries-testing) diff --git a/libraries-testing-2/pom.xml b/libraries-testing-2/pom.xml new file mode 100644 index 0000000000..6e75df172f --- /dev/null +++ b/libraries-testing-2/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + libraries-testing-2 + libraries-testing-2 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../parent-boot-2 + + + + + au.com.dius + pact-jvm-provider-junit5_2.12 + ${pact.version} + + + au.com.dius + pact-jvm-consumer-junit5_2.12 + ${pact.version} + test + + + org.springframework + spring-web + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + target/mypacts + + + + + + + + 3.6.3 + + + \ No newline at end of file diff --git a/libraries-5/src/main/java/com/baeldung/pact/config/MainApplication.java b/libraries-testing-2/src/main/java/com/baeldung/pact/config/MainApplication.java similarity index 100% rename from libraries-5/src/main/java/com/baeldung/pact/config/MainApplication.java rename to libraries-testing-2/src/main/java/com/baeldung/pact/config/MainApplication.java diff --git a/libraries-5/src/main/java/com/baeldung/pact/web/controller/PactController.java b/libraries-testing-2/src/main/java/com/baeldung/pact/web/controller/PactController.java similarity index 100% rename from libraries-5/src/main/java/com/baeldung/pact/web/controller/PactController.java rename to libraries-testing-2/src/main/java/com/baeldung/pact/web/controller/PactController.java diff --git a/libraries-5/src/main/java/com/baeldung/pact/web/dto/PactDto.java b/libraries-testing-2/src/main/java/com/baeldung/pact/web/dto/PactDto.java similarity index 100% rename from libraries-5/src/main/java/com/baeldung/pact/web/dto/PactDto.java rename to libraries-testing-2/src/main/java/com/baeldung/pact/web/dto/PactDto.java diff --git a/libraries-5/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java b/libraries-testing-2/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java similarity index 100% rename from libraries-5/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java rename to libraries-testing-2/src/test/java/com/baeldung/pact/PactConsumerDrivenContractUnitTest.java diff --git a/libraries-5/src/test/java/com/baeldung/pact/PactProviderLiveTest.java b/libraries-testing-2/src/test/java/com/baeldung/pact/PactProviderLiveTest.java similarity index 100% rename from libraries-5/src/test/java/com/baeldung/pact/PactProviderLiveTest.java rename to libraries-testing-2/src/test/java/com/baeldung/pact/PactProviderLiveTest.java diff --git a/libraries-testing/README.md b/libraries-testing/README.md index 2c473e8aa6..d3f6bc7ea0 100644 --- a/libraries-testing/README.md +++ b/libraries-testing/README.md @@ -14,3 +14,4 @@ This module contains articles about test libraries. - [Introduction to DBUnit](https://www.baeldung.com/java-dbunit) - [Introduction to ArchUnit](https://www.baeldung.com/java-archunit-intro) - [Guide to the ModelAssert Library for JSON](https://www.baeldung.com/json-modelassert) +- More articles: [[more -->]](../libraries-testing-2) diff --git a/libraries/README.md b/libraries/README.md index 33c40ea67c..7e72292f45 100644 --- a/libraries/README.md +++ b/libraries/README.md @@ -8,14 +8,7 @@ The code examples related to different libraries are each in their own module. Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-modules) we already have separate modules. Please make sure to have a look at the existing modules in such cases. ### Relevant articles - -- [Introduction to Javatuples](https://www.baeldung.com/java-tuples) -- [Introduction to Javassist](https://www.baeldung.com/javassist) - [Intro to JaVers](https://www.baeldung.com/javers) -- [Merging Streams in Java](https://www.baeldung.com/java-merge-streams) - [Introduction to Quartz](https://www.baeldung.com/quartz) -- [How to Warm Up the JVM](https://www.baeldung.com/java-jvm-warmup) -- [Software Transactional Memory in Java Using Multiverse](https://www.baeldung.com/java-multiverse-stm) - [Locality-Sensitive Hashing in Java Using Java-LSH](https://www.baeldung.com/locality-sensitive-hashing) -- [Introduction to Neuroph](https://www.baeldung.com/neuroph) - More articles [[next -->]](/libraries-2) diff --git a/libraries/pom.xml b/libraries/pom.xml index 07a4853728..3ff912cae3 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -13,12 +13,6 @@ - - - org.beykery - neuroph - ${neuroph.version} - cglib @@ -35,16 +29,6 @@ commons-net ${commons-net.version} - - org.javatuples - javatuples - ${javatuples.version} - - - org.javassist - javassist - ${javaassist.version} - org.javers javers-core @@ -104,11 +88,6 @@ ${spring-mock-mvc.version} test - - org.multiverse - multiverse-core - ${multiverse.version} - pl.pragmatists JUnitParams @@ -120,16 +99,6 @@ quartz ${quartz.version} - - org.jooq - jool - ${jool.version} - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - info.debatty java-lsh @@ -264,11 +233,8 @@ 2.2 - 0.7.0 3.2.7 - 1.2 3.1.0 - 2.92 1.9.26 1.41.0 1.9.0 @@ -289,8 +255,6 @@ 4.3.8.RELEASE 3.0.3 2.3.0 - 3.29.2-GA - 0.9.12 3.6 2.6 diff --git a/lombok-modules/lombok-custom/pom.xml b/lombok-modules/lombok-custom/pom.xml index 1f7f630772..9a9293c288 100644 --- a/lombok-modules/lombok-custom/pom.xml +++ b/lombok-modules/lombok-custom/pom.xml @@ -58,7 +58,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${maven.compiler.source} ${maven.compiler.target} diff --git a/lombok-modules/pom.xml b/lombok-modules/pom.xml index 46d91462fb..e64f2e04ae 100644 --- a/lombok-modules/pom.xml +++ b/lombok-modules/pom.xml @@ -26,7 +26,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${maven.compiler.source} ${maven.compiler.target} diff --git a/maven-modules/maven-exec-plugin/pom.xml b/maven-modules/maven-exec-plugin/pom.xml index 370b344167..adaa96fd8f 100644 --- a/maven-modules/maven-exec-plugin/pom.xml +++ b/maven-modules/maven-exec-plugin/pom.xml @@ -45,7 +45,7 @@ 1.2.6 - 3.11.0 + 3.12.1 3.1.0 diff --git a/maven-modules/maven-generate-war/pom.xml b/maven-modules/maven-generate-war/pom.xml index d73ffe8b1d..1d7c79aa81 100644 --- a/maven-modules/maven-generate-war/pom.xml +++ b/maven-modules/maven-generate-war/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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.baeldung maven-generate-war 0.0.1-SNAPSHOT maven-generate-war @@ -60,7 +59,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${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 ae2eddb40f..7c604b121b 100644 --- a/maven-modules/maven-integration-test/pom.xml +++ b/maven-modules/maven-integration-test/pom.xml @@ -269,7 +269,6 @@ 3.4.0 3.0.2 - 3.11.0 3.1.2 1.1 3.0.0 diff --git a/maven-modules/maven-unused-dependencies/pom.xml b/maven-modules/maven-unused-dependencies/pom.xml index d98fe83a0e..e11428d25b 100644 --- a/maven-modules/maven-unused-dependencies/pom.xml +++ b/maven-modules/maven-unused-dependencies/pom.xml @@ -41,7 +41,7 @@ 3.2.2 1.7.25 3.1.2 - 3.1 + 3.12.1 \ No newline at end of file diff --git a/lagom/.gitignore b/microservices-modules/lagom/.gitignore similarity index 100% rename from lagom/.gitignore rename to microservices-modules/lagom/.gitignore diff --git a/lagom/README.md b/microservices-modules/lagom/README.md similarity index 100% rename from lagom/README.md rename to microservices-modules/lagom/README.md diff --git a/lagom/build.sbt b/microservices-modules/lagom/build.sbt similarity index 100% rename from lagom/build.sbt rename to microservices-modules/lagom/build.sbt diff --git a/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java b/microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java similarity index 100% rename from lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java rename to microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/api/GreetingService.java diff --git a/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java b/microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java similarity index 100% rename from lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java rename to microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingCommand.java diff --git a/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java b/microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java similarity index 100% rename from lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java rename to microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEntity.java diff --git a/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java b/microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java similarity index 100% rename from lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java rename to microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingEvent.java diff --git a/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java b/microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java similarity index 100% rename from lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java rename to microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceImpl.java diff --git a/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java b/microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java similarity index 100% rename from lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java rename to microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingServiceModule.java diff --git a/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java b/microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java similarity index 100% rename from lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java rename to microservices-modules/lagom/greeting-api/src/main/java/com/baeldung/lagom/helloworld/greeting/impl/GreetingState.java diff --git a/jersey/src/main/resources/logback.xml b/microservices-modules/lagom/greeting-api/src/main/resources/logback.xml similarity index 100% rename from jersey/src/main/resources/logback.xml rename to microservices-modules/lagom/greeting-api/src/main/resources/logback.xml diff --git a/lagom/greeting-impl/bin/application.conf b/microservices-modules/lagom/greeting-impl/src/main/resources/application.conf similarity index 100% rename from lagom/greeting-impl/bin/application.conf rename to microservices-modules/lagom/greeting-impl/src/main/resources/application.conf diff --git a/jmeter/src/main/resources/logback.xml b/microservices-modules/lagom/greeting-impl/src/main/resources/logback.xml similarity index 100% rename from jmeter/src/main/resources/logback.xml rename to microservices-modules/lagom/greeting-impl/src/main/resources/logback.xml diff --git a/lagom/project/build.properties b/microservices-modules/lagom/project/build.properties similarity index 100% rename from lagom/project/build.properties rename to microservices-modules/lagom/project/build.properties diff --git a/lagom/project/plugins.sbt b/microservices-modules/lagom/project/plugins.sbt similarity index 100% rename from lagom/project/plugins.sbt rename to microservices-modules/lagom/project/plugins.sbt diff --git a/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java b/microservices-modules/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java similarity index 100% rename from lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java rename to microservices-modules/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherService.java diff --git a/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java b/microservices-modules/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java similarity index 100% rename from lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java rename to microservices-modules/lagom/weather-api/src/main/java/com/baeldung/lagom/helloworld/weather/api/WeatherStats.java diff --git a/lagom/greeting-api/src/main/resources/logback.xml b/microservices-modules/lagom/weather-api/src/main/resources/logback.xml similarity index 100% rename from lagom/greeting-api/src/main/resources/logback.xml rename to microservices-modules/lagom/weather-api/src/main/resources/logback.xml diff --git a/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java b/microservices-modules/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java similarity index 100% rename from lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java rename to microservices-modules/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceImpl.java diff --git a/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java b/microservices-modules/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java similarity index 100% rename from lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java rename to microservices-modules/lagom/weather-impl/src/main/java/com/baeldung/lagom/helloworld/weather/impl/WeatherServiceModule.java diff --git a/lagom/weather-impl/bin/application.conf b/microservices-modules/lagom/weather-impl/src/main/resources/application.conf similarity index 100% rename from lagom/weather-impl/bin/application.conf rename to microservices-modules/lagom/weather-impl/src/main/resources/application.conf diff --git a/lagom/greeting-impl/src/main/resources/logback.xml b/microservices-modules/lagom/weather-impl/src/main/resources/logback.xml similarity index 100% rename from lagom/greeting-impl/src/main/resources/logback.xml rename to microservices-modules/lagom/weather-impl/src/main/resources/logback.xml diff --git a/microservices-modules/pom.xml b/microservices-modules/pom.xml index a9cd8d2cd9..4b46e7cd1b 100644 --- a/microservices-modules/pom.xml +++ b/microservices-modules/pom.xml @@ -15,6 +15,7 @@ helidon + micronaut microprofile msf4j diff --git a/microservices-modules/rest-express/pom.xml b/microservices-modules/rest-express/pom.xml index 1b22bb8117..be1c142a94 100644 --- a/microservices-modules/rest-express/pom.xml +++ b/microservices-modules/rest-express/pom.xml @@ -2,14 +2,13 @@ - - microservices-modules - com.baeldung - 1.0.0-SNAPSHOT - 4.0.0 - + rest-express + 1.0.0-SNAPSHOT rest-express + jar + A Basic, MongoDB-backed Service Suite + https://github.com/RestExpress/RestExpress-Scaffold - A Basic, MongoDB-backed Service Suite - https://github.com/RestExpress/RestExpress-Scaffold - 1.0.0-SNAPSHOT - rest-express - jar + + + microservices-modules + com.baeldung + 1.0.0-SNAPSHOT + diff --git a/osgi/pom.xml b/osgi/pom.xml index 16b1f5d106..238f50293b 100644 --- a/osgi/pom.xml +++ b/osgi/pom.xml @@ -71,7 +71,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} ${maven.compiler.source} ${maven.compiler.target} diff --git a/parent-boot-3/pom.xml b/parent-boot-3/pom.xml index f1ab699c83..099828de19 100644 --- a/parent-boot-3/pom.xml +++ b/parent-boot-3/pom.xml @@ -225,7 +225,7 @@ 3.2.0 - 3.10.1 + 3.12.1 3.3.0 3.3.0 2.22.2 diff --git a/parent-java/README.md b/parent-java/README.md deleted file mode 100644 index 1b14b7cfc1..0000000000 --- a/parent-java/README.md +++ /dev/null @@ -1,3 +0,0 @@ -## Parent Java - -This is a parent module for all projects using Java \ No newline at end of file diff --git a/parent-java/pom.xml b/parent-java/pom.xml deleted file mode 100644 index 03cafac55b..0000000000 --- a/parent-java/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - 4.0.0 - parent-java - 0.0.1-SNAPSHOT - parent-java - pom - Parent for all java modules - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - - com.google.guava - guava - ${guava.version} - - - commons-io - commons-io - ${commons-io.version} - - - org.openjdk.jmh - jmh-core - ${jmh-core.version} - - - org.openjdk.jmh - jmh-generator-annprocess - ${jmh-generator.version} - - - - - 3.2.0 - - - \ No newline at end of file diff --git a/parent-spring-6/pom.xml b/parent-spring-6/pom.xml index 7aaffb5483..7418c019c4 100644 --- a/parent-spring-6/pom.xml +++ b/parent-spring-6/pom.xml @@ -35,7 +35,7 @@ - 6.0.12 + 6.1.2 diff --git a/patterns-modules/axon/pom.xml b/patterns-modules/axon/pom.xml index 473a1b0e15..4d83f8f9e6 100644 --- a/patterns-modules/axon/pom.xml +++ b/patterns-modules/axon/pom.xml @@ -51,6 +51,7 @@ io.projectreactor reactor-core + ${reactor.version} com.h2database @@ -70,6 +71,7 @@ io.projectreactor reactor-test + ${reactor.version} test @@ -114,6 +116,7 @@ 4.6.3 3.4.8 + 3.6.0 \ No newline at end of file diff --git a/patterns-modules/ddd/pom.xml b/patterns-modules/ddd/pom.xml index 80147c29c6..1eb1f90741 100644 --- a/patterns-modules/ddd/pom.xml +++ b/patterns-modules/ddd/pom.xml @@ -10,29 +10,11 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 - - - - org.junit - junit-bom - ${junit-jupiter.version} - pom - import - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - @@ -88,12 +70,15 @@ de.flapdoodle.embed de.flapdoodle.embed.mongo + ${de.flapdoodle.embed.mongo.version} test + com.baeldung.ddd.PersistingDddAggregatesApplication 1.0.1 + 4.11.1 \ No newline at end of file diff --git a/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java index 81ae3bbd19..e0e7ea9a4e 100644 --- a/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java +++ b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrder.java @@ -4,12 +4,12 @@ import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.ElementCollection; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "order_table") diff --git a/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java index a3b50f0502..bf1d7020be 100644 --- a/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java +++ b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaOrderLine.java @@ -1,7 +1,7 @@ package com.baeldung.ddd.order.jpa; -import javax.persistence.Embeddable; -import javax.persistence.Embedded; +import jakarta.persistence.Embeddable; +import jakarta.persistence.Embedded; @Embeddable class JpaOrderLine { diff --git a/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java index 1d2ae5230a..30b074b2e4 100644 --- a/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java +++ b/patterns-modules/ddd/src/main/java/com/baeldung/ddd/order/jpa/JpaProduct.java @@ -2,7 +2,7 @@ package com.baeldung.ddd.order.jpa; import java.math.BigDecimal; -import javax.persistence.Embeddable; +import jakarta.persistence.Embeddable; @Embeddable class JpaProduct { diff --git a/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java index ec107d635b..76dc438b63 100644 --- a/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java +++ b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/AddProductRequest.java @@ -4,7 +4,7 @@ import com.baeldung.dddhexagonalspring.domain.Product; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -import javax.validation.constraints.NotNull; +import jakarta.validation.constraints.NotNull; public class AddProductRequest { @NotNull private Product product; diff --git a/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java index 8c51fbe479..ff81908811 100644 --- a/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java +++ b/patterns-modules/ddd/src/main/java/com/baeldung/dddhexagonalspring/application/request/CreateOrderRequest.java @@ -4,7 +4,7 @@ import com.baeldung.dddhexagonalspring.domain.Product; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; -import javax.validation.constraints.NotNull; +import jakarta.validation.constraints.NotNull; public class CreateOrderRequest { @NotNull private Product product; diff --git a/persistence-modules/core-java-persistence-3/pom.xml b/persistence-modules/core-java-persistence-3/pom.xml index 26ac2a5218..60562859a7 100644 --- a/persistence-modules/core-java-persistence-3/pom.xml +++ b/persistence-modules/core-java-persistence-3/pom.xml @@ -1,15 +1,19 @@ - + 4.0.0 com.baeldung.core-java-persistence-3 core-java-persistence-3 - core-java-persistence-3 0.1.0-SNAPSHOT + core-java-persistence-3 jar + com.baeldung persistence-modules 1.0.0-SNAPSHOT + com.h2database @@ -22,6 +26,7 @@ ${commons-dbutils.version} + 2.1.214 1.8.1 diff --git a/persistence-modules/core-java-persistence/pom.xml b/persistence-modules/core-java-persistence/pom.xml index 5d5c36ef01..20553da4e8 100644 --- a/persistence-modules/core-java-persistence/pom.xml +++ b/persistence-modules/core-java-persistence/pom.xml @@ -62,7 +62,7 @@ 2.9.0 - 5.0.1 + 5.1.0 0.9.5.5 3.0.4 6.0.6 diff --git a/persistence-modules/fauna/pom.xml b/persistence-modules/fauna/pom.xml index 4c37c2ae9e..3a34ad3ca1 100644 --- a/persistence-modules/fauna/pom.xml +++ b/persistence-modules/fauna/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -59,6 +59,8 @@ 4.2.0 + 17 + com.baeldung.faunablog.FaunaBlogApplication \ No newline at end of file diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/WebSecurityConfiguration.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/WebSecurityConfiguration.java index 12770c47ce..005f1751ea 100644 --- a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/WebSecurityConfiguration.java +++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/WebSecurityConfiguration.java @@ -5,15 +5,17 @@ import com.faunadb.client.FaunaClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.Customizer; +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.configurers.CsrfConfigurer; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity -@EnableGlobalMethodSecurity(prePostEnabled = true) +@EnableMethodSecurity public class WebSecurityConfiguration { @Autowired @@ -21,13 +23,11 @@ public class WebSecurityConfiguration { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.csrf() - .disable(); - http.authorizeRequests() - .antMatchers("/**") - .permitAll() - .and() - .httpBasic(); + http.csrf(CsrfConfigurer::disable) + .authorizeHttpRequests(requests -> requests + .requestMatchers("/**") + .permitAll()) + .httpBasic(Customizer.withDefaults()); return http.build(); } diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsController.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsController.java index e8e6316ea8..37701ae531 100644 --- a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsController.java +++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsController.java @@ -6,7 +6,6 @@ import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; -import org.springframework.web.server.ResponseStatusException; import java.util.List; import java.util.concurrent.ExecutionException; diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsService.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsService.java index 5143a24b28..5865c1af49 100644 --- a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsService.java +++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/posts/PostsService.java @@ -6,7 +6,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.time.Instant; -import java.util.Collection; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; diff --git a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/users/FaunaUserDetailsService.java b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/users/FaunaUserDetailsService.java index 2e88aaa477..d0ddea3f69 100644 --- a/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/users/FaunaUserDetailsService.java +++ b/persistence-modules/fauna/src/main/java/com/baeldung/faunablog/users/FaunaUserDetailsService.java @@ -6,6 +6,8 @@ import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; import java.util.concurrent.ExecutionException; @@ -30,8 +32,9 @@ public class FaunaUserDetailsService implements UserDetailsService { if (userData == null) { throw new UsernameNotFoundException("User not found"); } + PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); - return User.withDefaultPasswordEncoder() + return User.builder().passwordEncoder(encoder::encode) .username(userData.at("data", "username").to(String.class).orNull()) .password(userData.at("data", "password").to(String.class).orNull()) .roles("USER") diff --git a/persistence-modules/flyway-repair/pom.xml b/persistence-modules/flyway-repair/pom.xml index 1a5384a916..f7fa4f4d5e 100644 --- a/persistence-modules/flyway-repair/pom.xml +++ b/persistence-modules/flyway-repair/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -31,6 +31,7 @@ org.flywaydb flyway-maven-plugin + ${flyway-maven-plugin.version} org.springframework.boot @@ -73,6 +74,10 @@ src/main/resources/application-${spring-boot.run.profiles}.properties + 10.4.0 + 17 + 17 + 17 \ No newline at end of file diff --git a/persistence-modules/flyway-repair/src/test/java/FlywayAppIntegrationTest.java b/persistence-modules/flyway-repair/src/test/java/FlywayAppIntegrationTest.java new file mode 100644 index 0000000000..e2280ac2e4 --- /dev/null +++ b/persistence-modules/flyway-repair/src/test/java/FlywayAppIntegrationTest.java @@ -0,0 +1,38 @@ +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Set; + +import javax.sql.DataSource; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.flywaycallbacks.FlywayApplication; + +@RunWith(SpringRunner.class) +@ContextConfiguration(classes = { FlywayApplication.class }) +public class FlywayAppIntegrationTest { + + @Autowired + private DataSource dataSource; + + @Test + public void testAllMigrationsExecuted() throws SQLException { + DatabaseMetaData metadata = dataSource.getConnection() + .getMetaData(); + ResultSet resultSet = metadata.getTables(null, null, null, new String[] { "TABLE" }); + Set tables = Set.of("TABLE_ONE", "TABLE_TWO", "TABLE_THREE", "TABLE_FOUR"); + int migrations = 0; + while (resultSet.next()) { + if (tables.contains(resultSet.getString("TABLE_NAME"))) { + migrations++; + } + } + Assert.assertEquals(migrations, 4); + } +} diff --git a/persistence-modules/flyway/pom.xml b/persistence-modules/flyway/pom.xml index df35f85bfb..07a2925356 100644 --- a/persistence-modules/flyway/pom.xml +++ b/persistence-modules/flyway/pom.xml @@ -63,7 +63,7 @@ - 8.5.13 + 10.2.0 \ No newline at end of file diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/HibernateUtil.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/HibernateUtil.java index 641b80b412..bbf8f46e82 100644 --- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/HibernateUtil.java +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/HibernateUtil.java @@ -11,6 +11,7 @@ import org.hibernate.service.ServiceRegistry; import com.baeldung.hibernate.exception.persistentobject.entity.Article; import com.baeldung.hibernate.exception.persistentobject.entity.Author; import com.baeldung.hibernate.exception.persistentobject.entity.Book; +import com.baeldung.hibernate.namedparameternotbound.Person; public class HibernateUtil { private static SessionFactory sessionFactory; @@ -34,6 +35,7 @@ public class HibernateUtil { configuration.addAnnotatedClass(Book.class); configuration.addAnnotatedClass(Author.class); configuration.addAnnotatedClass(Article.class); + configuration.addAnnotatedClass(Person.class); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build(); diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/namedparameternotbound/Person.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/namedparameternotbound/Person.java new file mode 100644 index 0000000000..e5f5ebc4a0 --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/namedparameternotbound/Person.java @@ -0,0 +1,38 @@ +package com.baeldung.hibernate.namedparameternotbound; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +@Entity +public class Person { + + @Id + private int id; + private String firstName; + private String lastName; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + +} diff --git a/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/namedparameternotbound/NamedParameterNotBoundExceptionUnitTest.java b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/namedparameternotbound/NamedParameterNotBoundExceptionUnitTest.java new file mode 100644 index 0000000000..f16a89917d --- /dev/null +++ b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/namedparameternotbound/NamedParameterNotBoundExceptionUnitTest.java @@ -0,0 +1,53 @@ +package com.baeldung.hibernate.namedparameternotbound; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.hibernate.QueryException; +import org.hibernate.Session; +import org.hibernate.query.Query; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.baeldung.hibernate.exception.persistentobject.HibernateUtil; + +class NamedParameterNotBoundExceptionUnitTest { + + private static Session session; + + @BeforeAll + static void init() { + session = HibernateUtil.getSessionFactory() + .openSession(); + session.beginTransaction(); + } + + @AfterAll + static void clear() { + session.close(); + } + + @Test + void whenSettingValueToNamedParameter_thenDoNotThrowQueryException() { + Query query = session.createQuery("FROM Person p WHERE p.firstName = :firstName", Person.class); + query.setParameter("firstName", "Azhrioun"); + + assertNotNull(query.list()); + } + + @Test + void whenNotSettingValueToNamedParameter_thenThrowQueryException() { + Exception exception = assertThrows(QueryException.class, () -> { + Query query = session.createQuery("FROM Person p WHERE p.firstName = :firstName", Person.class); + query.list(); + }); + + String expectedMessage = "Named parameter not bound"; + String actualMessage = exception.getMessage(); + + assertTrue(actualMessage.contains(expectedMessage)); + } + +} diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java index 699890c457..56165d7880 100644 --- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java +++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/CustomClassIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.hibernate; +import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; @@ -74,5 +75,13 @@ public class CustomClassIntegrationTest { assertEquals("Sales", result.getDepartmentName()); } + @Test + public void whenCastResultQueryToList_ThenListOfResultIsReturned() { + Query query = session.createQuery("select new com.baeldung.hibernate.pojo.Result(m.name, m.department.name) " + + "from DeptEmployee m"); + List results = query.list(); + assertNotNull(results); + assertEquals(1, results.size()); + } } diff --git a/persistence-modules/java-harperdb/README.md b/persistence-modules/java-harperdb/README.md new file mode 100644 index 0000000000..99a91e00ed --- /dev/null +++ b/persistence-modules/java-harperdb/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Working With HarperDB and Java](https://www.baeldung.com/java-harperdb) diff --git a/persistence-modules/java-harperdb/pom.xml b/persistence-modules/java-harperdb/pom.xml index 318f4b7460..7340aa4dbc 100644 --- a/persistence-modules/java-harperdb/pom.xml +++ b/persistence-modules/java-harperdb/pom.xml @@ -31,6 +31,7 @@ java-harperdb ${haperdb-driver.version} system + ${project.basedir}/lib/cdata.jdbc.harperdb.jar diff --git a/persistence-modules/jooq/pom.xml b/persistence-modules/jooq/pom.xml index b9229377ab..d0f1b733a4 100644 --- a/persistence-modules/jooq/pom.xml +++ b/persistence-modules/jooq/pom.xml @@ -31,20 +31,34 @@ jooq-codegen ${jooq.version} + + + + commons-io + commons-io + 2.15.1 + test + + org.postgresql postgresql ${postgresql.version} + runtime com.h2database h2 ${h2.version} + runtime - 3.13.4 + 17 + 17 + 17 + 3.19.0 \ No newline at end of file diff --git a/persistence-modules/jooq/src/test/java/com/baeldung/jooq/CodeGenerationIntegrationTest.java b/persistence-modules/jooq/src/test/java/com/baeldung/jooq/CodeGenerationIntegrationTest.java new file mode 100644 index 0000000000..3ca0919eaa --- /dev/null +++ b/persistence-modules/jooq/src/test/java/com/baeldung/jooq/CodeGenerationIntegrationTest.java @@ -0,0 +1,75 @@ +package com.baeldung.jooq; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Files; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.codegen.GenerationTool; +import org.jooq.impl.DSL; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.jooq.model.tables.Article; +import com.baeldung.jooq.model.tables.Author; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.apache.commons.io.FileUtils; + +public class CodeGenerationIntegrationTest { + + static DSLContext context; + + @BeforeClass + public static void setup() throws SQLException { + Connection conn = DriverManager.getConnection("jdbc:h2:mem:tes;INIT=CREATE SCHEMA IF NOT EXISTS \"public\""); + context = DSL.using(conn, SQLDialect.H2); + + context.createTable(Author.AUTHOR) + .columns( + Author.AUTHOR.ID, + Author.AUTHOR.FIRST_NAME, + Author.AUTHOR.LAST_NAME, + Author.AUTHOR.AGE + ) + .execute(); + context.createTable(Article.ARTICLE) + .columns( + Article.ARTICLE.ID, + Article.ARTICLE.TITLE, + Article.ARTICLE.DESCRIPTION, + Article.ARTICLE.AUTHOR_ID + ) + .execute(); + } + + @AfterClass + public static void cleanup() throws IOException { + File generatedDirectory = new File("src/main/java/com/baeldung/jooq/generated"); + FileUtils.deleteDirectory(generatedDirectory); + } + + @Test + public void testClassGenerationFromExistingDatabase() throws Exception { + + File generatedDirectory = new File("src/main/java/com/baeldung/jooq/generated"); + + assertFalse(generatedDirectory.exists()); + + URL jooqConfigURL = getClass().getClassLoader().getResource("jooq-config.xml"); + assertNotNull(jooqConfigURL); + File file = new File(jooqConfigURL.getFile()); + GenerationTool.generate(Files.readString(file.toPath())); + + assertTrue(generatedDirectory.exists()); + } +} diff --git a/persistence-modules/jooq/src/test/java/com/baeldung/jooq/CrudLiveTest.java b/persistence-modules/jooq/src/test/java/com/baeldung/jooq/CrudIntegrationTest.java similarity index 99% rename from persistence-modules/jooq/src/test/java/com/baeldung/jooq/CrudLiveTest.java rename to persistence-modules/jooq/src/test/java/com/baeldung/jooq/CrudIntegrationTest.java index d41344c08e..0d8df27ccc 100644 --- a/persistence-modules/jooq/src/test/java/com/baeldung/jooq/CrudLiveTest.java +++ b/persistence-modules/jooq/src/test/java/com/baeldung/jooq/CrudIntegrationTest.java @@ -28,7 +28,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -public class CrudLiveTest { +public class CrudIntegrationTest { static DSLContext context; diff --git a/persistence-modules/jooq/src/test/resources/jooq-config.xml b/persistence-modules/jooq/src/test/resources/jooq-config.xml new file mode 100644 index 0000000000..2eed2fbe80 --- /dev/null +++ b/persistence-modules/jooq/src/test/resources/jooq-config.xml @@ -0,0 +1,26 @@ + + + + + org.h2.Driver + jdbc:h2:mem:tes + + + + + + org.jooq.codegen.JavaGenerator + + + org.jooq.meta.h2.H2Database + public + .* + + + + + com.baeldung.jooq.generated + src/main/java + + + \ No newline at end of file diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 41ff596ccf..6caedb3273 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -60,7 +60,7 @@ solr spring-boot-persistence-2 - + spring-boot-persistence-3 spring-boot-persistence spring-boot-persistence-h2 @@ -108,7 +108,7 @@ spring-jpa spring-jpa-2 spring-jdbc - spring-jdbc-2 + spring-jdbc-2 spring-mybatis spring-persistence-simple diff --git a/persistence-modules/questdb/pom.xml b/persistence-modules/questdb/pom.xml index 5e803f739a..cb32c5248f 100644 --- a/persistence-modules/questdb/pom.xml +++ b/persistence-modules/questdb/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + persistence-modules + 1.0.0-SNAPSHOT diff --git a/persistence-modules/scylladb/pom.xml b/persistence-modules/scylladb/pom.xml index 66dd89afa9..2ce777edaa 100644 --- a/persistence-modules/scylladb/pom.xml +++ b/persistence-modules/scylladb/pom.xml @@ -10,12 +10,13 @@ Sample ScyllaDB Project 1.17.6 + true com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 diff --git a/persistence-modules/sirix/pom.xml b/persistence-modules/sirix/pom.xml index 85379dc566..1d8853c200 100644 --- a/persistence-modules/sirix/pom.xml +++ b/persistence-modules/sirix/pom.xml @@ -12,9 +12,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + persistence-modules + 1.0.0-SNAPSHOT diff --git a/persistence-modules/spring-boot-mysql/pom.xml b/persistence-modules/spring-boot-mysql/pom.xml index 6c19b92314..182babc6c5 100644 --- a/persistence-modules/spring-boot-mysql/pom.xml +++ b/persistence-modules/spring-boot-mysql/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -43,7 +43,6 @@ org.springframework.boot spring-boot-maven-plugin - 2.1.5.RELEASE diff --git a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Application.java b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Application.java index d69f66fc7a..e3df121b24 100644 --- a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Application.java +++ b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/Application.java @@ -1,9 +1,9 @@ package com.baeldung.boot; +import jakarta.annotation.PostConstruct; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import javax.annotation.PostConstruct; import java.util.TimeZone; @SpringBootApplication diff --git a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/User.java b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/User.java index 55cb97dec2..f20fdc46e8 100644 --- a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/User.java +++ b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/User.java @@ -1,9 +1,10 @@ package com.baeldung.boot; + import org.springframework.data.annotation.CreatedDate; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.Date; @Entity diff --git a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/jpa/Employee.java b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/jpa/Employee.java index 28869d0ac1..d397b0b7e9 100644 --- a/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/jpa/Employee.java +++ b/persistence-modules/spring-boot-mysql/src/main/java/com/baeldung/boot/jpa/Employee.java @@ -1,7 +1,7 @@ package com.baeldung.boot.jpa; -import javax.persistence.*; +import jakarta.persistence.*; import java.io.Serializable; import java.time.LocalDate; import java.util.Date; diff --git a/persistence-modules/spring-boot-mysql/src/main/resources/application.yml b/persistence-modules/spring-boot-mysql/src/main/resources/application.yml index d70c21aad2..b1586f91d5 100644 --- a/persistence-modules/spring-boot-mysql/src/main/resources/application.yml +++ b/persistence-modules/spring-boot-mysql/src/main/resources/application.yml @@ -1,6 +1,7 @@ spring: - profiles: - active: "dev2" + config: + activate: + on-profile: "dev2" main: banner-mode: "off" jpa: @@ -14,7 +15,9 @@ spring: --- spring: - profiles: "dev1" + config: + activate: + on-profile: "dev1" datasource: url: jdbc:mysql://localhost:3306/test? username: root @@ -23,7 +26,9 @@ spring: --- spring: - profiles: "dev2" + config: + activate: + on-profile: "dev2" datasource: url: >- jdbc:mysql://localhost:3306/test_db?sslMode=VERIFY_CA& diff --git a/persistence-modules/spring-boot-persistence-3/pom.xml b/persistence-modules/spring-boot-persistence-3/pom.xml index 5e8ad64a7a..eb0507ca56 100644 --- a/persistence-modules/spring-boot-persistence-3/pom.xml +++ b/persistence-modules/spring-boot-persistence-3/pom.xml @@ -59,8 +59,11 @@ + - 2.1.8.RELEASE + 3.2.0 + 2.0.9 + 1.4.14 \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Account.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Account.java index d422c30a0e..2d3bdc6f9a 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Account.java +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Account.java @@ -1,11 +1,16 @@ package com.baeldung.countrows.entity; -import javax.persistence.*; - -import java.security.PrivateKey; import java.sql.Timestamp; -import java.time.Instant; -import java.util.Date; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.OneToOne; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; @Entity @Table(name = "ACCOUNTS") diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Permission.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Permission.java index 9acedf0558..4f45fb47a6 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Permission.java +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/entity/Permission.java @@ -1,6 +1,11 @@ package com.baeldung.countrows.entity; -import javax.persistence.*; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; @Entity @Table(name = "PERMISSIONS") diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/AccountRepository.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/AccountRepository.java index 422962ce45..b293cecce7 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/AccountRepository.java +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/repository/AccountRepository.java @@ -4,13 +4,9 @@ import com.baeldung.countrows.entity.Account; import com.baeldung.countrows.entity.Permission; 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; import java.sql.Timestamp; -import java.util.Date; -import java.util.List; @Repository public interface AccountRepository extends JpaRepository { diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/service/AccountStatsLogic.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/service/AccountStatsLogic.java index e4e716b4ce..cc5d69f848 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/service/AccountStatsLogic.java +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/countrows/service/AccountStatsLogic.java @@ -2,16 +2,10 @@ package com.baeldung.countrows.service; import java.sql.Timestamp; import java.text.ParseException; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import javax.persistence.criteria.*; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -20,6 +14,14 @@ import com.baeldung.countrows.entity.Permission; import com.baeldung.countrows.repository.AccountRepository; import com.baeldung.countrows.repository.PermissionRepository; +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceContext; +import jakarta.persistence.Query; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; + @Service public class AccountStatsLogic { @Autowired diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientDatabase.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientDatabase.java index d8d178a4d5..e5bef58d8d 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientDatabase.java +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/dsrouting/ClientDatabase.java @@ -1,7 +1,5 @@ package com.baeldung.dsrouting; public enum ClientDatabase { - CLIENT_A, CLIENT_B - } diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/largeresultset/LargeResultSetApplication.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/largeresultset/LargeResultSetApplication.java index d592894226..c2a94b8fce 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/largeresultset/LargeResultSetApplication.java +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/largeresultset/LargeResultSetApplication.java @@ -5,7 +5,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class LargeResultSetApplication { - public static void main(String[] args) { SpringApplication.run(LargeResultSetApplication.class, args); } diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/largeresultset/Student.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/largeresultset/Student.java index 283d0f032d..753cff02cb 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/largeresultset/Student.java +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/largeresultset/Student.java @@ -1,8 +1,9 @@ package com.baeldung.largeresultset; -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 Student { diff --git a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/largeresultset/service/StudentService.java b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/largeresultset/service/StudentService.java index e65fc34849..403054f6bd 100644 --- a/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/largeresultset/service/StudentService.java +++ b/persistence-modules/spring-boot-persistence-3/src/main/java/com/baeldung/largeresultset/service/StudentService.java @@ -3,8 +3,6 @@ package com.baeldung.largeresultset.service; import java.util.List; import java.util.stream.Stream; -import javax.persistence.EntityManager; - import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Slice; @@ -14,6 +12,8 @@ import org.springframework.transaction.annotation.Transactional; import com.baeldung.largeresultset.Student; import com.baeldung.largeresultset.StudentRepository; +import jakarta.persistence.EntityManager; + @Service public class StudentService { private static final int BATCH_SIZE = 5; diff --git a/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTest.java b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTest.java index af825601aa..e3a4cbf816 100644 --- a/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTest.java +++ b/persistence-modules/spring-boot-persistence-3/src/test/java/com/baeldung/boot/countrows/accountstatslogic/AccountStatsUnitTest.java @@ -4,9 +4,7 @@ import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import java.sql.Timestamp; import java.text.ParseException; -import java.text.SimpleDateFormat; import java.time.Instant; -import java.util.Date; import java.util.UUID; import org.junit.jupiter.api.AfterEach; diff --git a/persistence-modules/spring-data-cassandra-reactive/pom.xml b/persistence-modules/spring-data-cassandra-reactive/pom.xml index cddb62186b..41f184e233 100644 --- a/persistence-modules/spring-data-cassandra-reactive/pom.xml +++ b/persistence-modules/spring-data-cassandra-reactive/pom.xml @@ -23,6 +23,7 @@ io.projectreactor reactor-core + ${reactor.version} org.springframework.boot @@ -45,6 +46,7 @@ io.projectreactor reactor-test + ${reactor.version} test @@ -57,6 +59,7 @@ 4.3.1.0 + 3.6.0 \ No newline at end of file diff --git a/persistence-modules/spring-data-jdbc/pom.xml b/persistence-modules/spring-data-jdbc/pom.xml index 630fe141b3..9128c70b98 100644 --- a/persistence-modules/spring-data-jdbc/pom.xml +++ b/persistence-modules/spring-data-jdbc/pom.xml @@ -7,9 +7,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -36,4 +36,8 @@ + + true + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java index ceb7a968a4..b2f026fa0c 100644 --- a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java +++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springdatajdbcintro/repository/PersonRepository.java @@ -3,7 +3,6 @@ package com.baeldung.springdatajdbcintro.repository; import com.baeldung.springdatajdbcintro.entity.Person; import org.springframework.data.jdbc.repository.query.Modifying; import org.springframework.data.jdbc.repository.query.Query; -import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/Todo.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/Todo.java index 56f513027b..1dbe75d91f 100644 --- a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/Todo.java +++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/todos/Todo.java @@ -1,9 +1,9 @@ package com.baeldung.springmultipledatasources.todos; -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 Todo { diff --git a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/Topic.java b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/Topic.java index 390300ff1a..49b33d9b96 100644 --- a/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/Topic.java +++ b/persistence-modules/spring-data-jdbc/src/main/java/com/baeldung/springmultipledatasources/topics/Topic.java @@ -1,9 +1,9 @@ package com.baeldung.springmultipledatasources.topics; -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 Topic { diff --git a/persistence-modules/spring-data-jpa-enterprise-2/README.md b/persistence-modules/spring-data-jpa-enterprise-2/README.md index 8e154f6b75..0c1e9968bc 100644 --- a/persistence-modules/spring-data-jpa-enterprise-2/README.md +++ b/persistence-modules/spring-data-jpa-enterprise-2/README.md @@ -3,7 +3,8 @@ This module contains articles about Spring Data JPA used in enterprise applications such as transactions, sessions, naming conventions and more ### Relevant Articles: - +- [Custom Naming Convention with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-custom-naming) +- [Working with Lazy Element Collections in JPA](https://www.baeldung.com/java-jpa-lazy-collections) ### Eclipse Config diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/ElementCollectionApplication.java diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Employee.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Employee.java similarity index 87% rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Employee.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Employee.java index 8b98164d63..9bc0663016 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Employee.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Employee.java @@ -1,9 +1,14 @@ package com.baeldung.elementcollection.model; -import javax.persistence.*; import java.util.List; import java.util.Objects; +import javax.persistence.CollectionTable; +import javax.persistence.ElementCollection; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.JoinColumn; + @Entity public class Employee { @Id diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Phone.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Phone.java similarity index 99% rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Phone.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Phone.java index d73d30c47a..15d05aea98 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/model/Phone.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/model/Phone.java @@ -1,8 +1,9 @@ package com.baeldung.elementcollection.model; -import javax.persistence.Embeddable; import java.util.Objects; +import javax.persistence.Embeddable; + @Embeddable public class Phone { private String type; diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java similarity index 99% rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java index 49180c35eb..996cac7cd9 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/elementcollection/repository/EmployeeRepository.java @@ -1,14 +1,16 @@ package com.baeldung.elementcollection.repository; -import com.baeldung.elementcollection.model.Employee; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; +import java.util.HashMap; +import java.util.Map; import javax.persistence.EntityGraph; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; -import java.util.HashMap; -import java.util.Map; + +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.elementcollection.model.Employee; @Repository public class EmployeeRepository { diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/Person.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/Person.java similarity index 94% rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/Person.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/Person.java index cfb6e67c2c..35dd2dc226 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/Person.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/Person.java @@ -1,6 +1,5 @@ package com.baeldung.namingstrategy; -import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/PersonRepository.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/PersonRepository.java similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/PersonRepository.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/PersonRepository.java diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategy.java diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategy.java diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/SpringDataJpaNamingConventionApplication.java diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategy.java diff --git a/persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java b/persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/main/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategy.java diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java similarity index 99% rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java index 306798aa68..ed2bb97252 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/elementcollection/ElementCollectionIntegrationTest.java @@ -1,8 +1,10 @@ package com.baeldung.elementcollection; -import com.baeldung.elementcollection.model.Employee; -import com.baeldung.elementcollection.model.Phone; -import com.baeldung.elementcollection.repository.EmployeeRepository; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +import java.util.Arrays; + import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -12,10 +14,9 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; -import java.util.Arrays; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; +import com.baeldung.elementcollection.model.Employee; +import com.baeldung.elementcollection.model.Phone; +import com.baeldung.elementcollection.repository.EmployeeRepository; @RunWith(SpringRunner.class) @SpringBootTest(classes = ElementCollectionApplication.class) diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java similarity index 99% rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java index 71a4dbda3f..b3225175ca 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -1,5 +1,17 @@ package com.baeldung.namingstrategy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,17 +22,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfigur import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("quoted-lower-case-naming-strategy.properties") class QuotedLowerCaseNamingStrategyH2IntegrationTest { diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java similarity index 99% rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java index 6b1c984600..b21fdf9edd 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -1,5 +1,17 @@ package com.baeldung.namingstrategy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,17 +22,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfigur import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("quoted-lower-case-naming-strategy-on-postgres.properties") class QuotedLowerCaseNamingStrategyPostgresLiveTest { diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java similarity index 99% rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java index f819327a5c..74f82f0d39 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -1,5 +1,17 @@ package com.baeldung.namingstrategy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,17 +22,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfigur import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("quoted-upper-case-naming-strategy.properties") class QuotedUpperCaseNamingStrategyH2IntegrationTest { diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java similarity index 99% rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java index bd23b81b4b..6741b09366 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/QuotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -1,5 +1,17 @@ package com.baeldung.namingstrategy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,17 +22,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfigur import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("quoted-upper-case-naming-strategy-on-postgres.properties") class QuotedUpperCaseNamingStrategyPostgresLiveTest { diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java similarity index 99% rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java index 1850fea173..dbbccdd61d 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyH2IntegrationTest.java @@ -1,5 +1,17 @@ package com.baeldung.namingstrategy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,17 +22,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfigur import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("spring-physical-naming-strategy.properties") class SpringPhysicalNamingStrategyH2IntegrationTest { diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java similarity index 99% rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java index e26ebb148d..760dacdaa2 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/SpringPhysicalNamingStrategyPostgresLiveTest.java @@ -1,5 +1,17 @@ package com.baeldung.namingstrategy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,17 +22,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfigur import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("spring-physical-naming-strategy-on-postgres.properties") class SpringPhysicalNamingStrategyPostgresLiveTest { diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java similarity index 98% rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java index 6311c42e93..d0e86384b8 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyH2IntegrationTest.java @@ -1,5 +1,17 @@ package com.baeldung.namingstrategy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,18 +22,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfigur import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("unquoted-lower-case-naming-strategy.properties") class UnquotedLowerCaseNamingStrategyH2IntegrationTest { diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java similarity index 99% rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java index 033a213cf5..121b184a3c 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedLowerCaseNamingStrategyPostgresLiveTest.java @@ -1,5 +1,17 @@ package com.baeldung.namingstrategy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,17 +22,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfigur import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("unquoted-lower-case-naming-strategy-on-postgres.properties") class UnquotedLowerCaseNamingStrategyPostgresLiveTest { diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java similarity index 99% rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java index 7af8001854..b4f25605bd 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyH2IntegrationTest.java @@ -1,5 +1,17 @@ package com.baeldung.namingstrategy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,17 +22,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfigur import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("unquoted-upper-case-naming-strategy.properties") class UnquotedUpperCaseNamingStrategyH2IntegrationTest { diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java similarity index 99% rename from persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java index 0151e7ece4..7ecd4cc80e 100644 --- a/persistence-modules/spring-data-jpa-enterprise/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java +++ b/persistence-modules/spring-data-jpa-enterprise-2/src/test/java/com/baeldung/namingstrategy/UnquotedUpperCaseNamingStrategyPostgresLiveTest.java @@ -1,5 +1,17 @@ package com.baeldung.namingstrategy; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.Query; + import org.hibernate.exception.SQLGrammarException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,17 +22,6 @@ import org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfigur import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.TestPropertySource; -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import java.math.BigInteger; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; - @DataJpaTest(excludeAutoConfiguration = TestDatabaseAutoConfiguration.class) @TestPropertySource("unquoted-upper-case-naming-strategy-on-postgres.properties") class UnquotedUpperCaseNamingStrategyPostgresLiveTest { diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy-on-postgres.properties diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/quoted-lower-case-naming-strategy.properties diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy-on-postgres.properties diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/quoted-upper-case-naming-strategy.properties diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy-on-postgres.properties diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/spring-physical-naming-strategy.properties diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy-on-postgres.properties diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/unquoted-lower-case-naming-strategy.properties diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy-on-postgres.properties diff --git a/persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties b/persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties similarity index 100% rename from persistence-modules/spring-data-jpa-enterprise/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties rename to persistence-modules/spring-data-jpa-enterprise-2/src/test/resources/com/baeldung/namingstrategy/unquoted-upper-case-naming-strategy.properties diff --git a/persistence-modules/spring-data-jpa-enterprise/README.md b/persistence-modules/spring-data-jpa-enterprise/README.md index b563fa46d4..c48a519a87 100644 --- a/persistence-modules/spring-data-jpa-enterprise/README.md +++ b/persistence-modules/spring-data-jpa-enterprise/README.md @@ -7,8 +7,6 @@ This module contains articles about Spring Data JPA used in enterprise applicati - [Spring Data Java 8 Support](https://www.baeldung.com/spring-data-java-8) - [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) -- [Working with Lazy Element Collections in JPA](https://www.baeldung.com/java-jpa-lazy-collections) -- [Custom Naming Convention with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-custom-naming) - [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) diff --git a/persistence-modules/spring-data-jpa-query-2/pom.xml b/persistence-modules/spring-data-jpa-query-2/pom.xml index 62bf7f0314..6ef1adad14 100644 --- a/persistence-modules/spring-data-jpa-query-2/pom.xml +++ b/persistence-modules/spring-data-jpa-query-2/pom.xml @@ -1,7 +1,7 @@ + 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 spring-data-jpa-query-2 spring-data-jpa-query-2 diff --git a/persistence-modules/spring-data-jpa-query-3/pom.xml b/persistence-modules/spring-data-jpa-query-3/pom.xml index 1dff3024f6..5ea69791af 100644 --- a/persistence-modules/spring-data-jpa-query-3/pom.xml +++ b/persistence-modules/spring-data-jpa-query-3/pom.xml @@ -8,8 +8,20 @@ 0.15 + + + + org.apache.maven.plugins + maven-compiler-plugin + + 9 + 9 + + + + - + com.baeldung parent-boot-2 0.0.1-SNAPSHOT @@ -34,12 +46,16 @@ org.springframework.boot spring-boot-starter-web - org.springframework.boot spring-boot-starter-test test + + org.springframework.boot + spring-boot-starter-webflux + test + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerService.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerService.java index 73affeb1a1..2fc29e097b 100644 --- a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerService.java +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/paging/CustomerService.java @@ -1,5 +1,6 @@ package com.baeldung.spring.data.jpa.paging; +import java.util.Collections; import java.util.List; import org.springframework.data.domain.Page; @@ -29,6 +30,13 @@ public class CustomerService { return new PageImpl<>(pageContent, pageRequest, allCustomers.size()); } + public List getCustomerListFromPage(int page, int size) { + Pageable pageRequest = createPageRequestUsing(page, size); + Page allCustomers = customerRepository.findAll(pageRequest); + + return allCustomers.hasContent() ? allCustomers.getContent() : Collections.emptyList(); + } + private Pageable createPageRequestUsing(int page, int size) { return PageRequest.of(page, size); } diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/querymap/AppConfig.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/querymap/AppConfig.java new file mode 100644 index 0000000000..abcf5f3690 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/querymap/AppConfig.java @@ -0,0 +1,8 @@ +package com.baeldung.spring.data.jpa.querymap; + +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AppConfig { + +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/querymap/User.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/querymap/User.java new file mode 100644 index 0000000000..1b9630dafc --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/querymap/User.java @@ -0,0 +1,93 @@ +package com.baeldung.spring.data.jpa.querymap; + +import java.util.Objects; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue + private Long id; + private String firstName; + private String lastName; + + public User() { + } + + public User(final String firstName, final String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } + + public User(final Long id, final String firstName, final String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + final User user = (User) o; + + if (!Objects.equals(id, user.id)) { + return false; + } + if (!Objects.equals(firstName, user.firstName)) { + return false; + } + return Objects.equals(lastName, user.lastName); + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (firstName != null ? firstName.hashCode() : 0); + result = 31 * result + (lastName != null ? lastName.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "User{" + + "id=" + id + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + '}'; + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/querymap/UserRepository.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/querymap/UserRepository.java new file mode 100644 index 0000000000..c4b23fa678 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/querymap/UserRepository.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.data.jpa.querymap; + +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.transaction.Transactional; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.util.Streamable; + +public interface UserRepository extends JpaRepository { + + String FIND_ALL_USERS = "select u from User u"; + + @Query(FIND_ALL_USERS) + Streamable findAllAsStreamable(); + + @Query(FIND_ALL_USERS) + Stream findAllAsStream(); + + @Query(FIND_ALL_USERS) + Users findAllUsers(); + + default Map findAllAsMapUsingCollection() { + return findAll().stream().collect(Collectors.toMap(User::getId, Function.identity())); + } + + default Map findAllAsMapUsingStreamable() { + return findAllAsStreamable().stream().collect(Collectors.toMap(User::getId, Function.identity())); + } + + @Transactional + default Map findAllAsMapUsingStream() { + return findAllAsStream().collect(Collectors.toMap(User::getId, Function.identity())); + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/querymap/Users.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/querymap/Users.java new file mode 100644 index 0000000000..acf05726b0 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/querymap/Users.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.data.jpa.querymap; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import org.springframework.data.util.Streamable; + +public class Users implements Streamable { + + private final Streamable userStreamable; + + public Users(Streamable userStreamable) { + this.userStreamable = userStreamable; + } + + @Override + public Iterator iterator() { + return userStreamable.iterator(); + } + + public Map getUserIdToUserMap() { + return stream().collect(Collectors.toMap(User::getId, Function.identity())); + } + + public List getAllUsersWithShortNames(int maxNameLength) { + return stream() + .filter(s -> s.getFirstName().length() <= maxNameLength) + .collect(Collectors.toList()); + } + + public Map> groupUsersAlphabetically() { + return stream().collect(Collectors.groupingBy(s -> getFristCharacter(s.getFirstName()))); + } + + private Character getFristCharacter(final String string) { + return string.substring(0, 1).toUpperCase().charAt(0); + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/NewsApplication.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/NewsApplication.java new file mode 100644 index 0000000000..04dca159c7 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/NewsApplication.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.data.jpa.spel; + +import java.util.Locale; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.web.servlet.LocaleResolver; +import org.springframework.web.servlet.i18n.SessionLocaleResolver; + +@SpringBootApplication +public class NewsApplication { + + public static void main(String[] args) { + SpringApplication.run(NewsApplication.class, args); + } + + @Bean + public LocaleResolver localeResolver() { + SessionLocaleResolver slr = new SessionLocaleResolver(); + slr.setDefaultLocale(Locale.US); + return slr; + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/config/WebMvcConfig.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/config/WebMvcConfig.java new file mode 100644 index 0000000000..6569e31af4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/config/WebMvcConfig.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.data.jpa.spel.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + @Override + public void addInterceptors(InterceptorRegistry registry) { + LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); + localeChangeInterceptor.setParamName("locale"); + registry.addInterceptor(localeChangeInterceptor); + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/controller/ArticleController.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/controller/ArticleController.java new file mode 100644 index 0000000000..4e092fe150 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/controller/ArticleController.java @@ -0,0 +1,26 @@ +package com.baeldung.spring.data.jpa.spel.controller; + +import com.baeldung.spring.data.jpa.spel.entity.Article; +import com.baeldung.spring.data.jpa.spel.repository.ArticleRepository; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/articles") +public class ArticleController { + + private final ArticleRepository articleRepository; + + @Autowired + public ArticleController(final ArticleRepository articleRepository) { + this.articleRepository = articleRepository; + } + + @GetMapping + List
getAllArticlesWithNativeQuery() { + return articleRepository.findAllArticlesUsingLocaleWithNativeQuery(); + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/entity/Article.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/entity/Article.java new file mode 100644 index 0000000000..93a0e3b9a9 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/entity/Article.java @@ -0,0 +1,111 @@ +package com.baeldung.spring.data.jpa.spel.entity; + +import java.util.Objects; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + + +@Entity(name = "articles") +@Table(name = "articles") +public class Article { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + private String title; + private String content; + private String language; + + public Article() { + } + + public Article(final String title, final String content, final String language) { + this.title = title; + this.content = content; + this.language = language; + } + + public Article(final Long id, final String title, final String content, final String language) { + this.id = id; + this.title = title; + this.content = content; + this.language = language; + } + + public Long getId() { + return id; + } + + public void setId(final Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(final String title) { + this.title = title; + } + + public String getContent() { + return content; + } + + public void setContent(final String content) { + this.content = content; + } + + public String getLanguage() { + return language; + } + + public void setLanguage(final String language) { + this.language = language; + } + + @Override + public String toString() { + return "News{" + + "id=" + id + + ", title='" + title + '\'' + + ", content='" + content + '\'' + + ", language=" + language + + '}'; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + final Article article = (Article) o; + + if (!Objects.equals(id, article.id)) { + return false; + } + if (!Objects.equals(title, article.title)) { + return false; + } + if (!Objects.equals(content, article.content)) { + return false; + } + return Objects.equals(language, article.language); + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (title != null ? title.hashCode() : 0); + result = 31 * result + (content != null ? content.hashCode() : 0); + result = 31 * result + (language != null ? language.hashCode() : 0); + return result; + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/entity/ArticleWrapper.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/entity/ArticleWrapper.java new file mode 100644 index 0000000000..046a9c558a --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/entity/ArticleWrapper.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.data.jpa.spel.entity; + +public class ArticleWrapper { + + private final Article article; + + public ArticleWrapper(Article article) { + this.article = article; + } + + public Article getArticle() { + return article; + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/entity/Language.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/entity/Language.java new file mode 100644 index 0000000000..6fea0e06f4 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/entity/Language.java @@ -0,0 +1,56 @@ +package com.baeldung.spring.data.jpa.spel.entity; + +import java.util.Objects; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; + +@Entity +public class Language { + + @Id + @Column(name = "iso_code") + private String isoCode; + + public Language() { + } + + public Language(final String isoCode) { + this.isoCode = isoCode; + } + + public String getIsoCode() { + return isoCode; + } + + public void setIsoCode(final String isoCode) { + this.isoCode = isoCode; + } + + @Override + public String toString() { + return "Language{" + + "isoCode='" + isoCode + '\'' + + '}'; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + final Language language = (Language) o; + + return Objects.equals(isoCode, language.isoCode); + } + + @Override + public int hashCode() { + return isoCode != null ? isoCode.hashCode() : 0; + } +} + diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/extension/LocaleContextHolderExtension.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/extension/LocaleContextHolderExtension.java new file mode 100644 index 0000000000..c0a334440f --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/extension/LocaleContextHolderExtension.java @@ -0,0 +1,20 @@ +package com.baeldung.spring.data.jpa.spel.extension; + +import java.util.Locale; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.data.spel.spi.EvaluationContextExtension; +import org.springframework.stereotype.Component; + +@Component +public class LocaleContextHolderExtension implements EvaluationContextExtension { + + @Override + public String getExtensionId() { + return "locale"; + } + + @Override + public Locale getRootObject() { + return LocaleContextHolder.getLocale(); + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/repository/ArticleRepository.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/repository/ArticleRepository.java new file mode 100644 index 0000000000..26549f67f5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/repository/ArticleRepository.java @@ -0,0 +1,78 @@ +package com.baeldung.spring.data.jpa.spel.repository; + +import com.baeldung.spring.data.jpa.spel.entity.Article; +import com.baeldung.spring.data.jpa.spel.entity.ArticleWrapper; +import java.util.List; +import javax.transaction.Transactional; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface ArticleRepository extends BaseNewsApplicationRepository { + + + @Modifying + @Transactional + @Query(value = "INSERT INTO articles (id, title, content, language) " + + "VALUES (?1, ?2, ?3, ?4)", + nativeQuery = true) + void saveWithPositionalArguments(Long id, String title, String content, String language); + + + @Modifying + @Transactional + @Query(value = "INSERT INTO articles (id, title, content, language) " + + "VALUES (?#{[0]}, ?#{[1]}, ?#{[2]}, ?#{[3]})", + nativeQuery = true) + void saveWithPositionalSpELArguments(long id, String title, String content, String language); + + @Modifying + @Transactional + @Query(value = "INSERT INTO articles (id, title, content, language) " + + "VALUES (?#{[0]}, ?#{[1]}, ?#{[2] ?: 'Empty Article'}, ?#{[3]})", + nativeQuery = true) + void saveWithPositionalSpELArgumentsWithEmptyCheck(long id, String title, String content, String language); + + @Modifying + @Transactional + @Query(value = "INSERT INTO articles (id, title, content, language) " + + "VALUES (:id, :title, :content, :language)", + nativeQuery = true) + void saveWithNamedArguments(@Param("id") long id, @Param("title") String title, + @Param("content") String content, @Param("language") String language); + + @Modifying + @Transactional + @Query(value = "INSERT INTO articles (id, title, content, language) " + + "VALUES (:#{#id}, :#{#title}, :#{#content}, :#{#language})", + nativeQuery = true) + void saveWithNamedSpELArguments(@Param("id") long id, @Param("title") String title, + @Param("content") String content, @Param("language") String language); + + @Modifying + @Transactional + @Query(value = "INSERT INTO articles (id, title, content, language) " + + "VALUES (:#{#id}, :#{#title}, :#{#content}, :#{#language.toLowerCase()})", + nativeQuery = true) + void saveWithNamedSpELArgumentsAndLowerCaseLanguage(@Param("id") long id, @Param("title") String title, + @Param("content") String content, @Param("language") String language); + + @Modifying + @Transactional + @Query(value = "INSERT INTO articles (id, title, content, language) " + + "VALUES (:#{#article.id}, :#{#article.title}, :#{#article.content}, :#{#article.language})", + nativeQuery = true) + void saveWithSingleObjectSpELArgument(@Param("article") Article article); + + @Modifying + @Transactional + @Query(value = "INSERT INTO articles (id, title, content, language) " + + "VALUES (:#{#wrapper.article.id}, :#{#wrapper.article.title}, :#{#wrapper.article.content}, :#{#wrapper.article.language})", + nativeQuery = true) + void saveWithSingleWrappedObjectSpELArgument(@Param("wrapper") ArticleWrapper articleWrapper); + + + @Query(value = "SELECT * FROM articles WHERE language = :#{locale.language}", + nativeQuery = true) + List
findAllArticlesUsingLocaleWithNativeQuery(); +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/repository/BaseNewsApplicationRepository.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/repository/BaseNewsApplicationRepository.java new file mode 100644 index 0000000000..e76995eaa3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/spel/repository/BaseNewsApplicationRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.data.jpa.spel.repository; + +import com.baeldung.spring.data.jpa.spel.entity.Article; +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.NoRepositoryBean; + +@NoRepositoryBean +public interface BaseNewsApplicationRepository extends JpaRepository { + + @Query(value = "select e from #{#entityName} e") + List
findAllEntitiesUsingEntityPlaceholder(); + + @Query(value = "SELECT * FROM #{#entityName}", nativeQuery = true) + List
findAllEntitiesUsingEntityPlaceholderWithNativeQuery(); +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/paging/CustomerServiceUnitTest.java b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/paging/CustomerServiceUnitTest.java index 1a34822527..cd5cbdcd60 100644 --- a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/paging/CustomerServiceUnitTest.java +++ b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/paging/CustomerServiceUnitTest.java @@ -1,14 +1,17 @@ package com.baeldung.spring.data.jpa.paging; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.List; import java.util.stream.Collectors; -import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; @@ -16,6 +19,8 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; @ExtendWith(MockitoExtension.class) public class CustomerServiceUnitTest { @@ -46,12 +51,7 @@ public class CustomerServiceUnitTest { private static final List PAGE_4_CONTENTS = Arrays.asList("Penny", "Queen", "Rob", "Sue", "Tammy"); - private static final List EMPTY_PAGE = Arrays.asList(); - - @BeforeEach - void setup() { - when(customerRepository.findAll()).thenReturn(ALL_CUSTOMERS); - } + private static final List EMPTY_PAGE = Collections.emptyList(); private static Collection testIO() { return Arrays.asList(new Object[][] { @@ -66,6 +66,7 @@ public class CustomerServiceUnitTest { @ParameterizedTest @MethodSource("testIO") void givenAListOfCustomers_whenGetCustomers_thenReturnsDesiredDataAlongWithPagingInformation(int page, int size, List expectedNames, long expectedTotalElements, long expectedTotalPages) { + when(customerRepository.findAll()).thenReturn(ALL_CUSTOMERS); Page customers = customerService.getCustomers(page, size); List names = customers.getContent() .stream() @@ -77,4 +78,27 @@ public class CustomerServiceUnitTest { assertEquals(expectedTotalElements, customers.getTotalElements()); assertEquals(expectedTotalPages, customers.getTotalPages()); } + + @Test + void givenAPageOfCustomers_whenGetCustomerList_thenReturnsList() { + Page pagedResponse = new PageImpl(ALL_CUSTOMERS.subList(0, 5)); + when(customerRepository.findAll(any(Pageable.class))).thenReturn(pagedResponse); + + List customers = customerService.getCustomerListFromPage(0, 5); + List customerNames = customers.stream() + .map(Customer::getName) + .collect(Collectors.toList()); + + assertEquals(PAGE_1_CONTENTS.size(), customers.size()); + assertEquals(PAGE_1_CONTENTS, customerNames); + } + + @Test + void givenAnEmptyPageOfCustomers_whenGetCustomerList_thenReturnsEmptyList() { + Page emptyPage = Page.empty(); + when(customerRepository.findAll(any(Pageable.class))).thenReturn(emptyPage); + List customers = customerService.getCustomerListFromPage(0, 5); + + assertThat(customers).isEmpty(); + } } diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/querymap/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/querymap/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..7f7c3899fe --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/querymap/UserRepositoryIntegrationTest.java @@ -0,0 +1,114 @@ +package com.baeldung.spring.data.jpa.querymap; + + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assumptions.assumeThat; + +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest(classes = AppConfig.class, properties = { + "spring.jpa.defer-datasource-initialization=true", + "spring.sql.init.data-locations=classpath:user-map-query-dml.sql" +}) +@DisplayName("Given: ") +class UserRepositoryIntegrationTest { + + public static final int NUMBER_OF_USERS = 50; + + @Autowired + private UserRepository repository; + + @Test + @DisplayName("repository is present") + void whenContextStartsRepositoryIsPresent() { + assumeThat(repository).isNotNull(); + } + + @Test + @DisplayName("data is loaded") + void whenUserPersistedUserCanBeFetched() { + final List users = repository.findAll(); + assumeThat(users).hasSize(NUMBER_OF_USERS); + } + + @Nested + @DisplayName("When: ") + class When { + + @Test + @DisplayName("fetch all users in a Map with Collection all of them are present") + void fetchUsersInMapUsingCollectionsThenAllOfThemPresent() { + final Map users = repository.findAllAsMapUsingCollection(); + validateUserIdToUserMap(users); + } + + @Test + @DisplayName("fetch all users in a Map with Streamable all of them are present") + void fetchUsersInMapUsingStreamableThenAllOfThemPresent() { + final Map users = repository.findAllAsMapUsingStreamable(); + validateUserIdToUserMap(users); + } + + @Test + @DisplayName("fetch all users in a Map with Stream all of them are present") + void fetchUsersInMapUsingStreamThenAllOfThemPresent() { + final Map users = repository.findAllAsMapUsingStream(); + validateUserIdToUserMap(users); + } + + @Test + @DisplayName("fetch all users in a Map with Streamable wrapper all of them are present") + void fetchUsersInMapUsingStreamableWrapperThenAllOfThemPresent() { + final Users streamableWrapper = repository.findAllUsers(); + final Map users = streamableWrapper.getUserIdToUserMap(); + validateUserIdToUserMap(users); + } + + @Test + @DisplayName("fetch all users in a Map with Streamable wrapper " + + "with a filter, all of them are present") + void fetchUsersInMapUsingStreamableWrapperWithFilterThenAllOfThemPresent() { + final Users users = repository.findAllUsers(); + final int maxNameLength = 4; + final List actual = users.getAllUsersWithShortNames(maxNameLength); + User[] expected = { + new User(9L, "Moe", "Oddy"), + new User(25L, "Lane", "Endricci"), + new User(26L, "Doro", "Kinforth"), + new User(34L, "Otho", "Rowan"), + new User(39L, "Mel", "Moffet") + }; + assertThat(actual).containsExactly(expected); + } + + @Test + @DisplayName("fetch all users in a Map with Streamable wrapper " + + "and grouping all of them are present") + void fetchUsersInMapUsingStreamableWrapperAndGroupingThenAllOfThemPresent() { + final Users users = repository.findAllUsers(); + final Map> alphabeticalGrouping = users.groupUsersAlphabetically(); + final List actual = alphabeticalGrouping.get('A'); + User[] expected = { + new User(2L, "Auroora", "Oats"), + new User(4L, "Alika", "Capin"), + new User(20L, "Artus", "Rickards"), + new User(27L, "Antonina", "Vivian")}; + assertThat(actual).containsExactly(expected); + } + + } + + private static void validateUserIdToUserMap(final Map users) { + assertThat(users.values()).hasSize(NUMBER_OF_USERS); + users.forEach((id, user) -> { + assertThat(user.getId()).isEqualTo(id); + }); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/spel/controller/ArticleControllerIntegrationTest.java b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/spel/controller/ArticleControllerIntegrationTest.java new file mode 100644 index 0000000000..7d3af20fae --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/spel/controller/ArticleControllerIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.spring.data.jpa.spel.controller; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import com.baeldung.spring.data.jpa.spel.NewsApplication; +import com.baeldung.spring.data.jpa.spel.entity.Article; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +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.test.web.reactive.server.WebTestClient; + +@SpringBootTest(classes = NewsApplication.class, + webEnvironment = WebEnvironment.RANDOM_PORT, + properties = { + "spring.jpa.show-sql=true", + "spring.jpa.generate-ddl=true", + "spring.jpa.defer-datasource-initialization=true", + "spring.sql.init.data-locations=classpath:articles-dml.sql" + }) +class ArticleControllerIntegrationTest { + + @Autowired + private ArticleController articleController; + @Autowired + private WebTestClient webTestClient; + + @Test + void whenApplicationStartBeansArePresent() { + assertNotNull(articleController); + assertNotNull(webTestClient); + } + + @ParameterizedTest + @CsvSource({"eng,2", "fr,2", "esp,2", "deu, 2", "jp,0"}) + void whenAskForNewsGetAllNewsInSpecificLanguageBasedOnLocale(String language, int expectedResultSize) { + webTestClient.get().uri("/articles?locale=" + language) + .exchange() + .expectStatus().isOk() + .expectBodyList(Article.class) + .hasSize(expectedResultSize); + } + + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/spel/repository/ArticleRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/spel/repository/ArticleRepositoryIntegrationTest.java new file mode 100644 index 0000000000..f7f9cb996e --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/spel/repository/ArticleRepositoryIntegrationTest.java @@ -0,0 +1,141 @@ +package com.baeldung.spring.data.jpa.spel.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import com.baeldung.spring.data.jpa.spel.NewsApplication; +import com.baeldung.spring.data.jpa.spel.entity.Article; +import com.baeldung.spring.data.jpa.spel.entity.ArticleWrapper; +import com.baeldung.spring.data.jpa.spel.extension.LocaleContextHolderExtension; +import java.util.List; +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; + +@SpringBootTest(classes = NewsApplication.class, + properties = { + "spring.jpa.show-sql=true", + "spring.jpa.generate-ddl=true", + }) +class ArticleRepositoryIntegrationTest { + + @Autowired + private ArticleRepository articleRepository; + + private static final String ENGLISH = "eng"; + private static final Article SPORTS_ARTICLE + = new Article(1L, "Sports Update", + "The local team won their game last night...", ENGLISH); + + @Autowired + private LocaleContextHolderExtension localeContextHolderExtension; + + @Test + void whenContextStartRepositoryIsPresent() { + assertNotNull(articleRepository, "Repository should be present"); + } + + @Test + void whenContextStartContextHolderIsPresent() { + assertNotNull(localeContextHolderExtension, "Context holder should be present"); + assertNotNull(localeContextHolderExtension.getRootObject()); + } + + @AfterEach + void tearDown() { + articleRepository.deleteAll(); + } + + @Test + void givenArticleWhenCreateWithPositionalArgumentsPlaceholdersShouldBePersisted() { + articleRepository.saveWithPositionalArguments(1L, SPORTS_ARTICLE.getTitle(), + SPORTS_ARTICLE.getContent(), + SPORTS_ARTICLE.getLanguage()); + final List
articles = articleRepository.findAll(); + assertEquals(1, articles.size()); + } + + @Test + void givenArticleWhenCreateWithPositionalSpELArgumentsPlaceholdersShouldBePersisted() { + articleRepository.saveWithPositionalSpELArguments(1L, SPORTS_ARTICLE.getTitle(), + SPORTS_ARTICLE.getContent(), + SPORTS_ARTICLE.getLanguage()); + final List
articles = articleRepository.findAll(); + assertEquals(1, articles.size()); + } + + @Test + void givenArticleWhenCreateWithPositionalSpELArgumentsPlaceholdersWithEmptyCheckShouldStoreDefaultValue() { + articleRepository.saveWithPositionalSpELArgumentsWithEmptyCheck(1L, + SPORTS_ARTICLE.getTitle(), null, SPORTS_ARTICLE.getLanguage()); + final List
articles = articleRepository.findAll(); + assertEquals(1, articles.size()); + assertEquals("Empty Article", articles.get(0).getContent()); + } + + @Test + void givenArticleWhenCreateWithPositionalSpELArgumentsPlaceholdersWithEmptyCheckShouldStoreTheOriginalContent() { + articleRepository.saveWithPositionalSpELArgumentsWithEmptyCheck(1L, + SPORTS_ARTICLE.getTitle(), SPORTS_ARTICLE.getContent(), SPORTS_ARTICLE.getLanguage()); + final List
articles = articleRepository.findAll(); + assertEquals(1, articles.size()); + assertEquals(SPORTS_ARTICLE, articles.get(0)); + } + + @Test + void givenArticleWhenCreateWithNamedArgumentsPlaceholdersShouldBePersisted() { + articleRepository.saveWithNamedArguments(1L, SPORTS_ARTICLE.getTitle(), + SPORTS_ARTICLE.getContent(), SPORTS_ARTICLE.getLanguage()); + final List
articles = articleRepository.findAll(); + assertEquals(1, articles.size()); + } + + @Test + void givenArticleWhenCreateWithNamedSpELArgumentsPlaceholdersShouldBePersisted() { + articleRepository.saveWithNamedSpELArguments(1L, SPORTS_ARTICLE.getTitle(), + SPORTS_ARTICLE.getContent(), SPORTS_ARTICLE.getLanguage()); + final List
articles = articleRepository.findAll(); + assertEquals(1, articles.size()); + } + + @Test + void givenArticleWhenCreateWithNamedSpELArgumentsAndLowerCaseLanguagePlaceholdersConvertLanguageToLowerCase() { + final String language = "ENG"; + articleRepository.saveWithNamedSpELArgumentsAndLowerCaseLanguage(1L, + SPORTS_ARTICLE.getTitle(), SPORTS_ARTICLE.getContent(), + language); + final List
articles = articleRepository.findAll(); + assertEquals(1, articles.size()); + assertEquals(language.toLowerCase(), articles.get(0).getLanguage()); + } + + @Test + void givenArticleWhenCreateWithSingleObjectArgumentPlaceholdersShouldBePersisted() { + articleRepository.saveWithSingleObjectSpELArgument(SPORTS_ARTICLE); + final List
articles = articleRepository.findAll(); + assertEquals(1, articles.size()); + } + + @Test + void givenArticleWhenCreateWithSingleWrappedObjectArgumentPlaceholdersShouldBePersisted() { + articleRepository.saveWithSingleWrappedObjectSpELArgument(new ArticleWrapper(SPORTS_ARTICLE)); + final List
articles = articleRepository.findAll(); + assertEquals(1, articles.size()); + } + + @Test + void givenInheritedQueryWhenSearchForArticlesWillReturnThem() { + articleRepository.save(SPORTS_ARTICLE); + final List
articles = articleRepository.findAllEntitiesUsingEntityPlaceholder(); + assertEquals(1, articles.size()); + } + + @Test + void givenInheritedNativeQueryWhenSearchForArticlesWillReturnThem() { + articleRepository.save(SPORTS_ARTICLE); + final List
articles = articleRepository.findAllEntitiesUsingEntityPlaceholderWithNativeQuery(); + assertEquals(1, articles.size()); + } + +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/resources/articles-dml.sql b/persistence-modules/spring-data-jpa-query-3/src/test/resources/articles-dml.sql new file mode 100644 index 0000000000..c6e00ee7cc --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/test/resources/articles-dml.sql @@ -0,0 +1,15 @@ +-- English +INSERT INTO articles (id, title, content, language) VALUES (11, 'Sports Update', 'The local team won their game last night...', 'eng'); +INSERT INTO articles (id, title, content, language) VALUES (17, 'Health News', 'New advancements in medical research were revealed...', 'eng'); + +-- French +INSERT INTO articles (id, title, content, language) VALUES (18, 'Nouvelles de la santé', 'De nouvelles avancées dans la recherche médicale ont été révélées...', 'fr'); +INSERT INTO articles (id, title, content, language) VALUES (12, 'Actualité sportive', 'L''équipe locale a gagné son match hier soir...', 'fr'); + +-- Spanish +INSERT INTO articles (id, title, content, language) VALUES (13, 'Actualización Deportiva', 'El equipo local ganó su partido anoche...', 'esp'); +INSERT INTO articles (id, title, content, language) VALUES (14, 'Innovación Tecnológica', 'Se ha anunciado un avance en la investigación de IA...', 'esp'); + +-- German +INSERT INTO articles (id, title, content, language) VALUES (15, 'Sportaktualisierung', 'Die lokale Mannschaft hat ihr Spiel gestern Abend gewonnen...', 'deu'); +INSERT INTO articles (id, title, content, language) VALUES (16, 'Technologie Durchbruch', 'Ein Durchbruch in der KI-Forschung wurde bekannt gegeben...', 'deu'); diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/resources/user-map-query-dml.sql b/persistence-modules/spring-data-jpa-query-3/src/test/resources/user-map-query-dml.sql new file mode 100644 index 0000000000..a7e3d59362 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/test/resources/user-map-query-dml.sql @@ -0,0 +1,50 @@ +INSERT INTO users (id, first_name, last_name) VALUES (1, 'Findlay', 'MacCafferty'); +INSERT INTO users (id, first_name, last_name) VALUES (2, 'Auroora', 'Oats'); +INSERT INTO users (id, first_name, last_name) VALUES (3, 'Shaylah', 'Coleson'); +INSERT INTO users (id, first_name, last_name) VALUES (4, 'Alika', 'Capin'); +INSERT INTO users (id, first_name, last_name) VALUES (5, 'Caressa', 'Caldicot'); +INSERT INTO users (id, first_name, last_name) VALUES (6, 'Bonny', 'Kilday'); +INSERT INTO users (id, first_name, last_name) VALUES (7, 'Carmina', 'Stopp'); +INSERT INTO users (id, first_name, last_name) VALUES (8, 'Tiebout', 'Gamlyn'); +INSERT INTO users (id, first_name, last_name) VALUES (9, 'Moe', 'Oddy'); +INSERT INTO users (id, first_name, last_name) VALUES (10, 'Edita', 'Kenyon'); +INSERT INTO users (id, first_name, last_name) VALUES (11, 'Melany', 'Blaylock'); +INSERT INTO users (id, first_name, last_name) VALUES (12, 'Sigvard', 'Storrier'); +INSERT INTO users (id, first_name, last_name) VALUES (13, 'Ogdon', 'Labitt'); +INSERT INTO users (id, first_name, last_name) VALUES (14, 'Stacia', 'Waleworke'); +INSERT INTO users (id, first_name, last_name) VALUES (15, 'Tiffi', 'Pearsey'); +INSERT INTO users (id, first_name, last_name) VALUES (16, 'Nefen', 'Roddick'); +INSERT INTO users (id, first_name, last_name) VALUES (17, 'Danie', 'Silman'); +INSERT INTO users (id, first_name, last_name) VALUES (18, 'Giacobo', 'Slowey'); +INSERT INTO users (id, first_name, last_name) VALUES (19, 'Robbie', 'McGillicuddy'); +INSERT INTO users (id, first_name, last_name) VALUES (20, 'Artus', 'Rickards'); +INSERT INTO users (id, first_name, last_name) VALUES (21, 'Pauline', 'Furnival'); +INSERT INTO users (id, first_name, last_name) VALUES (22, 'Bella', 'Crittal'); +INSERT INTO users (id, first_name, last_name) VALUES (23, 'Melicent', 'Lowe'); +INSERT INTO users (id, first_name, last_name) VALUES (24, 'Delora', 'Leving'); +INSERT INTO users (id, first_name, last_name) VALUES (25, 'Lane', 'Endricci'); +INSERT INTO users (id, first_name, last_name) VALUES (26, 'Doro', 'Kinforth'); +INSERT INTO users (id, first_name, last_name) VALUES (27, 'Antonina', 'Vivian'); +INSERT INTO users (id, first_name, last_name) VALUES (28, 'Hanny', 'Challoner'); +INSERT INTO users (id, first_name, last_name) VALUES (29, 'Tarrance', 'Beretta'); +INSERT INTO users (id, first_name, last_name) VALUES (30, 'Emyle', 'Jaycox'); +INSERT INTO users (id, first_name, last_name) VALUES (31, 'Lelah', 'Vesque'); +INSERT INTO users (id, first_name, last_name) VALUES (32, 'Kitty', 'Pumphrey'); +INSERT INTO users (id, first_name, last_name) VALUES (33, 'Karmen', 'Flaubert'); +INSERT INTO users (id, first_name, last_name) VALUES (34, 'Otho', 'Rowan'); +INSERT INTO users (id, first_name, last_name) VALUES (35, 'Jacinta', 'Tatlow'); +INSERT INTO users (id, first_name, last_name) VALUES (36, 'Jennette', 'Wass'); +INSERT INTO users (id, first_name, last_name) VALUES (37, 'Randi', 'Hambridge'); +INSERT INTO users (id, first_name, last_name) VALUES (38, 'Filmer', 'Conibere'); +INSERT INTO users (id, first_name, last_name) VALUES (39, 'Mel', 'Moffet'); +INSERT INTO users (id, first_name, last_name) VALUES (40, 'Clement', 'MacGovern'); +INSERT INTO users (id, first_name, last_name) VALUES (41, 'Silvana', 'Couronne'); +INSERT INTO users (id, first_name, last_name) VALUES (42, 'Myles', 'Lambersen'); +INSERT INTO users (id, first_name, last_name) VALUES (43, 'Sisile', 'Jeskins'); +INSERT INTO users (id, first_name, last_name) VALUES (44, 'Jackie', 'Aulsford'); +INSERT INTO users (id, first_name, last_name) VALUES (45, 'Duncan', 'Stapford'); +INSERT INTO users (id, first_name, last_name) VALUES (46, 'Heddie', 'Wylder'); +INSERT INTO users (id, first_name, last_name) VALUES (47, 'Homerus', 'Lyddyard'); +INSERT INTO users (id, first_name, last_name) VALUES (48, 'Davis', 'Golson'); +INSERT INTO users (id, first_name, last_name) VALUES (49, 'Marjory', 'Wilcock'); +INSERT INTO users (id, first_name, last_name) VALUES (50, 'Sheffield', 'Pigford'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-3/pom.xml b/persistence-modules/spring-data-jpa-repo-3/pom.xml index 211e8a2d96..5c57606d31 100644 --- a/persistence-modules/spring-data-jpa-repo-3/pom.xml +++ b/persistence-modules/spring-data-jpa-repo-3/pom.xml @@ -3,16 +3,17 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + spring-data-jpa-repo-3 + 0.0.1-SNAPSHOT + spring-data-jpa-repo-3 + spring-data-jpa-repo-3 + com.baeldung parent-boot-3 0.0.1-SNAPSHOT ../../parent-boot-3 - spring-data-jpa-repo-3 - 0.0.1-SNAPSHOT - spring-data-jpa-repo-3 - spring-data-jpa-repo-3 diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/lastrecord/Post.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/lastrecord/Post.java new file mode 100644 index 0000000000..c797a6378f --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/lastrecord/Post.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.data.jpa.listrepositories.lastrecord; + +import java.time.LocalDate; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; + +@Entity +public class Post { + + @Id + private Long id; + private String title; + private LocalDate publicationDate; + + 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 LocalDate getPublicationDate() { + return publicationDate; + } + + public void setPublicationDate(LocalDate publicationDate) { + this.publicationDate = publicationDate; + } + +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/lastrecord/PostRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/lastrecord/PostRepository.java new file mode 100644 index 0000000000..50d9e399c3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/lastrecord/PostRepository.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.data.jpa.listrepositories.lastrecord; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +public interface PostRepository extends JpaRepository { + + Post findFirstByOrderByPublicationDateDesc(); + + Post findTopByOrderByPublicationDateDesc(); + + @Query("SELECT p FROM Post p ORDER BY p.publicationDate DESC LIMIT 1") + Post findLastPost(); + +} diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/resources/data.sql b/persistence-modules/spring-data-jpa-repo-3/src/main/resources/data.sql index 50bd326155..8f114f1aa5 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/resources/data.sql +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/resources/data.sql @@ -1,4 +1,10 @@ INSERT INTO person (id, first_name, last_name) VALUES(1, 'Azhrioun', 'Abderrahim'); INSERT INTO person (id, first_name, last_name) VALUES(2, 'Brian', 'Wheeler'); INSERT INTO person (id, first_name, last_name) VALUES(3, 'Stella', 'Anderson'); -INSERT INTO person (id, first_name, last_name) VALUES(4, 'Stella', 'Wheeler'); \ No newline at end of file +INSERT INTO person (id, first_name, last_name) VALUES(4, 'Stella', 'Wheeler'); + +INSERT INTO post (id, title, publication_date) VALUES(1, 'Facebook post', '2020-11-10'); +INSERT INTO post (id, title, publication_date) VALUES(2, 'Instagram post', '2020-12-24'); +INSERT INTO post (id, title, publication_date) VALUES(3, 'Twitter post', '2023-01-10'); +INSERT INTO post (id, title, publication_date) VALUES(4, 'tiktok post', '2023-03-18'); +INSERT INTO post (id, title, publication_date) VALUES(5, 'Pinterest post', '2023-09-09'); \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/resources/schema.sql b/persistence-modules/spring-data-jpa-repo-3/src/main/resources/schema.sql index c8be0eb781..c991c04900 100644 --- a/persistence-modules/spring-data-jpa-repo-3/src/main/resources/schema.sql +++ b/persistence-modules/spring-data-jpa-repo-3/src/main/resources/schema.sql @@ -3,4 +3,11 @@ CREATE TABLE person( id INT PRIMARY KEY, first_name VARCHAR(200), last_name VARCHAR(200) +); + +DROP TABLE IF EXISTS post; +CREATE TABLE post( + id INT PRIMARY KEY, + title VARCHAR(200), + publication_date DATE ) \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/lastrecord/PostRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/lastrecord/PostRepositoryIntegrationTest.java new file mode 100644 index 0000000000..ecfb28574e --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/lastrecord/PostRepositoryIntegrationTest.java @@ -0,0 +1,40 @@ +package com.baeldung.spring.data.jpa.listrepositories.lastrecord; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; + +@DataJpaTest +class PostRepositoryIntegrationTest { + + @Autowired + private PostRepository postRepository; + + @Test + void givenPosts_whenUsingFindFirstDerivedQuery_thenReturnLastPost() { + Post post = postRepository.findFirstByOrderByPublicationDateDesc(); + + assertNotNull(post); + assertEquals(5, post.getId()); + } + + @Test + void givenPosts_whenUsingFindTopDerivedQuery_thenReturnLastPost() { + Post post = postRepository.findTopByOrderByPublicationDateDesc(); + + assertNotNull(post); + assertEquals(5, post.getId()); + } + + @Test + void givenPosts_whenUsingQueryAnnotation_thenReturnLastPost() { + Post post = postRepository.findLastPost(); + + assertNotNull(post); + assertEquals(5, post.getId()); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/ApplicationConfig.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/ApplicationConfig.java new file mode 100644 index 0000000000..043efc584a --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/ApplicationConfig.java @@ -0,0 +1,8 @@ +package com.baeldung.spring.data.persistence.findvsget; + +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ApplicationConfig { + +} diff --git a/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/entity/User.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/entity/User.java new file mode 100644 index 0000000000..264ea92a5c --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/entity/User.java @@ -0,0 +1,90 @@ +package com.baeldung.spring.data.persistence.findvsget.entity; + +import java.util.Objects; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @Column(name = "id") + private Long id; + @Column(name = "first_name") + private String firstName; + @Column(name = "second_name") + private String secondName; + + public User() { + } + + public User(final Long id, final String firstName, final String secondName) { + this.id = id; + this.firstName = firstName; + this.secondName = secondName; + } + + public void setId(final Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public String getSecondName() { + return secondName; + } + + public void setSecondName(final String secondName) { + this.secondName = secondName; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + final User user = (User) o; + + if (!Objects.equals(id, user.id)) { + return false; + } + if (!Objects.equals(firstName, user.firstName)) { + return false; + } + return Objects.equals(secondName, user.secondName); + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (firstName != null ? firstName.hashCode() : 0); + result = 31 * result + (secondName != null ? secondName.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "User{" + + "id=" + id + + ", firstName='" + firstName + '\'' + + ", secondName='" + secondName + '\'' + + '}'; + } +} diff --git a/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/repository/NewTransactionUserRepository.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/repository/NewTransactionUserRepository.java new file mode 100644 index 0000000000..6b0523b637 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/repository/NewTransactionUserRepository.java @@ -0,0 +1,19 @@ +package com.baeldung.spring.data.persistence.findvsget.repository; + +import com.baeldung.spring.data.persistence.findvsget.entity.User; +import java.util.Optional; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +@Repository +public interface NewTransactionUserRepository extends JpaRepository { + + @Override + @Transactional(propagation = Propagation.REQUIRES_NEW) + User getReferenceById(Long id); + + @Override + Optional findById(Long id); +} diff --git a/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/repository/SimpleUserRepository.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/repository/SimpleUserRepository.java new file mode 100644 index 0000000000..e105f226a5 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/repository/SimpleUserRepository.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.data.persistence.findvsget.repository; + +import com.baeldung.spring.data.persistence.findvsget.entity.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface SimpleUserRepository extends JpaRepository { + +} diff --git a/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/service/NonTransactionalUserReferenceService.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/service/NonTransactionalUserReferenceService.java new file mode 100644 index 0000000000..e79df3c91d --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/service/NonTransactionalUserReferenceService.java @@ -0,0 +1,33 @@ +package com.baeldung.spring.data.persistence.findvsget.service; + +import com.baeldung.spring.data.persistence.findvsget.entity.User; +import com.baeldung.spring.data.persistence.findvsget.repository.SimpleUserRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +@Service +public class NonTransactionalUserReferenceService { + + private static final Logger log = LoggerFactory.getLogger(NonTransactionalUserReferenceService.class); + private SimpleUserRepository repository; + + public User findUserReference(final long id) { + log.info("Before requesting a user"); + final User user = repository.getReferenceById(id); + log.info("After requesting a user"); + return user; + } + + public User findAndUseUserReference(final long id) { + final User user = repository.getReferenceById(id); + log.info("Before accessing a username"); + final String firstName = user.getFirstName(); + log.info("This message shouldn't be displayed because of the thrown exception: {}", firstName); + return user; + } + + public void setRepository(final SimpleUserRepository repository) { + this.repository = repository; + } +} diff --git a/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/service/SimpleUserService.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/service/SimpleUserService.java new file mode 100644 index 0000000000..0ed7a72946 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/service/SimpleUserService.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.data.persistence.findvsget.service; + +import com.baeldung.spring.data.persistence.findvsget.entity.User; +import com.baeldung.spring.data.persistence.findvsget.repository.SimpleUserRepository; +import java.util.Optional; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +@Service +public class SimpleUserService { + + private static final Logger log = LoggerFactory.getLogger(SimpleUserService.class); + private final SimpleUserRepository repository; + + public SimpleUserService(final SimpleUserRepository repository) { + this.repository = repository; + } + + public User findUser(final long id) { + log.info("Before requesting a user in a findUser method"); + final Optional optionalUser = repository.findById(id); + log.info("After requesting a user in a findUser method"); + final User user = optionalUser.orElse(null); + log.info("After unwrapping an optional in a findUser method"); + return user; + } +} diff --git a/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/service/TransactionalUserReferenceService.java b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/service/TransactionalUserReferenceService.java new file mode 100644 index 0000000000..56ba884fed --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/src/main/java/com/baeldung/spring/data/persistence/findvsget/service/TransactionalUserReferenceService.java @@ -0,0 +1,36 @@ +package com.baeldung.spring.data.persistence.findvsget.service; + +import com.baeldung.spring.data.persistence.findvsget.entity.User; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class TransactionalUserReferenceService { + + private static final Logger log = LoggerFactory.getLogger(TransactionalUserReferenceService.class); + private JpaRepository repository; + + @Transactional + public User findUserReference(final long id) { + log.info("Before requesting a user"); + final User user = repository.getReferenceById(id); + log.info("After requesting a user"); + return user; + } + + @Transactional + public User findAndUseUserReference(final long id) { + final User user = repository.getReferenceById(id); + log.info("Before accessing a username"); + final String firstName = user.getFirstName(); + log.info("After accessing a username: {}", firstName); + return user; + } + + public void setRepository(final JpaRepository repository) { + this.repository = repository; + } +} diff --git a/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/findvsget/DatabaseConfigurationBaseIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/findvsget/DatabaseConfigurationBaseIntegrationTest.java new file mode 100644 index 0000000000..3ac46c3a39 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/findvsget/DatabaseConfigurationBaseIntegrationTest.java @@ -0,0 +1,43 @@ +package com.baeldung.spring.data.persistence.findvsget; + +import static com.baeldung.spring.data.persistence.findvsget.UserProvider.userSource; +import static org.assertj.core.api.Assumptions.assumeThat; + +import com.baeldung.spring.data.persistence.findvsget.entity.User; +import com.baeldung.spring.data.persistence.findvsget.repository.SimpleUserRepository; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.provider.Arguments; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest(classes = ApplicationConfig.class, properties = { + "spring.jpa.generate-ddl=true", + "spring.jpa.show-sql=false" +}) +abstract class DatabaseConfigurationBaseIntegrationTest { + + private static final int NUMBER_OF_USERS = 10; + + @Autowired + private SimpleUserRepository repository; + + @BeforeEach + void populateDatabase() { + final List users = userSource() + .map(Arguments::get) + .map(s -> new User(((Long) s[0]), s[1].toString(), s[2].toString())) + .collect(Collectors.toList()); + repository.saveAll(users); + assumeThat(repository.findAll()).hasSize(NUMBER_OF_USERS); + } + + @AfterEach + void clearDatabase() { + repository.deleteAll(); + } + +} + diff --git a/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/findvsget/FindUserIntegrationIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/findvsget/FindUserIntegrationIntegrationTest.java new file mode 100644 index 0000000000..efe370b38a --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/findvsget/FindUserIntegrationIntegrationTest.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.data.persistence.findvsget; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.spring.data.persistence.findvsget.entity.User; +import com.baeldung.spring.data.persistence.findvsget.service.SimpleUserService; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; + +@DisplayName("findBy test:") +class FindUserIntegrationIntegrationTest extends DatabaseConfigurationBaseIntegrationTest { + + + @Autowired + private SimpleUserService service; + + @ParameterizedTest + @ArgumentsSource(UserProvider.class) + @DisplayName("when looking for a user by an existing ID returns a user") + void whenGettingUserByCorrectIdThenReturnUser(Long id, String firstName, String lastName) { + final User expected = new User(id, firstName, lastName); + final User actual = service.findUser(id); + assertThat(actual).isEqualTo(expected); + } + + @ParameterizedTest + @DisplayName("when looking for a user by a non-existing ID returns null") + @ValueSource(longs = {11, 12, 13}) + void whenGettingUserByIncorrectIdThenReturnNull(Long id) { + assertThat(service.findUser(id)).isNull(); + } + + +} diff --git a/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/findvsget/GetReferenceIntegrationIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/findvsget/GetReferenceIntegrationIntegrationTest.java new file mode 100644 index 0000000000..c4be5d1ccd --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/findvsget/GetReferenceIntegrationIntegrationTest.java @@ -0,0 +1,125 @@ +package com.baeldung.spring.data.persistence.findvsget; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +import com.baeldung.spring.data.persistence.findvsget.entity.User; +import com.baeldung.spring.data.persistence.findvsget.repository.NewTransactionUserRepository; +import com.baeldung.spring.data.persistence.findvsget.repository.SimpleUserRepository; +import com.baeldung.spring.data.persistence.findvsget.service.NonTransactionalUserReferenceService; +import com.baeldung.spring.data.persistence.findvsget.service.TransactionalUserReferenceService; +import org.hibernate.LazyInitializationException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; +import org.springframework.beans.factory.annotation.Autowired; + + +@DisplayName("getReferenceBy test:") +class GetReferenceIntegrationIntegrationTest extends DatabaseConfigurationBaseIntegrationTest { + + private static final long EXISTING_ID = 1L; + + @Nested + @DisplayName("given non-transactional service, even if user exists") + class GivenNonTransactionalService { + + @Autowired + private NonTransactionalUserReferenceService nonTransactionalService; + + @BeforeEach + void configureService(@Autowired SimpleUserRepository repository) { + nonTransactionalService.setRepository(repository); + } + + @Test + void whenFindUserReferenceUsingOutsideServiceThenThrowsException() { + final User user = nonTransactionalService.findUserReference(EXISTING_ID); + assertThatExceptionOfType(LazyInitializationException.class) + .isThrownBy(user::getFirstName); + } + + @Test + void whenFindUserReferenceNotUsingOutsideServiceThenDontThrowException() { + final User user = nonTransactionalService.findUserReference(EXISTING_ID); + assertThat(user).isNotNull(); + } + + @Test + void whenFindUserReferenceUsingInsideServiceThenThrowsException() { + assertThatExceptionOfType(LazyInitializationException.class) + .isThrownBy(() -> nonTransactionalService.findAndUseUserReference(EXISTING_ID)); + } + } + + @Nested + @DisplayName("given transactional service with simple repository, even if user exists") + class GivenTransactionalService { + + @Autowired + private TransactionalUserReferenceService transactionalService; + + @BeforeEach + void configureService(@Autowired SimpleUserRepository repository) { + transactionalService.setRepository(repository); + } + + @Test + void whenFindUserReferenceUsingOutsideServiceThenThrowsException() { + final User user = transactionalService.findUserReference(EXISTING_ID); + assertThatExceptionOfType(LazyInitializationException.class) + .isThrownBy(user::getFirstName); + } + + @Test + void whenFindUserReferenceNotUsingOutsideServiceThenDontThrowException() { + final User user = transactionalService.findUserReference(EXISTING_ID); + assertThat(user).isNotNull(); + } + + @ParameterizedTest + @ArgumentsSource(UserProvider.class) + void whenFindUserReferenceUsingInsideServiceThenReturnsUser(Long id, String firstName, String lastName) { + final User expected = new User(id, firstName, lastName); + final User actual = transactionalService.findAndUseUserReference(id); + assertThat(actual).isEqualTo(expected); + } + } + + @Nested + @DisplayName("given transactional service with new transaction repository, even if user exists") + class GivenTransactionalServiceWithNewTransactionRepository { + + @Autowired + private TransactionalUserReferenceService transactionalServiceWithNewTransactionRepository; + + @BeforeEach + void configureService(@Autowired NewTransactionUserRepository repository) { + transactionalServiceWithNewTransactionRepository.setRepository(repository); + } + + @Test + void whenFindUserReferenceUsingOutsideServiceThenThrowsException() { + final User user = transactionalServiceWithNewTransactionRepository + .findUserReference(EXISTING_ID); + assertThatExceptionOfType(LazyInitializationException.class) + .isThrownBy(user::getFirstName); + } + + @Test + void whenFindUserReferenceNotUsingOutsideServiceThenDontThrowException() { + final User user = transactionalServiceWithNewTransactionRepository.findUserReference(EXISTING_ID); + assertThat(user).isNotNull(); + } + + @Test + void whenFindUserReferenceUsingInsideServiceThenThrowsExceptionDueToSeparateTransactions() { + assertThatExceptionOfType(LazyInitializationException.class) + .isThrownBy(() -> transactionalServiceWithNewTransactionRepository + .findAndUseUserReference(EXISTING_ID)); + } + } +} diff --git a/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/findvsget/UserProvider.java b/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/findvsget/UserProvider.java new file mode 100644 index 0000000000..f0222dae50 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-4/src/test/java/com/baeldung/spring/data/persistence/findvsget/UserProvider.java @@ -0,0 +1,30 @@ +package com.baeldung.spring.data.persistence.findvsget; + + +import java.util.stream.Stream; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; + +public class UserProvider implements ArgumentsProvider { + + @Override + public Stream provideArguments(final ExtensionContext context) { + return userSource(); + } + + static Stream userSource() { + return Stream.of( + Arguments.of(1L, "Saundra", "Krystek"), + Arguments.of(2L, "Korey", "Venners"), + Arguments.of(3L, "Lory", "Daffey"), + Arguments.of(4L, "Michail", "Spinella"), + Arguments.of(5L, "Emanuel", "Geertje"), + Arguments.of(6L, "Jervis", "Waugh"), + Arguments.of(7L, "Chantal", "Soldan"), + Arguments.of(8L, "Darnall", "Fanner"), + Arguments.of(9L, "Cordelia", "Hindge"), + Arguments.of(10L, "Lem", "Pitcock") + ); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/README.md b/persistence-modules/spring-data-jpa-repo/README.md index 9587f544f9..ef3442929e 100644 --- a/persistence-modules/spring-data-jpa-repo/README.md +++ b/persistence-modules/spring-data-jpa-repo/README.md @@ -20,6 +20,6 @@ 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" +- Project -> Properties -> Java Persistence -> 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-repo/src/main/java/com/baeldung/boot/BootApplication.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/BootApplication.java new file mode 100644 index 0000000000..9275d9f449 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/boot/BootApplication.java @@ -0,0 +1,21 @@ +package com.baeldung.boot; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +import com.baeldung.jpa.JpaApplication; +import com.baeldung.boot.daos.impl.ExtendedRepositoryImpl; + +@SpringBootApplication +@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class, basePackages = "com.baeldung.boot.daos") +@EntityScan({"com.baeldung.boot.domain"}) +@ComponentScan("com.baeldung.boot.daos") +public class BootApplication { + public static void main(String[] args) { + SpringApplication.run(JpaApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/JpaApplication.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/JpaApplication.java new file mode 100644 index 0000000000..eab5a741a3 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/JpaApplication.java @@ -0,0 +1,17 @@ +package com.baeldung.jpa; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; + +@SpringBootApplication +@ComponentScan("com.baeldung.jpa") +@EnableJpaRepositories("com.baeldung.jpa.repository") +public class JpaApplication { + + public static void main(String[] args) { + SpringApplication.run(JpaApplication.class, args); + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/config/JpaPopulators.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/config/JpaPopulators.java similarity index 93% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/config/JpaPopulators.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/config/JpaPopulators.java index 24348d31c5..c21bb48c83 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/config/JpaPopulators.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/config/JpaPopulators.java @@ -1,35 +1,35 @@ -package com.baeldung.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.data.repository.init.Jackson2RepositoryPopulatorFactoryBean; -import org.springframework.data.repository.init.UnmarshallerRepositoryPopulatorFactoryBean; -import org.springframework.oxm.jaxb.Jaxb2Marshaller; - -import com.baeldung.entity.Fruit; - -@Configuration -public class JpaPopulators { - - @Bean - public Jackson2RepositoryPopulatorFactoryBean getRespositoryPopulator() throws Exception { - Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean(); - factory.setResources(new Resource[] { new ClassPathResource("fruit-data.json") }); - return factory; - } - - @Bean - public UnmarshallerRepositoryPopulatorFactoryBean repositoryPopulator() { - - Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller(); - unmarshaller.setClassesToBeBound(Fruit.class); - - UnmarshallerRepositoryPopulatorFactoryBean factory = new UnmarshallerRepositoryPopulatorFactoryBean(); - factory.setUnmarshaller(unmarshaller); - factory.setResources(new Resource[] { new ClassPathResource("apple-fruit-data.xml"), new ClassPathResource("guava-fruit-data.xml") }); - return factory; - } - -} +package com.baeldung.jpa.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.data.repository.init.Jackson2RepositoryPopulatorFactoryBean; +import org.springframework.data.repository.init.UnmarshallerRepositoryPopulatorFactoryBean; +import org.springframework.oxm.jaxb.Jaxb2Marshaller; + +import com.baeldung.jpa.domain.Fruit; + +@Configuration +public class JpaPopulators { + + @Bean + public Jackson2RepositoryPopulatorFactoryBean getRespositoryPopulator() throws Exception { + Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean(); + factory.setResources(new Resource[] { new ClassPathResource("fruit-data.json") }); + return factory; + } + + @Bean + public UnmarshallerRepositoryPopulatorFactoryBean repositoryPopulator() { + + Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller(); + unmarshaller.setClassesToBeBound(Fruit.class); + + UnmarshallerRepositoryPopulatorFactoryBean factory = new UnmarshallerRepositoryPopulatorFactoryBean(); + factory.setUnmarshaller(unmarshaller); + factory.setResources(new Resource[] { new ClassPathResource("apple-fruit-data.xml"), new ClassPathResource("guava-fruit-data.xml") }); + return factory; + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PersistenceConfig.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/config/PersistenceConfig.java similarity index 87% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PersistenceConfig.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/config/PersistenceConfig.java index f3c9301bcf..0c47351104 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PersistenceConfig.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/config/PersistenceConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.repository; +package com.baeldung.jpa.config; import java.util.Properties; @@ -6,12 +6,10 @@ import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; 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.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; @@ -23,24 +21,18 @@ import com.google.common.base.Preconditions; @Configuration @PropertySource("classpath:persistence.properties") -@ComponentScan("com.baeldung.repository") -//@ImportResource("classpath*:*springDataConfig.xml") @EnableTransactionManagement -@EnableJpaRepositories(basePackages = "com.baeldung.repository") +//@ImportResource("classpath*:*springDataConfig.xml") public class PersistenceConfig { @Autowired private Environment env; - public PersistenceConfig() { - super(); - } - @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan("com.baeldung.spring.data.persistence.repository"); + em.setPackagesToScan("com.baeldung.jpa.domain"); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/Foo.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/domain/Foo.java similarity index 98% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/Foo.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/domain/Foo.java index 27ebcf5875..f799635eae 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/Foo.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/domain/Foo.java @@ -1,4 +1,4 @@ -package com.baeldung.repository; +package com.baeldung.jpa.domain; import java.io.Serializable; diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Fruit.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/domain/Fruit.java similarity index 90% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Fruit.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/domain/Fruit.java index d45ac33db8..6314c58da3 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Fruit.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/domain/Fruit.java @@ -1,40 +1,40 @@ -package com.baeldung.entity; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -@Entity -public class Fruit { - - @Id - private long id; - private String name; - private String color; - - 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 String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - -} +package com.baeldung.jpa.domain; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +@Entity +public class Fruit { + + @Id + private long id; + private String name; + private String color; + + 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 String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Passenger.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/domain/Passenger.java similarity index 98% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Passenger.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/domain/Passenger.java index 3aafbe9afa..acfb7947c0 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Passenger.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/domain/Passenger.java @@ -1,4 +1,4 @@ -package com.baeldung.entity; +package com.baeldung.jpa.domain; import javax.persistence.Basic; import javax.persistence.Column; diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Song.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/domain/Song.java similarity index 97% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Song.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/domain/Song.java index 395527c1eb..9dcde0bea4 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/entity/Song.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/domain/Song.java @@ -1,4 +1,4 @@ -package com.baeldung.entity; +package com.baeldung.jpa.domain; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FruitRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/repository/FruitRepository.java similarity index 88% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FruitRepository.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/repository/FruitRepository.java index 5055252adf..dfbb4a5102 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FruitRepository.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/repository/FruitRepository.java @@ -1,27 +1,27 @@ -package com.baeldung.repository; - -import java.util.List; - -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 com.baeldung.entity.Fruit; - -@Repository -public interface FruitRepository extends JpaRepository { - - Long deleteByName(String name); - - List deleteByColor(String color); - - Long removeByName(String name); - - List removeByColor(String color); - - @Modifying - @Query("delete from Fruit f where f.name=:name or f.color=:color") - int deleteFruits(@Param("name") String name, @Param("color") String color); -} +package com.baeldung.jpa.repository; + +import java.util.List; + +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 com.baeldung.jpa.domain.Fruit; + +@Repository +public interface FruitRepository extends JpaRepository { + + Long deleteByName(String name); + + List deleteByColor(String color); + + Long removeByName(String name); + + List removeByColor(String color); + + @Modifying + @Query("delete from Fruit f where f.name=:name or f.color=:color") + int deleteFruits(@Param("name") String name, @Param("color") String color); +} diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooDAO.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/repository/IFooDAO.java similarity index 82% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooDAO.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/repository/IFooDAO.java index 6ee74fe26c..4834e2f68c 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooDAO.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/repository/IFooDAO.java @@ -1,9 +1,10 @@ -package com.baeldung.repository; +package com.baeldung.jpa.repository; 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; + +import com.baeldung.jpa.domain.Foo; public interface IFooDAO extends JpaRepository { diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PassengerRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/repository/PassengerRepository.java similarity index 58% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PassengerRepository.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/repository/PassengerRepository.java index a295a74f1b..c7aa56f830 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/PassengerRepository.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/repository/PassengerRepository.java @@ -1,13 +1,13 @@ -package com.baeldung.repository; +package com.baeldung.jpa.repository; -import com.baeldung.entity.Passenger; +import com.baeldung.jpa.domain.Passenger; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository -interface PassengerRepository extends JpaRepository { +public interface PassengerRepository extends JpaRepository { List findByFirstNameIgnoreCase(String firstName); diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/SongRepository.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/repository/SongRepository.java similarity index 86% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/SongRepository.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/repository/SongRepository.java index 6faed411d3..c7a8647f5a 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/SongRepository.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/repository/SongRepository.java @@ -1,11 +1,11 @@ -package com.baeldung.repository; +package com.baeldung.jpa.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; -import com.baeldung.entity.Song; +import com.baeldung.jpa.domain.Song; @Repository public interface SongRepository extends JpaRepository { diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FooService.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/service/FooService.java similarity index 71% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FooService.java rename to persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/service/FooService.java index 98084240ac..d449bc11a8 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/FooService.java +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/service/FooService.java @@ -1,10 +1,14 @@ -package com.baeldung.repository; +package com.baeldung.jpa.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import com.baeldung.jpa.domain.Foo; +import com.baeldung.jpa.repository.IFooDAO; + @Service public class FooService implements IFooService { + @Autowired private IFooDAO dao; diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/service/IFooService.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/service/IFooService.java new file mode 100644 index 0000000000..f75f33ba38 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/jpa/service/IFooService.java @@ -0,0 +1,7 @@ +package com.baeldung.jpa.service; + +import com.baeldung.jpa.domain.Foo; + +public interface IFooService { + Foo create(Foo foo); +} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooService.java b/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooService.java deleted file mode 100644 index 6c4d36710c..0000000000 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/repository/IFooService.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.baeldung.repository; - -public interface IFooService { - Foo create(Foo foo); -} \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/main/resources/fruit-data.json b/persistence-modules/spring-data-jpa-repo/src/main/resources/fruit-data.json index 6dc44e2586..b605352dc9 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/resources/fruit-data.json +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/fruit-data.json @@ -1,12 +1,12 @@ [ { - "_class": "com.baeldung.entity.Fruit", + "_class": "com.baeldung.jpa.domain.Fruit", "name": "apple", "color": "red", "id": 1 }, { - "_class": "com.baeldung.entity.Fruit", + "_class": "com.baeldung.jpa.domain.Fruit", "name": "guava", "color": "green", "id": 2 diff --git a/persistence-modules/spring-data-jpa-repo/src/main/resources/springDataConfig.xml b/persistence-modules/spring-data-jpa-repo/src/main/resources/springDataConfig.xml index e581d514a4..7746814290 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/resources/springDataConfig.xml +++ b/persistence-modules/spring-data-jpa-repo/src/main/resources/springDataConfig.xml @@ -7,5 +7,5 @@ http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd" > - + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java index b367b5fdca..51874e2bbe 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/ExtendedStudentRepositoryIntegrationTest.java @@ -13,11 +13,11 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.Application; +import com.baeldung.boot.BootApplication; import com.baeldung.boot.domain.Student; @RunWith(SpringRunner.class) -@ContextConfiguration(classes = {Application.class}) +@ContextConfiguration(classes = { BootApplication.class}) @DirtiesContext public class ExtendedStudentRepositoryIntegrationTest { @Resource diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java index e4bd3dabff..af454379c8 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/boot/daos/InventoryRepositoryIntegrationTest.java @@ -15,11 +15,11 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; -import com.baeldung.Application; +import com.baeldung.boot.BootApplication; import com.baeldung.boot.domain.MerchandiseEntity; @RunWith(SpringRunner.class) -@SpringBootTest(classes = Application.class) +@SpringBootTest(classes = BootApplication.class) public class InventoryRepositoryIntegrationTest { private static final String ORIGINAL_TITLE = "Pair of Pants"; diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FooServiceIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/jpa/FooServiceIntegrationTest.java similarity index 73% rename from persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FooServiceIntegrationTest.java rename to persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/jpa/FooServiceIntegrationTest.java index 9362b4c338..4c0fc99eb5 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FooServiceIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/jpa/FooServiceIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.repository; +package com.baeldung.jpa; import javax.sql.DataSource; @@ -6,11 +6,16 @@ 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.domain.Foo; +import com.baeldung.jpa.service.IFooService; + @RunWith(SpringRunner.class) -@ContextConfiguration(classes = PersistenceConfig.class) +@ContextConfiguration(classes = { JpaApplication.class}) +@DirtiesContext public class FooServiceIntegrationTest { @Autowired diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/jpa/FruitPopulatorIntegrationTest.java similarity index 86% rename from persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java rename to persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/jpa/FruitPopulatorIntegrationTest.java index 4d3661e717..e321b1271e 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/FruitPopulatorIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/jpa/FruitPopulatorIntegrationTest.java @@ -1,38 +1,39 @@ -package com.baeldung.repository; - -import static org.junit.Assert.assertEquals; - -import java.util.List; - -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 com.baeldung.entity.Fruit; - -@RunWith(SpringRunner.class) -@SpringBootTest -public class FruitPopulatorIntegrationTest { - - @Autowired - private FruitRepository fruitRepository; - - @Test - public void givenFruitJsonPopulatorThenShouldInsertRecordOnStart() { - - List fruits = fruitRepository.findAll(); - assertEquals("record count is not matching", 2, fruits.size()); - - fruits.forEach(fruit -> { - if (1 == fruit.getId()) { - assertEquals("apple", fruit.getName()); - assertEquals("red", fruit.getColor()); - } else if (2 == fruit.getId()) { - assertEquals("guava", fruit.getName()); - assertEquals("green", fruit.getColor()); - } - }); - } -} +package com.baeldung.jpa; + +import static org.junit.Assert.assertEquals; + +import java.util.List; + +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 com.baeldung.jpa.domain.Fruit; +import com.baeldung.jpa.repository.FruitRepository; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = JpaApplication.class) +public class FruitPopulatorIntegrationTest { + + @Autowired + private FruitRepository fruitRepository; + + @Test + public void givenFruitJsonPopulatorThenShouldInsertRecordOnStart() { + + List fruits = fruitRepository.findAll(); + assertEquals("record count is not matching", 2, fruits.size()); + + fruits.forEach(fruit -> { + if (1 == fruit.getId()) { + assertEquals("apple", fruit.getName()); + assertEquals("red", fruit.getColor()); + } else if (2 == fruit.getId()) { + assertEquals("guava", fruit.getName()); + assertEquals("green", fruit.getColor()); + } + }); + } +} diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/jpa/PassengerRepositoryIntegrationTest.java similarity index 81% rename from persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/jpa/PassengerRepositoryIntegrationTest.java index fd06710084..1676cd6406 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/PassengerRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/jpa/PassengerRepositoryIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.repository; +package com.baeldung.jpa; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; @@ -8,18 +8,22 @@ import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; +import javax.transaction.Transactional; 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.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.entity.Passenger; +import com.baeldung.jpa.domain.Passenger; +import com.baeldung.jpa.repository.PassengerRepository; -@DataJpaTest(showSql = false) @RunWith(SpringRunner.class) +@ContextConfiguration(classes = { JpaApplication.class}) +@DirtiesContext public class PassengerRepositoryIntegrationTest { @PersistenceContext @@ -28,6 +32,7 @@ public class PassengerRepositoryIntegrationTest { private PassengerRepository repository; @Before + @Transactional public void before() { entityManager.persist(Passenger.from("Jill", "Smith")); entityManager.persist(Passenger.from("Eve", "Jackson")); @@ -36,6 +41,7 @@ public class PassengerRepositoryIntegrationTest { entityManager.persist(Passenger.from("Siya", "Kolisi")); } + @Transactional @Test public void givenPassengers_whenMatchingIgnoreCase_thenExpectedReturned() { Passenger jill = Passenger.from("Jill", "Smith"); diff --git a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/jpa/SongRepositoryIntegrationTest.java similarity index 84% rename from persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/jpa/SongRepositoryIntegrationTest.java index 19362acd44..f5861ec120 100644 --- a/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/repository/SongRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-repo/src/test/java/com/baeldung/jpa/SongRepositoryIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.repository; +package com.baeldung.jpa; import static org.junit.Assert.assertEquals; @@ -7,17 +7,19 @@ import java.util.List; 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.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; -import com.baeldung.entity.Song; -import com.baeldung.repository.SongRepository; +import com.baeldung.jpa.domain.Song; +import com.baeldung.jpa.repository.SongRepository; @RunWith(SpringRunner.class) -@SpringBootTest +@ContextConfiguration(classes = { JpaApplication.class }) @Sql(scripts = { "/test-song-data.sql" }) +@DirtiesContext public class SongRepositoryIntegrationTest { @Autowired private SongRepository songRepository; diff --git a/persistence-modules/spring-data-mongodb-reactive/pom.xml b/persistence-modules/spring-data-mongodb-reactive/pom.xml index 46b2e8067f..ca45d4a758 100644 --- a/persistence-modules/spring-data-mongodb-reactive/pom.xml +++ b/persistence-modules/spring-data-mongodb-reactive/pom.xml @@ -18,7 +18,7 @@ io.projectreactor reactor-core - ${reactor-core.version} + ${reactor.version} org.springframework.boot @@ -40,6 +40,7 @@ io.projectreactor reactor-test + ${reactor.version} test @@ -126,7 +127,7 @@ 5.3.15 4.5.2 - 3.3.1.RELEASE + 3.6.0 \ No newline at end of file diff --git a/persistence-modules/spring-data-yugabytedb/pom.xml b/persistence-modules/spring-data-yugabytedb/pom.xml index d7f7576cfe..ec10275da4 100644 --- a/persistence-modules/spring-data-yugabytedb/pom.xml +++ b/persistence-modules/spring-data-yugabytedb/pom.xml @@ -10,11 +10,15 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 + + com.baeldung.Main + + org.springframework.boot diff --git a/persistence-modules/spring-data-yugabytedb/src/main/java/com/baeldung/User.java b/persistence-modules/spring-data-yugabytedb/src/main/java/com/baeldung/User.java index 54bbf2617c..c6c40c6953 100644 --- a/persistence-modules/spring-data-yugabytedb/src/main/java/com/baeldung/User.java +++ b/persistence-modules/spring-data-yugabytedb/src/main/java/com/baeldung/User.java @@ -1,11 +1,11 @@ package com.baeldung; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +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") diff --git a/persistence-modules/spring-data-yugabytedb/src/main/resources/application.properties b/persistence-modules/spring-data-yugabytedb/src/main/resources/application.properties index fdb3d50ec8..19c539ec9d 100644 --- a/persistence-modules/spring-data-yugabytedb/src/main/resources/application.properties +++ b/persistence-modules/spring-data-yugabytedb/src/main/resources/application.properties @@ -2,3 +2,5 @@ spring.datasource.url=jdbc:postgresql://localhost:5433/yugabyte spring.datasource.username=yugabyte spring.datasource.password=yugabyte spring.jpa.hibernate.ddl-auto=create +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect + diff --git a/persistence-modules/spring-jdbc-2/pom.xml b/persistence-modules/spring-jdbc-2/pom.xml index ce79c1c615..7942e7675d 100644 --- a/persistence-modules/spring-jdbc-2/pom.xml +++ b/persistence-modules/spring-jdbc-2/pom.xml @@ -1,9 +1,8 @@ + 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 - org.example spring-jdbc-2 1.0-SNAPSHOT diff --git a/persistence-modules/spring-jdbc/pom.xml b/persistence-modules/spring-jdbc/pom.xml index 1cf4c141b3..fc56d132af 100644 --- a/persistence-modules/spring-jdbc/pom.xml +++ b/persistence-modules/spring-jdbc/pom.xml @@ -8,11 +8,15 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 + + com.baeldung.spring.jdbc.batch.SpringJdbcBatchPerformanceApplication + + org.springframework.data diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java index 0f47473bd7..6306d63a41 100644 --- a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositoryJDBCTemplate.java @@ -1,6 +1,7 @@ package com.baeldung.spring.jdbc.autogenkey.repository; import java.sql.PreparedStatement; +import java.sql.Statement; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; @@ -21,7 +22,8 @@ public class MessageRepositoryJDBCTemplate { KeyHolder keyHolder = new GeneratedKeyHolder(); jdbcTemplate.update(connection -> { - PreparedStatement ps = connection.prepareStatement(INSERT_MESSAGE_SQL); + PreparedStatement ps = connection.prepareStatement(INSERT_MESSAGE_SQL, + Statement.RETURN_GENERATED_KEYS); ps.setString(1, message); return ps; }, keyHolder); @@ -32,7 +34,7 @@ public class MessageRepositoryJDBCTemplate { final String SELECT_BY_ID = "select message from sys_message where id = ?"; public String getMessageById(long id) { - return this.jdbcTemplate.queryForObject(SELECT_BY_ID, String.class, new Object[] { id }); + return this.jdbcTemplate.queryForObject(SELECT_BY_ID, String.class, id); } } diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java index 247fbf28c2..cb2c0bf5a8 100644 --- a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/autogenkey/repository/MessageRepositorySimpleJDBCInsert.java @@ -20,7 +20,7 @@ public class MessageRepositorySimpleJDBCInsert { } public long insert(String message) { - Map parameters = new HashMap(1); + Map parameters = new HashMap<>(1); parameters.put("message", message); Number newId = messageInsert.executeAndReturnKey(parameters); return (long) newId; diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/replacedeprecated/model/StudentResultExtractor.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/replacedeprecated/model/StudentResultExtractor.java index d2da59e5f9..7559987992 100644 --- a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/replacedeprecated/model/StudentResultExtractor.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/replacedeprecated/model/StudentResultExtractor.java @@ -10,7 +10,7 @@ import java.util.List; public class StudentResultExtractor implements ResultSetExtractor> { @Override public List extractData(ResultSet rs) throws SQLException { - List students = new ArrayList(); + List students = new ArrayList<>(); while(rs.next()) { Student student = new Student(); student.setStudentId(rs.getInt("student_id")); diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAO.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAO.java index 11ecd84000..2560c01840 100644 --- a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAO.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAO.java @@ -57,7 +57,7 @@ public class EmployeeDAO { } public int addEmplyeeUsingSimpelJdbcInsert(final Employee emp) { - final Map parameters = new HashMap(); + final Map parameters = new HashMap<>(); parameters.put("ID", emp.getId()); parameters.put("FIRST_NAME", emp.getFirstName()); parameters.put("LAST_NAME", emp.getLastName()); @@ -68,7 +68,7 @@ public class EmployeeDAO { public Employee getEmployee(final int id) { final String query = "SELECT * FROM EMPLOYEE WHERE ID = ?"; - return jdbcTemplate.queryForObject(query, new Object[] { id }, new EmployeeRowMapper()); + return jdbcTemplate.queryForObject(query, new EmployeeRowMapper(), id); } public void addEmplyeeUsingExecuteMethod() { diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAO.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAO.java index 38b4a58355..9d6194936b 100644 --- a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAO.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/inclause/EmployeeDAO.java @@ -35,8 +35,7 @@ public class EmployeeDAO { String inSql = String.join(",", Collections.nCopies(ids.size(), "?")); List employees = jdbcTemplate.query( String.format("SELECT * FROM EMPLOYEE WHERE id IN (%s)", inSql), - ids.toArray(), - (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name"))); + (rs, rowNum) -> new Employee(rs.getInt("id"), rs.getString("first_name"), rs.getString("last_name")), ids.toArray()); return employees; } diff --git a/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/autogenkey/autogenkey-schema.sql b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/autogenkey/autogenkey-schema.sql index 925b27143c..6bd0cf1497 100644 --- a/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/autogenkey/autogenkey-schema.sql +++ b/persistence-modules/spring-jdbc/src/main/resources/com/baeldung/spring/jdbc/autogenkey/autogenkey-schema.sql @@ -1,5 +1,5 @@ CREATE TABLE IF NOT EXISTS sys_message ( - id bigint(20) NOT NULL AUTO_INCREMENT, + id bigint NOT NULL AUTO_INCREMENT, message varchar(100) NOT NULL, PRIMARY KEY (id) ); \ No newline at end of file diff --git a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java index 86a23ecc3e..71eb13fe75 100644 --- a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/autogenkey/GetAutoGenKeyByJDBC.java @@ -7,7 +7,6 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.spring.jdbc.autogenkey.repository.MessageRepositoryJDBCTemplate; diff --git a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java index b382895143..53cf40c118 100644 --- a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/guide/EmployeeDAOIntegrationTest.java @@ -81,7 +81,7 @@ public class EmployeeDAOIntegrationTest { @Test public void testBatchUpdateUsingJDBCTemplate() { - final List employees = new ArrayList(); + final List employees = new ArrayList<>(); final Employee emp1 = new Employee(); emp1.setId(10); emp1.setFirstName("firstName1"); @@ -113,7 +113,7 @@ public class EmployeeDAOIntegrationTest { @Test public void testBatchUpdateUsingNamedParameterJDBCTemplate() { - final List employees = new ArrayList(); + final List employees = new ArrayList<>(); final Employee emp1 = new Employee(); emp1.setId(40); emp1.setFirstName("firstName4"); diff --git a/persistence-modules/spring-jpa-2/pom.xml b/persistence-modules/spring-jpa-2/pom.xml index 9abf888fb2..c20c43912b 100644 --- a/persistence-modules/spring-jpa-2/pom.xml +++ b/persistence-modules/spring-jpa-2/pom.xml @@ -54,8 +54,8 @@ io.jsonwebtoken - jjwt - 0.9.1 + jjwt-api + 0.12.3 diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/multitenant/security/AuthenticationService.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/multitenant/security/AuthenticationService.java index 00db7eebc4..42eab1d6de 100644 --- a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/multitenant/security/AuthenticationService.java +++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/multitenant/security/AuthenticationService.java @@ -30,7 +30,7 @@ public class AuthenticationService { if (token != null) { String user = Jwts.parser() .setSigningKey(SIGNINGKEY) - .parseClaimsJws(token.replace(PREFIX, "")) + .build().parseClaimsJws(token.replace(PREFIX, "")) .getBody() .getSubject(); if (user != null) { @@ -48,9 +48,11 @@ public class AuthenticationService { } String tenant = Jwts.parser() .setSigningKey(SIGNINGKEY) - .parseClaimsJws(token.replace(PREFIX, "")) + .build().parseClaimsJws(token.replace(PREFIX, "")) .getBody() - .getAudience(); + .getAudience() + .iterator() + .next(); return tenant; } } diff --git a/persistence-modules/spring-mybatis/pom.xml b/persistence-modules/spring-mybatis/pom.xml index 1b2223653b..6de7cef347 100644 --- a/persistence-modules/spring-mybatis/pom.xml +++ b/persistence-modules/spring-mybatis/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -78,11 +78,12 @@ - 5.3.15 + 6.0.13 - 2.0.6 + 3.0.3 3.5.2 - 2.2.0 + 3.0.3 + true \ No newline at end of file diff --git a/persistence-modules/spring-mybatis/src/test/java/com/baeldung/mybatis/spring/ArticleMapperCommonUnitTest.java b/persistence-modules/spring-mybatis/src/test/java/com/baeldung/mybatis/spring/ArticleMapperCommonUnitTest.java index 2a93ca3d61..ab1cdce2aa 100644 --- a/persistence-modules/spring-mybatis/src/test/java/com/baeldung/mybatis/spring/ArticleMapperCommonUnitTest.java +++ b/persistence-modules/spring-mybatis/src/test/java/com/baeldung/mybatis/spring/ArticleMapperCommonUnitTest.java @@ -5,7 +5,7 @@ import org.springframework.beans.factory.annotation.Autowired; import static org.assertj.core.api.Assertions.assertThat; -class ArticleMapperCommonUnitTest { +abstract class ArticleMapperCommonUnitTest { @Autowired ArticleMapper articleMapper; diff --git a/pom.xml b/pom.xml index eb780e5168..62d33aca8e 100644 --- a/pom.xml +++ b/pom.xml @@ -332,8 +332,7 @@ parent-spring-4 parent-spring-5 parent-spring-6 - parent-java - + core-java-modules/core-java-8 @@ -351,7 +350,6 @@ - libraries-jdk8 @@ -409,8 +407,7 @@ parent-spring-4 parent-spring-5 parent-spring-6 - parent-java - + spring-4 spring-cloud-modules @@ -465,8 +462,7 @@ parent-spring-4 parent-spring-5 parent-spring-6 - parent-java - + apache-spark jenkins-modules @@ -505,8 +501,7 @@ parent-spring-4 parent-spring-5 parent-spring-6 - parent-java - + core-java-modules/core-java-8 @@ -524,8 +519,6 @@ - - libraries-jdk8 lombok-modules/lombok-custom @@ -572,8 +565,7 @@ parent-spring-4 parent-spring-5 parent-spring-6 - parent-java - + spring-4 spring-cloud-modules @@ -620,8 +612,7 @@ parent-spring-4 parent-spring-5 parent-spring-6 - parent-java - + apache-spark jenkins-modules @@ -692,7 +683,6 @@ akka-modules algorithms-modules - antlr apache-cxf-modules apache-httpclient-2 apache-httpclient4 @@ -706,10 +696,7 @@ apache-poi-3 apache-poi apache-thrift - apache-tika apache-velocity - asciidoctor - asm atomix aws-modules azure @@ -745,22 +732,15 @@ java-blockchain java-jdi - java-rmi - java-spi - java-websocket javafx javax-sound javaxval-2 javaxval jaxb - jersey jetbrains jgit - jib - jmeter jmh - jsf json-modules jsoup jws @@ -772,13 +752,17 @@ libraries-4 libraries-5 libraries-6 + libraries-7 libraries-ai libraries-apache-commons-2 libraries-apache-commons-collections libraries-apache-commons-io libraries-apache-commons + libraries-bytecode + libraries-cli libraries-concurrency libraries-data-2 + libraries-data-3 libraries-data-db libraries-data-io libraries-data @@ -788,11 +772,14 @@ libraries-io libraries-llms libraries-primitive + libraries-reporting libraries-rpc libraries-security libraries-server-2 libraries-server + libraries-stream libraries-testing + libraries-testing-2 libraries-transform libraries lightrun @@ -813,11 +800,9 @@ osgi parent-boot-3 patterns-modules - pdf-2 - pdf performance-tests persistence-modules - persistence-modules/java-harperdb + persistence-modules/spring-data-neo4j protobuffer quarkus-modules @@ -835,6 +820,7 @@ spring-5 spring-activiti spring-actuator + spring-ai spring-aop-2 spring-batch-2 @@ -895,12 +881,14 @@ tensorflow-java testing-modules testing-modules/mockito-simple + text-processing-libraries-modules + timefold-solver vaadin vavr-modules vertx-modules web-modules webrtc - + xml-2 xml xstream @@ -938,7 +926,6 @@ akka-modules algorithms-modules - antlr apache-cxf-modules apache-httpclient-2 apache-httpclient4 @@ -952,10 +939,7 @@ apache-poi-3 apache-poi apache-thrift - apache-tika apache-velocity - asciidoctor - asm atomix aws-modules azure @@ -991,22 +975,15 @@ java-blockchain java-jdi - java-rmi - java-spi - java-websocket javafx javax-sound javaxval-2 javaxval jaxb - jersey jetbrains jgit - jib - jmeter jmh - jsf json-modules jsoup jws @@ -1018,13 +995,17 @@ libraries-4 libraries-5 libraries-6 + libraries-7 libraries-ai libraries-apache-commons-2 libraries-apache-commons-collections libraries-apache-commons-io libraries-apache-commons + libraries-bytecode + libraries-cli libraries-concurrency libraries-data-2 + libraries-data-3 libraries-data-db libraries-data-io libraries-data @@ -1034,11 +1015,14 @@ libraries-io libraries-llms libraries-primitive + libraries-reporting libraries-rpc libraries-security libraries-server-2 libraries-server + libraries-stream libraries-testing + libraries-testing-2 libraries-transform libraries lightrun @@ -1059,8 +1043,6 @@ osgi parent-boot-3 patterns-modules - pdf-2 - pdf performance-tests persistence-modules persistence-modules/spring-data-neo4j @@ -1080,6 +1062,7 @@ spring-5 spring-activiti spring-actuator + spring-ai spring-aop-2 spring-batch-2 @@ -1139,12 +1122,14 @@ tensorflow-java testing-modules testing-modules/mockito-simple + text-processing-libraries-modules + timefold-solver vaadin vavr-modules vertx-modules web-modules webrtc - + xml-2 xml xstream @@ -1165,7 +1150,6 @@ parent-spring-4 parent-spring-5 parent-spring-6 - parent-java @@ -1206,7 +1190,7 @@ 2.22.2 - 3.11.0 + 3.12.1 3.1.0 1.8 1.2.17 diff --git a/quarkus-modules/quarkus-funqy/pom.xml b/quarkus-modules/quarkus-funqy/pom.xml index f5ba9d08d8..dbccc5e987 100644 --- a/quarkus-modules/quarkus-funqy/pom.xml +++ b/quarkus-modules/quarkus-funqy/pom.xml @@ -13,6 +13,7 @@ quarkus-modules 1.0.0-SNAPSHOT + @@ -24,6 +25,7 @@ + io.quarkus @@ -48,6 +50,7 @@ test + @@ -86,6 +89,7 @@ + native @@ -134,4 +138,5 @@ 2.16.0.Final 3.0.0-M7 + diff --git a/reactor-core/pom.xml b/reactor-core/pom.xml index dd7533fe73..7bf34c93ad 100644 --- a/reactor-core/pom.xml +++ b/reactor-core/pom.xml @@ -29,7 +29,7 @@ io.projectreactor.addons reactor-extra - ${reactor.version} + ${reactor-extra.version} org.projectlombok @@ -40,7 +40,8 @@ - 3.5.1 + 3.6.0 + 3.5.1 \ No newline at end of file diff --git a/rxjava-modules/pom.xml b/rxjava-modules/pom.xml index 2f2597b644..160bbb327a 100644 --- a/rxjava-modules/pom.xml +++ b/rxjava-modules/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java + parent-modules + 1.0.0-SNAPSHOT diff --git a/security-modules/jjwt/pom.xml b/security-modules/jjwt/pom.xml index 3ea4a46b8a..3693eaf9c4 100644 --- a/security-modules/jjwt/pom.xml +++ b/security-modules/jjwt/pom.xml @@ -35,13 +35,23 @@ io.jsonwebtoken - jjwt + jjwt-api + ${jjwt.version} + + + io.jsonwebtoken + jjwt-impl + ${jjwt.version} + + + io.jsonwebtoken + jjwt-jackson ${jjwt.version} - 0.7.0 + 0.12.3 \ No newline at end of file diff --git a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java index e453f33d5e..c0f176034e 100644 --- a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java +++ b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/config/WebSecurityConfig.java @@ -66,7 +66,7 @@ public class WebSecurityConfig { // CsrfFilter already made sure the token matched. Here, we'll make sure it's not expired try { Jwts.parser() - .setSigningKeyResolver(secretService.getSigningKeyResolver()) + .setSigningKeyResolver(secretService.getSigningKeyResolver()).build() .parseClaimsJws(token.getToken()); } catch (JwtException e) { // most likely an ExpiredJwtException, but this will handle any diff --git a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java index 3d157827d1..1c29a753b6 100644 --- a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java +++ b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/DynamicJWTController.java @@ -4,7 +4,7 @@ import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; -import io.jsonwebtoken.impl.compression.CompressionCodecs; +import io.jsonwebtoken.impl.compression.DeflateCompressionAlgorithm; import io.jsonwebtoken.jjwtfun.model.JwtResponse; import io.jsonwebtoken.jjwtfun.service.SecretService; import org.springframework.beans.factory.annotation.Autowired; @@ -38,7 +38,7 @@ public class DynamicJWTController extends BaseController { public JwtResponse dynamicBuildercompress(@RequestBody Map claims) throws UnsupportedEncodingException { String jws = Jwts.builder() .setClaims(claims) - .compressWith(CompressionCodecs.DEFLATE) + .compressWith(new DeflateCompressionAlgorithm()) .signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes()) .compact(); return new JwtResponse(jws); diff --git a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/SecretsController.java b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/SecretsController.java index 1ca0973c33..4975385398 100644 --- a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/SecretsController.java +++ b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/SecretsController.java @@ -6,6 +6,7 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import java.security.NoSuchAlgorithmException; import java.util.Map; import static org.springframework.web.bind.annotation.RequestMethod.GET; @@ -23,7 +24,7 @@ public class SecretsController extends BaseController { } @RequestMapping(value = "/refresh-secrets", method = GET) - public Map refreshSecrets() { + public Map refreshSecrets() throws NoSuchAlgorithmException { return secretService.refreshSecrets(); } diff --git a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java index efafa4b1b7..4ff71a620e 100644 --- a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java +++ b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/controller/StaticJWTController.java @@ -42,7 +42,7 @@ public class StaticJWTController extends BaseController { public JwtResponse parser(@RequestParam String jwt) throws UnsupportedEncodingException { Jws jws = Jwts.parser() - .setSigningKeyResolver(secretService.getSigningKeyResolver()) + .setSigningKeyResolver(secretService.getSigningKeyResolver()).build() .parseClaimsJws(jwt); return new JwtResponse(jws); @@ -53,7 +53,7 @@ public class StaticJWTController extends BaseController { Jws jws = Jwts.parser() .requireIssuer("Stormpath") .require("hasMotorcycle", true) - .setSigningKeyResolver(secretService.getSigningKeyResolver()) + .setSigningKeyResolver(secretService.getSigningKeyResolver()).build() .parseClaimsJws(jwt); return new JwtResponse(jws); diff --git a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java index 4426a4b9b0..958d6fb48f 100644 --- a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java +++ b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/service/SecretService.java @@ -6,12 +6,14 @@ import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.SigningKeyResolver; import io.jsonwebtoken.SigningKeyResolverAdapter; import io.jsonwebtoken.impl.TextCodec; -import io.jsonwebtoken.impl.crypto.MacProvider; import io.jsonwebtoken.lang.Assert; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; +import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; + +import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.Map; @@ -28,7 +30,7 @@ public class SecretService { }; @PostConstruct - public void setup() { + public void setup() throws NoSuchAlgorithmException { refreshSecrets(); } @@ -42,32 +44,34 @@ public class SecretService { public void setSecrets(Map secrets) { Assert.notNull(secrets); - Assert.hasText(secrets.get(SignatureAlgorithm.HS256.getValue())); - Assert.hasText(secrets.get(SignatureAlgorithm.HS384.getValue())); - Assert.hasText(secrets.get(SignatureAlgorithm.HS512.getValue())); + Assert.hasText(secrets.get(SignatureAlgorithm.HS256.getJcaName())); + Assert.hasText(secrets.get(SignatureAlgorithm.HS384.getJcaName())); + Assert.hasText(secrets.get(SignatureAlgorithm.HS512.getJcaName())); this.secrets = secrets; } public byte[] getHS256SecretBytes() { - return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS256.getValue())); + return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS256.getJcaName())); } public byte[] getHS384SecretBytes() { - return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getValue())); + return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getJcaName())); } public byte[] getHS512SecretBytes() { - return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS512.getValue())); + return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS512.getJcaName())); } - public Map refreshSecrets() { - SecretKey key = MacProvider.generateKey(SignatureAlgorithm.HS256); - secrets.put(SignatureAlgorithm.HS256.getValue(), TextCodec.BASE64.encode(key.getEncoded())); - key = MacProvider.generateKey(SignatureAlgorithm.HS384); - secrets.put(SignatureAlgorithm.HS384.getValue(), TextCodec.BASE64.encode(key.getEncoded())); - key = MacProvider.generateKey(SignatureAlgorithm.HS512); - secrets.put(SignatureAlgorithm.HS512.getValue(), TextCodec.BASE64.encode(key.getEncoded())); + public Map refreshSecrets() throws NoSuchAlgorithmException { + SecretKey key = KeyGenerator.getInstance(SignatureAlgorithm.HS256.getJcaName()).generateKey(); + secrets.put(SignatureAlgorithm.HS256.getJcaName(), TextCodec.BASE64.encode(key.getEncoded())); + + key = KeyGenerator.getInstance(SignatureAlgorithm.HS384.getJcaName()).generateKey(); + secrets.put(SignatureAlgorithm.HS384.getJcaName(), TextCodec.BASE64.encode(key.getEncoded())); + + key = KeyGenerator.getInstance(SignatureAlgorithm.HS512.getJcaName()).generateKey(); + secrets.put(SignatureAlgorithm.HS512.getJcaName(), TextCodec.BASE64.encode(key.getEncoded())); return secrets; } } diff --git a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java index 0fbf7637dd..2fc97b0b51 100644 --- a/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java +++ b/security-modules/jjwt/src/main/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtil.java @@ -1,12 +1,14 @@ package io.jsonwebtoken.jjwtfun.util; +import io.jsonwebtoken.Jwt; +import io.jsonwebtoken.JwtParser; +import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; -import io.jsonwebtoken.impl.crypto.DefaultJwtSignatureValidator; import javax.crypto.spec.SecretKeySpec; + import java.util.Base64; -import static io.jsonwebtoken.SignatureAlgorithm.HS256; public class JWTDecoderUtil { @@ -21,26 +23,19 @@ public class JWTDecoderUtil { return header + " " + payload; } - public static String decodeJWTToken(String token, String secretKey) throws Exception { - Base64.Decoder decoder = Base64.getUrlDecoder(); + public static boolean isTokenValid(String token, String secretKey) throws Exception { + SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), SignatureAlgorithm.HS256.getJcaName()); - String[] chunks = token.split("\\."); + JwtParser jwtParser = Jwts.parser() + .verifyWith(secretKeySpec) + .build(); - String header = new String(decoder.decode(chunks[0])); - String payload = new String(decoder.decode(chunks[1])); - - String tokenWithoutSignature = chunks[0] + "." + chunks[1]; - String signature = chunks[2]; - - SignatureAlgorithm sa = HS256; - SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), sa.getJcaName()); - - DefaultJwtSignatureValidator validator = new DefaultJwtSignatureValidator(sa, secretKeySpec); - - if (!validator.isValid(tokenWithoutSignature, signature)) { - throw new Exception("Could not verify JWT token integrity!"); + try { + jwtParser.parse(token); + } catch (Exception e) { + throw new Exception("Could not verify JWT token integrity!", e); } - return header + " " + payload; + return true; } } diff --git a/security-modules/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtilUnitTest.java b/security-modules/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtilUnitTest.java index 3103a6c8a3..4cdfdc59ba 100644 --- a/security-modules/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtilUnitTest.java +++ b/security-modules/jjwt/src/test/java/io/jsonwebtoken/jjwtfun/util/JWTDecoderUtilUnitTest.java @@ -1,16 +1,16 @@ package io.jsonwebtoken.jjwtfun.util; import io.jsonwebtoken.SignatureAlgorithm; -import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertTrue; class JWTDecoderUtilUnitTest { private final static String SIMPLE_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZWxkdW5nIFVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9"; - private final static String SIGNED_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZWxkdW5nIFVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.qH7Zj_m3kY69kxhaQXTa-ivIpytKXXjZc1ZSmapZnGE"; + private final static String SIGNED_TOKEN = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZWxkdW5nIFVzZXIiLCJpYXQiOjE1MTYyMzkwMjJ9.6h_QYBTbyKxfMq3TGiAhVI416rctV0c0SpzWxVm-0-Y"; @Test void givenSimpleToken_whenDecoding_thenStringOfHeaderPayloadAreReturned() { @@ -20,13 +20,13 @@ class JWTDecoderUtilUnitTest { @Test void givenSignedToken_whenDecodingWithInvalidSecret_thenIntegrityIsNotValidated() { - assertThatThrownBy(() -> JWTDecoderUtil.decodeJWTToken(SIGNED_TOKEN, "BAD_SECRET")) + assertThatThrownBy(() -> JWTDecoderUtil. + isTokenValid(SIGNED_TOKEN, "BAD_SECRET")) .hasMessage("Could not verify JWT token integrity!"); } @Test void givenSignedToken_whenDecodingWithValidSecret_thenIntegrityIsValidated() throws Exception { - assertThat(JWTDecoderUtil.decodeJWTToken(SIGNED_TOKEN, "MySecretKey")) - .contains("Baeldung User"); + assertTrue(JWTDecoderUtil.isTokenValid(SIGNED_TOKEN, "randomSecretWithSome!!CharacterS!")); } } diff --git a/spring-4/pom.xml b/spring-4/pom.xml index ad05123543..9a50319d13 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -121,7 +121,7 @@ 1.0.1 3.6 2.4.0 - 4.0.3 + 5.1.0 2.17.1 diff --git a/spring-5/pom.xml b/spring-5/pom.xml index 1ac696e7bd..65f1b77520 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -143,7 +143,7 @@ 1.0 1.5.6 ${project.build.directory}/generated-snippets - 4.0.3 + 5.1.0 \ No newline at end of file diff --git a/spring-ai/.gitignore b/spring-ai/.gitignore new file mode 100644 index 0000000000..f475e4f82b --- /dev/null +++ b/spring-ai/.gitignore @@ -0,0 +1,12 @@ +#folders# +.idea +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear diff --git a/spring-ai/pom.xml b/spring-ai/pom.xml new file mode 100644 index 0000000000..d0e8ab2d1b --- /dev/null +++ b/spring-ai/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + spring-ai + spring-ai + war + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../parent-boot-3 + + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + + + org.springframework.experimental.ai + spring-ai-openai-spring-boot-starter + 0.7.1-SNAPSHOT + + + org.springframework.boot + spring-boot-starter-web + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + com.baeldung.spring.ai.SpringAIProjectApplication + JAR + + + + org.apache.maven.plugins + maven-compiler-plugin + + 16 + 16 + + **/*ManualTest.java + + + + + + diff --git a/spring-ai/postman/Spring_AI_Poetry.postman_environment.json b/spring-ai/postman/Spring_AI_Poetry.postman_environment.json new file mode 100644 index 0000000000..b3d4a00bee --- /dev/null +++ b/spring-ai/postman/Spring_AI_Poetry.postman_environment.json @@ -0,0 +1,25 @@ +{ + "id": "df61838b-eb6f-4243-87ee-ca02c77e8646", + "name": "Spring_AI_Poetry", + "values": [ + { + "key": "baseUrl", + "value": "localhost:8080", + "type": "default", + "enabled": true + }, + { + "key": "genre", + "value": "liric", + "enabled": true + }, + { + "key": "theme", + "value": "flames", + "enabled": true + } + ], + "_postman_variable_scope": "environment", + "_postman_exported_at": "2023-11-26T19:49:21.755Z", + "_postman_exported_using": "Postman/10.20.3" +} \ No newline at end of file diff --git a/spring-ai/postman/spring-ai.postman_collection.json b/spring-ai/postman/spring-ai.postman_collection.json new file mode 100644 index 0000000000..b26652bb4e --- /dev/null +++ b/spring-ai/postman/spring-ai.postman_collection.json @@ -0,0 +1,56 @@ +{ + "info": { + "_postman_id": "f4282fac-bfe5-45b9-aae6-5ea7c43528ee", + "name": "spring-ai", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "9576856" + }, + "item": [ + { + "name": "Generate poetry with genre and theme", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/ai/poetry?genre={{genre}}&theme={{theme}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "ai", + "poetry" + ], + "query": [ + { + "key": "genre", + "value": "{{genre}}" + }, + { + "key": "theme", + "value": "{{theme}}" + } + ] + } + }, + "response": [] + }, + { + "name": "Generate haiku about cats", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/ai/cathaiku", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "ai", + "cathaiku" + ] + } + }, + "response": [] + } + ] +} \ No newline at end of file diff --git a/spring-ai/src/main/java/com/baeldung/spring/ai/SpringAIProjectApplication.java b/spring-ai/src/main/java/com/baeldung/spring/ai/SpringAIProjectApplication.java new file mode 100644 index 0000000000..3dfa800d26 --- /dev/null +++ b/spring-ai/src/main/java/com/baeldung/spring/ai/SpringAIProjectApplication.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.ai; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SpringAIProjectApplication { + public static void main(String[] args) { SpringApplication.run(SpringAIProjectApplication.class, args);} +} diff --git a/spring-ai/src/main/java/com/baeldung/spring/ai/dto/PoetryDto.java b/spring-ai/src/main/java/com/baeldung/spring/ai/dto/PoetryDto.java new file mode 100644 index 0000000000..229d2b13f0 --- /dev/null +++ b/spring-ai/src/main/java/com/baeldung/spring/ai/dto/PoetryDto.java @@ -0,0 +1,3 @@ +package com.baeldung.spring.ai.dto; + +public record PoetryDto (String title, String poetry, String genre, String theme) {} diff --git a/spring-ai/src/main/java/com/baeldung/spring/ai/service/PoetryService.java b/spring-ai/src/main/java/com/baeldung/spring/ai/service/PoetryService.java new file mode 100644 index 0000000000..e2760b8950 --- /dev/null +++ b/spring-ai/src/main/java/com/baeldung/spring/ai/service/PoetryService.java @@ -0,0 +1,10 @@ +package com.baeldung.spring.ai.service; + +import com.baeldung.spring.ai.dto.PoetryDto; + +public interface PoetryService { + + String getCatHaiku(); + + PoetryDto getPoetryByGenreAndTheme(String genre, String theme); +} diff --git a/spring-ai/src/main/java/com/baeldung/spring/ai/service/impl/PoetryServiceImpl.java b/spring-ai/src/main/java/com/baeldung/spring/ai/service/impl/PoetryServiceImpl.java new file mode 100644 index 0000000000..791dba372e --- /dev/null +++ b/spring-ai/src/main/java/com/baeldung/spring/ai/service/impl/PoetryServiceImpl.java @@ -0,0 +1,50 @@ +package com.baeldung.spring.ai.service.impl; + +import com.baeldung.spring.ai.dto.PoetryDto; +import com.baeldung.spring.ai.service.PoetryService; +import org.springframework.ai.client.AiClient; +import org.springframework.ai.client.AiResponse; +import org.springframework.ai.parser.BeanOutputParser; +import org.springframework.ai.prompt.PromptTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.bind.annotation.GetMapping; + +@Service +public class PoetryServiceImpl implements PoetryService { + + public static final String WRITE_ME_HAIKU_ABOUT_CAT = """ + Write me Haiku about cat, + haiku should start with the word cat obligatory"""; + private final AiClient aiClient; + + @Autowired + public PoetryServiceImpl(AiClient aiClient) { + this.aiClient = aiClient; + } + @Override + public String getCatHaiku() { + return aiClient.generate(WRITE_ME_HAIKU_ABOUT_CAT); + } + + @Override + public PoetryDto getPoetryByGenreAndTheme(String genre, String theme) { + BeanOutputParser poetryDtoBeanOutputParser = new BeanOutputParser<>(PoetryDto.class); + + String promptString = """ + Write me {genre} poetry about {theme} + {format} + """; + + PromptTemplate promptTemplate = new PromptTemplate(promptString); + promptTemplate.add("genre", genre); + promptTemplate.add("theme", theme); + promptTemplate.add("format", poetryDtoBeanOutputParser.getFormat()); + + promptTemplate.setOutputParser(poetryDtoBeanOutputParser); + + AiResponse response = aiClient.generate(promptTemplate.create()); + return poetryDtoBeanOutputParser.parse(response.getGeneration().getText()); + } +} diff --git a/spring-ai/src/main/java/com/baeldung/spring/ai/web/ExceptionTranslator.java b/spring-ai/src/main/java/com/baeldung/spring/ai/web/ExceptionTranslator.java new file mode 100644 index 0000000000..55ba383fa6 --- /dev/null +++ b/spring-ai/src/main/java/com/baeldung/spring/ai/web/ExceptionTranslator.java @@ -0,0 +1,27 @@ +package com.baeldung.spring.ai.web; + +import com.theokanning.openai.OpenAiHttpException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ProblemDetail; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import java.util.Optional; + +@RestControllerAdvice +public class ExceptionTranslator extends ResponseEntityExceptionHandler { + + public static final String OPEN_AI_CLIENT_RAISED_EXCEPTION = "Open AI client raised exception"; + + @ExceptionHandler(OpenAiHttpException.class) + ProblemDetail handleOpenAiHttpException(OpenAiHttpException ex) { + HttpStatus status = Optional + .ofNullable(HttpStatus.resolve(ex.statusCode)) + .orElse(HttpStatus.BAD_REQUEST); + + ProblemDetail problemDetail = ProblemDetail.forStatusAndDetail(status, ex.getMessage()); + problemDetail.setTitle(OPEN_AI_CLIENT_RAISED_EXCEPTION); + return problemDetail; + } +} diff --git a/spring-ai/src/main/java/com/baeldung/spring/ai/web/PoetryController.java b/spring-ai/src/main/java/com/baeldung/spring/ai/web/PoetryController.java new file mode 100644 index 0000000000..27c1bad6e2 --- /dev/null +++ b/spring-ai/src/main/java/com/baeldung/spring/ai/web/PoetryController.java @@ -0,0 +1,39 @@ +package com.baeldung.spring.ai.web; + +import com.baeldung.spring.ai.dto.PoetryDto; +import com.baeldung.spring.ai.service.PoetryService; +import org.springframework.ai.client.AiClient; +import org.springframework.ai.client.AiResponse; +import org.springframework.ai.parser.BeanOutputParser; +import org.springframework.ai.prompt.PromptTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("ai") +public class PoetryController { + + private final PoetryService poetryService; + + @Autowired + public PoetryController(PoetryService poetryService) { + this.poetryService = poetryService; + } + + @GetMapping("/cathaiku") + public ResponseEntity generateHaiku(){ + return ResponseEntity.ok(poetryService.getCatHaiku()); + } + + @GetMapping("/poetry") + public ResponseEntity generatePoetry( + @RequestParam("genre") String genre, + @RequestParam("theme") String theme + ){ + return ResponseEntity.ok(poetryService.getPoetryByGenreAndTheme(genre, theme)); + } +} diff --git a/spring-ai/src/main/resources/application.yml b/spring-ai/src/main/resources/application.yml new file mode 100644 index 0000000000..ec3b936adc --- /dev/null +++ b/spring-ai/src/main/resources/application.yml @@ -0,0 +1,3 @@ +spring: + ai: + openai.api-key: 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 diff --git a/spring-ai/src/test/java/com/baeldung/spring/ai/web/PoetryControllerManualTest.java b/spring-ai/src/test/java/com/baeldung/spring/ai/web/PoetryControllerManualTest.java new file mode 100644 index 0000000000..23202e6bce --- /dev/null +++ b/spring-ai/src/test/java/com/baeldung/spring/ai/web/PoetryControllerManualTest.java @@ -0,0 +1,50 @@ +package com.baeldung.spring.ai.web; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.ai.client.AiClient; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import static org.hamcrest.Matchers.*; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@AutoConfigureMockMvc +@RunWith(SpringRunner.class) +@SpringBootTest +public class PoetryControllerManualTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper; + + @Autowired + private AiClient aiClient; + + @Test + public void givenGetCatHaiku_whenCallingAiClient_thenCorrect() throws Exception { + mockMvc.perform(get("/ai/cathaiku")) + .andExpect(status().isOk()) + .andExpect(content().string(containsStringIgnoringCase("cat"))); + } + + @Test + public void givenGetPoetryWithGenreAndTheme_whenCallingAiClient_thenCorrect() throws Exception { + String genre = "lyric"; + String theme = "coffee"; + mockMvc.perform(get("/ai/poetry?genre={genre}&theme={theme}", genre, theme)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.genre").value(containsStringIgnoringCase(genre))) + .andExpect(jsonPath("$.theme").value(containsStringIgnoringCase(theme))) + .andExpect(jsonPath("$.poetry").isNotEmpty()) + .andExpect(jsonPath("$.title").exists()); + } +} + diff --git a/spring-ai/src/test/resources/application.yml b/spring-ai/src/test/resources/application.yml new file mode 100644 index 0000000000..813348fec5 --- /dev/null +++ b/spring-ai/src/test/resources/application.yml @@ -0,0 +1,3 @@ +spring: + ai: + openai.api-key: "mock-key-token" diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index eaf04cf015..890edd6cc5 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -95,7 +95,7 @@ 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/README.md b/spring-boot-modules/spring-boot-3-2/README.md index 27f9281725..b461cd9913 100644 --- a/spring-boot-modules/spring-boot-3-2/README.md +++ b/spring-boot-modules/spring-boot-3-2/README.md @@ -1,3 +1,5 @@ ## Relevant Articles - [Spring Boot 3.1’s ConnectionDetails Abstraction](https://www.baeldung.com/spring-boot-3-1-connectiondetails-abstraction) - [@ConditionalOnThreading Annotation Spring](https://www.baeldung.com/spring-conditionalonthreading) +- [A Guide to RestClient in Spring Boot](https://www.baeldung.com/spring-boot-restclient) +- More articles: [[<-- prev]](/spring-boot-modules/spring-boot-3) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-3-2/pom.xml b/spring-boot-modules/spring-boot-3-2/pom.xml index e48b232a52..8878060a97 100644 --- a/spring-boot-modules/spring-boot-3-2/pom.xml +++ b/spring-boot-modules/spring-boot-3-2/pom.xml @@ -282,6 +282,7 @@ + com.baeldung.restclient.RestClientApplication 1.6.0.Beta1 2.0.0 3.0.0-M7 diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/Article.java b/spring-boot-modules/spring-boot-3-2/src/main/java/com/baeldung/restclient/Article.java similarity index 100% rename from spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/Article.java rename to spring-boot-modules/spring-boot-3-2/src/main/java/com/baeldung/restclient/Article.java diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleController.java b/spring-boot-modules/spring-boot-3-2/src/main/java/com/baeldung/restclient/ArticleController.java similarity index 75% rename from spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleController.java rename to spring-boot-modules/spring-boot-3-2/src/main/java/com/baeldung/restclient/ArticleController.java index 5e1dff6fd7..c2d87a558c 100644 --- a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleController.java +++ b/spring-boot-modules/spring-boot-3-2/src/main/java/com/baeldung/restclient/ArticleController.java @@ -1,13 +1,20 @@ package com.baeldung.restclient; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Objects; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + @RestController @RequestMapping("/articles") public class ArticleController { diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleNotFoundException.java b/spring-boot-modules/spring-boot-3-2/src/main/java/com/baeldung/restclient/ArticleNotFoundException.java similarity index 100% rename from spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/ArticleNotFoundException.java rename to spring-boot-modules/spring-boot-3-2/src/main/java/com/baeldung/restclient/ArticleNotFoundException.java diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/InvalidArticleResponseException.java b/spring-boot-modules/spring-boot-3-2/src/main/java/com/baeldung/restclient/InvalidArticleResponseException.java similarity index 100% rename from spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/InvalidArticleResponseException.java rename to spring-boot-modules/spring-boot-3-2/src/main/java/com/baeldung/restclient/InvalidArticleResponseException.java diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/RestClientApplication.java b/spring-boot-modules/spring-boot-3-2/src/main/java/com/baeldung/restclient/RestClientApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/restclient/RestClientApplication.java rename to spring-boot-modules/spring-boot-3-2/src/main/java/com/baeldung/restclient/RestClientApplication.java diff --git a/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java index 1a615faf4e..3e12215bcb 100644 --- a/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java @@ -1,7 +1,10 @@ package com.baeldung.restclient; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; + import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -14,11 +17,8 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestClient; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class RestClientIntegrationTest { diff --git a/spring-boot-modules/spring-boot-3-url-matching/pom.xml b/spring-boot-modules/spring-boot-3-url-matching/pom.xml index 43f89eab47..42bd8583b3 100644 --- a/spring-boot-modules/spring-boot-3-url-matching/pom.xml +++ b/spring-boot-modules/spring-boot-3-url-matching/pom.xml @@ -96,8 +96,8 @@ 6.0.6 3.1.0 - 3.5.4 - 3.5.4> + 3.6.0 + 3.6.0> 3.0.0-M7 diff --git a/spring-boot-modules/spring-boot-3/README.md b/spring-boot-modules/spring-boot-3/README.md index ded5db30e4..ff00a506cf 100644 --- a/spring-boot-modules/spring-boot-3/README.md +++ b/spring-boot-modules/spring-boot-3/README.md @@ -8,4 +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) -- [A Guide to RestClient in Spring Boot](https://www.baeldung.com/spring-boot-restclient) + +- More articles: [[next -->]](/spring-boot-modules/spring-boot-3-2) diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/springjunitconfiguration/Person.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/springjunitconfiguration/Person.java new file mode 100644 index 0000000000..097af2ad1c --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/springjunitconfiguration/Person.java @@ -0,0 +1,15 @@ +package com.baeldung.springjunitconfiguration; + +public class Person { + + String name; + + public Person(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + +} \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigIntegrationTest.java b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/springjunitconfiguration/SpringJUnitConfigIntegrationTest.java similarity index 94% rename from spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigIntegrationTest.java rename to spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/springjunitconfiguration/SpringJUnitConfigIntegrationTest.java index 5f81c94aa0..a163ef893c 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitConfigIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/springjunitconfiguration/SpringJUnitConfigIntegrationTest.java @@ -1,6 +1,4 @@ -package com.baeldung.jupiter; - -import static org.junit.Assert.assertNotNull; +package com.baeldung.springjunitconfiguration; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -8,9 +6,11 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; +import static org.junit.Assert.assertNotNull; + /** * @SpringJUnitConfig(SpringJUnitConfigTest.Config.class) is equivalent to: - * + * * @ExtendWith(SpringExtension.class) * @ContextConfiguration(classes = SpringJUnitConfigTest.Config.class ) * @@ -18,10 +18,6 @@ import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @SpringJUnitConfig(SpringJUnitConfigIntegrationTest.Config.class) public class SpringJUnitConfigIntegrationTest { - @Configuration - static class Config { - } - @Autowired private ApplicationContext applicationContext; @@ -30,4 +26,8 @@ public class SpringJUnitConfigIntegrationTest { assertNotNull(applicationContext); } + @Configuration + static class Config { + } + } diff --git a/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/springjunitconfiguration/SpringJUnitConfigurationUnitTest.java b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/springjunitconfiguration/SpringJUnitConfigurationUnitTest.java new file mode 100644 index 0000000000..79486e6b3e --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/springjunitconfiguration/SpringJUnitConfigurationUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.springjunitconfiguration; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringJUnitConfig(classes = TestConfig.class, loader = AnnotationConfigContextLoader.class) +public class SpringJUnitConfigurationUnitTest { + + @ParameterizedTest + @ValueSource(strings = { "Dilbert", "Wally" }) + void givenPeopleList_whenSetPeopleWithName_thenListContainsOnePerson(String name, @Autowired List people) { + assertThat(people.stream() + .map(Person::getName) + .filter(name::equals)).hasSize(1); + } +} diff --git a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigIntegrationTest.java b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/springjunitconfiguration/SpringJUnitWebConfigIntegrationTest.java similarity index 94% rename from spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigIntegrationTest.java rename to spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/springjunitconfiguration/SpringJUnitWebConfigIntegrationTest.java index 4c3ffda203..0ccb988e0a 100644 --- a/spring-5/src/test/java/com/baeldung/jupiter/SpringJUnitWebConfigIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/springjunitconfiguration/SpringJUnitWebConfigIntegrationTest.java @@ -1,6 +1,4 @@ -package com.baeldung.jupiter; - -import static org.junit.Assert.assertNotNull; +package com.baeldung.springjunitconfiguration; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -8,9 +6,11 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig; import org.springframework.web.context.WebApplicationContext; +import static org.junit.Assert.assertNotNull; + /** * @SpringJUnitWebConfig(SpringJUnitWebConfigTest.Config.class) is equivalent to: - * + * * @ExtendWith(SpringExtension.class) * @WebAppConfiguration * @ContextConfiguration(classes = SpringJUnitWebConfigTest.Config.class ) @@ -19,10 +19,6 @@ import org.springframework.web.context.WebApplicationContext; @SpringJUnitWebConfig(SpringJUnitWebConfigIntegrationTest.Config.class) public class SpringJUnitWebConfigIntegrationTest { - @Configuration - static class Config { - } - @Autowired private WebApplicationContext webAppContext; @@ -31,4 +27,8 @@ public class SpringJUnitWebConfigIntegrationTest { assertNotNull(webAppContext); } + @Configuration + static class Config { + } + } diff --git a/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/springjunitconfiguration/TestConfig.java b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/springjunitconfiguration/TestConfig.java new file mode 100644 index 0000000000..859aff9d9b --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/springjunitconfiguration/TestConfig.java @@ -0,0 +1,19 @@ +package com.baeldung.springjunitconfiguration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class TestConfig { + + @Bean + Person dilbert() { + return new Person("Dilbert"); + } + + @Bean + Person wally() { + return new Person("Wally"); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-crud/README.md b/spring-boot-modules/spring-boot-crud/README.md index 6b0032deb3..09c5d9ba3a 100644 --- a/spring-boot-modules/spring-boot-crud/README.md +++ b/spring-boot-modules/spring-boot-crud/README.md @@ -5,3 +5,4 @@ This module contains articles about Spring Boot CRUD Operations ### Relevant Articles: - [Spring Boot CRUD Application with Thymeleaf](https://www.baeldung.com/spring-boot-crud-thymeleaf) - [Using a Spring Boot Application as a Dependency](https://www.baeldung.com/spring-boot-dependency) +- [Differences Between Entities and DTOs](https://www.baeldung.com/java-entity-vs-dto) diff --git a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/Application.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/Application.java similarity index 54% rename from persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/Application.java rename to spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/Application.java index 47a18b557f..4a780ac17a 100644 --- a/persistence-modules/spring-data-jpa-repo/src/main/java/com/baeldung/Application.java +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/Application.java @@ -1,17 +1,12 @@ -package com.baeldung; +package com.baeldung.entitydtodifferences; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -import com.baeldung.boot.daos.impl.ExtendedRepositoryImpl; @SpringBootApplication -@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } - } diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/controller/UserController.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/controller/UserController.java new file mode 100644 index 0000000000..66cecacd9b --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/controller/UserController.java @@ -0,0 +1,39 @@ +package com.baeldung.entitydtodifferences.controller; + +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.entitydtodifferences.dto.UserCreationDto; +import com.baeldung.entitydtodifferences.dto.UserResponseDto; +import com.baeldung.entitydtodifferences.mapper.UserMapper; +import com.baeldung.entitydtodifferences.repository.UserRepository; + +@RestController +@RequestMapping("/users") +public class UserController { + + private final UserRepository userRepository; + + public UserController(UserRepository userRepository) { + this.userRepository = userRepository; + } + + @GetMapping + public List getUsers() { + return userRepository.findAll() + .stream() + .map(UserMapper::toDto) + .collect(Collectors.toList()); + } + + @PostMapping + public UserResponseDto createUser(@RequestBody UserCreationDto userCreationDto) { + return UserMapper.toDto(userRepository.save(UserMapper.toEntity(userCreationDto))); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/BookDto.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/BookDto.java new file mode 100644 index 0000000000..a5ee25f105 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/BookDto.java @@ -0,0 +1,30 @@ +package com.baeldung.entitydtodifferences.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class BookDto { + + @JsonProperty("NAME") + private final String name; + + @JsonProperty("AUTHOR") + private final String author; + + // Default constructor for Jackson deserialization + public BookDto() { + this(null, null); + } + + public BookDto(String name, String author) { + this.name = name; + this.author = author; + } + + public String getName() { + return name; + } + + public String getAuthor() { + return author; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserCreationDto.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserCreationDto.java new file mode 100644 index 0000000000..0859c042cf --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserCreationDto.java @@ -0,0 +1,48 @@ +package com.baeldung.entitydtodifferences.dto; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class UserCreationDto { + + @JsonProperty("FIRST_NAME") + private final String firstName; + + @JsonProperty("LAST_NAME") + private final String lastName; + + @JsonProperty("ADDRESS") + private final String address; + + @JsonProperty("BOOKS") + private final List books; + + // Default constructor for Jackson deserialization + public UserCreationDto() { + this(null, null, null, null); + } + + public UserCreationDto(String firstName, String lastName, String address, List books) { + this.firstName = firstName; + this.lastName = lastName; + this.address = address; + this.books = books; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public String getAddress() { + return address; + } + + public List getBooks() { + return books; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserResponseDto.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserResponseDto.java new file mode 100644 index 0000000000..910689dd41 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/dto/UserResponseDto.java @@ -0,0 +1,48 @@ +package com.baeldung.entitydtodifferences.dto; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class UserResponseDto { + + @JsonProperty("ID") + private final Long id; + + @JsonProperty("FIRST_NAME") + private final String firstName; + + @JsonProperty("LAST_NAME") + private final String lastName; + + @JsonProperty("BOOKS") + private final List books; + + // Default constructor for Jackson deserialization + public UserResponseDto() { + this(null, null, null, null); + } + + public UserResponseDto(Long id, String firstName, String lastName, List books) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + this.books = books; + } + + public Long getId() { + return id; + } + + public String getFirstName() { + return firstName; + } + + public String getLastName() { + return lastName; + } + + public List getBooks() { + return books; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/Book.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/Book.java new file mode 100644 index 0000000000..88e895467a --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/Book.java @@ -0,0 +1,39 @@ +package com.baeldung.entitydtodifferences.entity; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "books") +public class Book { + + @Id + private String name; + private String author; + + // Default constructor for JPA deserialization + public Book() { + } + + public Book(String name, String author) { + this.name = name; + this.author = author; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/User.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/User.java new file mode 100644 index 0000000000..6a404e9f1f --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/entity/User.java @@ -0,0 +1,90 @@ +package com.baeldung.entitydtodifferences.entity; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "users") +public class User { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String firstName; + private String lastName; + private String address; + + @OneToMany(cascade = CascadeType.ALL) + private List books; + + // Default constructor for JPA deserialization + public User() { + } + + public User(String firstName, String lastName, String address, List books) { + this.firstName = firstName; + this.lastName = lastName; + this.address = address; + this.books = books; + } + + public String getNameOfMostOwnedBook() { + Map bookOwnershipCount = books.stream() + .collect(Collectors.groupingBy(Book::getName, Collectors.counting())); + return bookOwnershipCount.entrySet() + .stream() + .max(Map.Entry.comparingByValue()) + .map(Map.Entry::getKey) + .orElse(null); + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getAddress() { + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public List getBooks() { + return books; + } + + public void setBooks(List books) { + this.books = books; + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/mapper/UserMapper.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/mapper/UserMapper.java new file mode 100644 index 0000000000..0c6899f98b --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/mapper/UserMapper.java @@ -0,0 +1,34 @@ +package com.baeldung.entitydtodifferences.mapper; + +import java.util.stream.Collectors; + +import com.baeldung.entitydtodifferences.dto.BookDto; +import com.baeldung.entitydtodifferences.dto.UserCreationDto; +import com.baeldung.entitydtodifferences.dto.UserResponseDto; +import com.baeldung.entitydtodifferences.entity.Book; +import com.baeldung.entitydtodifferences.entity.User; + +public class UserMapper { + + public static UserResponseDto toDto(User entity) { + return new UserResponseDto(entity.getId(), entity.getFirstName(), entity.getLastName(), entity.getBooks() + .stream() + .map(UserMapper::toDto) + .collect(Collectors.toList())); + } + + public static User toEntity(UserCreationDto dto) { + return new User(dto.getFirstName(), dto.getLastName(), dto.getAddress(), dto.getBooks() + .stream() + .map(UserMapper::toEntity) + .collect(Collectors.toList())); + } + + public static BookDto toDto(Book entity) { + return new BookDto(entity.getName(), entity.getAuthor()); + } + + public static Book toEntity(BookDto dto) { + return new Book(dto.getName(), dto.getAuthor()); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/repository/UserRepository.java b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/repository/UserRepository.java new file mode 100644 index 0000000000..4529de698e --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/main/java/com/baeldung/entitydtodifferences/repository/UserRepository.java @@ -0,0 +1,11 @@ +package com.baeldung.entitydtodifferences.repository; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import com.baeldung.entitydtodifferences.entity.User; + +@Repository +public interface UserRepository extends JpaRepository { + +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/ApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/ApplicationIntegrationTest.java new file mode 100644 index 0000000000..839bb381ec --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/ApplicationIntegrationTest.java @@ -0,0 +1,15 @@ +package com.baeldung.entitydtodifferences; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class ApplicationIntegrationTest { + + @Test + public void contextLoads() { + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/controller/UserControllerIntegrationTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/controller/UserControllerIntegrationTest.java new file mode 100644 index 0000000000..83e359e378 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/controller/UserControllerIntegrationTest.java @@ -0,0 +1,93 @@ +package com.baeldung.entitydtodifferences.controller; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import com.baeldung.entitydtodifferences.entity.Book; +import com.baeldung.entitydtodifferences.entity.User; +import com.baeldung.entitydtodifferences.repository.UserRepository; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@SpringBootTest +@AutoConfigureMockMvc +public class UserControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private UserRepository userRepository; + + @Autowired + private ObjectMapper objectMapper; + + @BeforeEach + public void beforeEach() { + userRepository.deleteAll(); + } + + @Test + public void givenUsersAreExisting_whenGetUsers_thenUsersAreReturned() throws Exception { + //given + Book book1 = new Book("Book1", "Author1"); + Book book2 = new Book("Book2", "Author2"); + User savedUser = userRepository.save(new User("John", "Doe", "123 Main St", Arrays.asList(book1, book2))); + String expectedJson = String.format( + "[{\"ID\":%s,\"FIRST_NAME\":\"John\",\"LAST_NAME\":\"Doe\",\"BOOKS\":[{\"NAME\":\"Book1\",\"AUTHOR\":\"Author1\"},{\"NAME\":\"Book2\",\"AUTHOR\":\"Author2\"}]}]", + savedUser.getId()); + //when + MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/users") + .contentType(MediaType.APPLICATION_JSON)) + .andReturn(); + //then + assertEquals(expectedJson, result.getResponse() + .getContentAsString()); + } + + @Test + public void givenValidUser_whenPostUser_thenUserIsCreated() throws Exception { + //given + String user = "{\"FIRST_NAME\":\"John\",\"LAST_NAME\":\"Doe\",\"BOOKS\":[{\"NAME\":\"Book1\",\"AUTHOR\":\"Author1\"},{\"NAME\":\"Book2\",\"AUTHOR\":\"Author2\"}]}"; + //when + MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/users") + .content(user) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON)) + .andReturn(); + JsonNode responseJson = objectMapper.readTree(result.getResponse() + .getContentAsString()); + //then + assertEquals("John", responseJson.get("FIRST_NAME") + .asText()); + assertEquals("Doe", responseJson.get("LAST_NAME") + .asText()); + assertTrue(responseJson.has("BOOKS")); + JsonNode booksArray = responseJson.get("BOOKS"); + assertEquals(2, booksArray.size()); + assertEquals("Book1", booksArray.get(0) + .get("NAME") + .asText()); + assertEquals("Author1", booksArray.get(0) + .get("AUTHOR") + .asText()); + assertEquals("Book2", booksArray.get(1) + .get("NAME") + .asText()); + assertEquals("Author2", booksArray.get(1) + .get("AUTHOR") + .asText()); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/BookUnitTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/BookUnitTest.java new file mode 100644 index 0000000000..60e229b7c9 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/BookUnitTest.java @@ -0,0 +1,19 @@ +package com.baeldung.entitydtodifferences.entity; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.Test; + +public class BookUnitTest { + + @Test + public void whenBookInitialized_thenInitializedCorrectly() { + //when + Book book = new Book("Book1", "Author1"); + //then + assertNotNull(book); + assertEquals("Book1", book.getName()); + assertEquals("Author1", book.getAuthor()); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/UserUnitTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/UserUnitTest.java new file mode 100644 index 0000000000..0d1efe7129 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/entity/UserUnitTest.java @@ -0,0 +1,51 @@ +package com.baeldung.entitydtodifferences.entity; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.Arrays; +import java.util.Collections; + +import org.junit.Test; + +public class UserUnitTest { + + @Test + public void whenUserInitialized_thenInitializedCorrectly() { + //when + Book book1 = new Book("Book1", "Author1"); + Book book2 = new Book("Book2", "Author2"); + User user = new User("John", "Doe", "123 Main St", Arrays.asList(book1, book2)); + //then + assertNotNull(user); + assertEquals("John", user.getFirstName()); + assertEquals("Doe", user.getLastName()); + assertEquals("123 Main St", user.getAddress()); + assertEquals(2, user.getBooks() + .size()); + } + + @Test + public void givenUserOwningMultipleBooks_whenGetNameOfMostOwnedBook_thenComputedCorrectly() { + //given + Book book1 = new Book("Book1", "Author1"); + Book book2 = new Book("Book2", "Author2"); + Book book3 = new Book("Book2", "Author3"); + User user = new User("John", "Doe", "123 Main St", Arrays.asList(book1, book2, book3)); + //when + String mostOwnedBook = user.getNameOfMostOwnedBook(); + //then + assertEquals("Book2", mostOwnedBook); + } + + @Test + public void givenUserWithNoBooks_henGetNameOfMostOwnedBook_thenReturnedNull() { + //given + User user = new User("John", "Doe", "123 Main St", Collections.emptyList()); + //when + String mostOwnedBook = user.getNameOfMostOwnedBook(); + //then + assertNull(mostOwnedBook); + } +} diff --git a/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/mapper/UserMapperUnitTest.java b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/mapper/UserMapperUnitTest.java new file mode 100644 index 0000000000..5154898877 --- /dev/null +++ b/spring-boot-modules/spring-boot-crud/src/test/java/com/baeldung/entitydtodifferences/mapper/UserMapperUnitTest.java @@ -0,0 +1,87 @@ +package com.baeldung.entitydtodifferences.mapper; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +import com.baeldung.entitydtodifferences.dto.BookDto; +import com.baeldung.entitydtodifferences.dto.UserCreationDto; +import com.baeldung.entitydtodifferences.dto.UserResponseDto; +import com.baeldung.entitydtodifferences.entity.Book; +import com.baeldung.entitydtodifferences.entity.User; + +public class UserMapperUnitTest { + + @Test + public void givenUserEntity_whenMappedToDto_thenMappedCorrectly() { + //given + Book book1 = new Book("Book1", "Author1"); + Book book2 = new Book("Book2", "Author2"); + User user = new User("John", "Doe", "123 Main St", Arrays.asList(book1, book2)); + //when + UserResponseDto userDto = UserMapper.toDto(user); + //then + assertEquals(user.getId(), userDto.getId()); + assertEquals(user.getFirstName(), userDto.getFirstName()); + assertEquals(user.getLastName(), userDto.getLastName()); + List bookDtos = userDto.getBooks(); + assertEquals(2, bookDtos.size()); + assertEquals(book1.getName(), bookDtos.get(0) + .getName()); + assertEquals(book1.getAuthor(), bookDtos.get(0) + .getAuthor()); + assertEquals(book2.getName(), bookDtos.get(1) + .getName()); + assertEquals(book2.getAuthor(), bookDtos.get(1) + .getAuthor()); + } + + @Test + public void givenUserDto_whenMappedToEntity_thenMappedCorrectly() { + //given + BookDto bookDto1 = new BookDto("Book3", "Author3"); + BookDto bookDto2 = new BookDto("Book4", "Author4"); + UserCreationDto userDto = new UserCreationDto("Jane", "Doe", "456 Oak St", Arrays.asList(bookDto1, bookDto2)); + //when + User user = UserMapper.toEntity(userDto); + //then + assertEquals(user.getFirstName(), userDto.getFirstName()); + assertEquals(user.getLastName(), userDto.getLastName()); + assertEquals(user.getAddress(), userDto.getAddress()); + List books = user.getBooks(); + assertEquals(2, books.size()); + assertEquals(bookDto1.getName(), books.get(0) + .getName()); + assertEquals(bookDto1.getAuthor(), books.get(0) + .getAuthor()); + assertEquals(bookDto2.getName(), books.get(1) + .getName()); + assertEquals(bookDto2.getAuthor(), books.get(1) + .getAuthor()); + } + + @Test + public void givenBookEntity_whenMappedToDto_thenMappedCorrectly() { + //given + Book book = new Book("Book5", "Author5"); + //when + BookDto bookDto = UserMapper.toDto(book); + //then + assertEquals(book.getName(), bookDto.getName()); + assertEquals(book.getAuthor(), bookDto.getAuthor()); + } + + @Test + public void givenBookDto_whenMappedToEntity_thenMappedCorrectly() { + //given + BookDto bookDto = new BookDto("Book6", "Author6"); + //when + Book book = UserMapper.toEntity(bookDto); + //then + assertEquals(bookDto.getName(), book.getName()); + assertEquals(bookDto.getAuthor(), book.getAuthor()); + } +} diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md index 8e6619dce4..b8f0347453 100644 --- a/spring-boot-modules/spring-boot-data-2/README.md +++ b/spring-boot-modules/spring-boot-data-2/README.md @@ -6,4 +6,4 @@ - [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) - [BootstrapMode for JPA Repositories](https://www.baeldung.com/jpa-bootstrap-mode) - [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) - +- [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/PropertyEditorApplication.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/PropertyEditorRestController.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCard.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/creditcard/CreditCardEditor.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/exotictype/editor/CustomExoticTypeEditor.java diff --git a/spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/propertyeditor/exotictype/model/ExoticType.java diff --git a/spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java b/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java similarity index 100% rename from spring-boot-modules/spring-boot-data/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java rename to spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/propertyeditor/creditcard/CreditCardEditorUnitTest.java diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/Application.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/Application.java new file mode 100644 index 0000000000..3072ca16ac --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/Application.java @@ -0,0 +1,8 @@ +package com.baeldung.jsonignore; + +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/absentfields/Employee.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/absentfields/Employee.java new file mode 100644 index 0000000000..5dbcd89cc0 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/absentfields/Employee.java @@ -0,0 +1,67 @@ +package com.baeldung.jsonignore.absentfields; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import java.util.Optional; + +@JsonInclude(Include.NON_ABSENT) +public class Employee { + + private String lastName; + private String firstName; + private long id; + private Optional salary; + + + public Employee() { + } + + public Employee(final long id, final String lastName, final String firstName, final Optional salary) { + this.id = id; + this.lastName = lastName; + this.firstName = firstName; + this.salary = salary; + } + + public String getLastName() { + return lastName; + } + + public String getFirstName() { + return firstName; + } + + public long getId() { + return id; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public void setId(final long id) { + this.id = id; + } + + public Optional getSalary() { + return salary; + } + + public void setSalary(final Optional salary) { + this.salary = salary; + } + + @Override + public String toString() { + return "Employee{" + + "lastName='" + lastName + '\'' + + ", firstName='" + firstName + '\'' + + ", id=" + id + + ", salary=" + salary + + '}'; + } +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/absentfields/Salary.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/absentfields/Salary.java new file mode 100644 index 0000000000..f9bbe1a225 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/absentfields/Salary.java @@ -0,0 +1,30 @@ +package com.baeldung.jsonignore.absentfields; + +import java.math.BigDecimal; + +public class Salary { + + private BigDecimal hourlyRate; + + public Salary() { + } + + public Salary(BigDecimal hourlyRate) { + this.hourlyRate = hourlyRate; + } + + public BigDecimal getHourlyRate() { + return hourlyRate; + } + + public void setHourlyRate(final BigDecimal hourlyRate) { + this.hourlyRate = hourlyRate; + } + + @Override + public String toString() { + return "Salary{" + + "hourlyRate=" + hourlyRate + + '}'; + } +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/controller/AbsentEmployeeEchoController.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/controller/AbsentEmployeeEchoController.java new file mode 100644 index 0000000000..d5d442154e --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/controller/AbsentEmployeeEchoController.java @@ -0,0 +1,19 @@ +package com.baeldung.jsonignore.controller; + +import com.baeldung.jsonignore.absentfields.Employee; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(AbsentEmployeeEchoController.USERS) +public class AbsentEmployeeEchoController { + + public static final String USERS = "/absent_employees"; + + @PostMapping + public Employee echoUser(@RequestBody Employee employee) { + return employee; + } +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/controller/EmployeeEchoController.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/controller/EmployeeEchoController.java new file mode 100644 index 0000000000..258b167265 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/controller/EmployeeEchoController.java @@ -0,0 +1,19 @@ +package com.baeldung.jsonignore.controller; + +import com.baeldung.jsonignore.nullfields.Employee; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(EmployeeEchoController.USERS) +public class EmployeeEchoController { + + public static final String USERS = "/employees"; + + @PostMapping + public Employee echoUser(@RequestBody Employee employee) { + return employee; + } +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/controller/EmptyEmployeeEchoController.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/controller/EmptyEmployeeEchoController.java new file mode 100644 index 0000000000..8024c653e0 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/controller/EmptyEmployeeEchoController.java @@ -0,0 +1,19 @@ +package com.baeldung.jsonignore.controller; + +import com.baeldung.jsonignore.emptyfields.Employee; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(EmptyEmployeeEchoController.USERS) +public class EmptyEmployeeEchoController { + + public static final String USERS = "/empty_employees"; + + @PostMapping + public Employee echoUser(@RequestBody Employee employee) { + return employee; + } +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/emptyfields/Employee.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/emptyfields/Employee.java new file mode 100644 index 0000000000..37171217d8 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/emptyfields/Employee.java @@ -0,0 +1,93 @@ +package com.baeldung.jsonignore.emptyfields; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +@JsonInclude(Include.NON_EMPTY) +public class Employee { + + private String lastName; + private String firstName; + private long id; + private Optional salary; + + private String phoneticName = ""; + + private List phoneNumbers = new ArrayList<>(); + + public Employee() { + } + + public Employee(final long id, final String lastName, final String firstName, + final Optional salary, final String phoneticName, final List phoneNumbers) { + this.id = id; + this.lastName = lastName; + this.firstName = firstName; + this.salary = salary; + this.phoneticName = phoneticName != null ? phoneticName : ""; + this.phoneNumbers.addAll(phoneNumbers); + } + + public String getLastName() { + return lastName; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public long getId() { + return id; + } + + public void setId(final long id) { + this.id = id; + } + + public Optional getSalary() { + return salary; + } + + public void setSalary(final Optional salary) { + this.salary = salary; + } + + public String getPhoneticName() { + return phoneticName; + } + + public void setPhoneticName(final String phoneticName) { + this.phoneticName = phoneticName; + } + + public List getPhoneNumbers() { + return phoneNumbers; + } + + public void setPhoneNumbers(final List phoneNumbers) { + this.phoneNumbers = phoneNumbers; + } + + @Override + public String toString() { + return "Employee{" + + "lastName='" + lastName + '\'' + + ", firstName='" + firstName + '\'' + + ", id=" + id + + ", salary=" + salary + + ", phoneticName='" + phoneticName + '\'' + + ", phoneNumbers=" + phoneNumbers + + '}'; + } +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/emptyfields/PhoneNumber.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/emptyfields/PhoneNumber.java new file mode 100644 index 0000000000..7353aed739 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/emptyfields/PhoneNumber.java @@ -0,0 +1,28 @@ +package com.baeldung.jsonignore.emptyfields; + +public class PhoneNumber { + + private String number; + + public PhoneNumber() { + } + + public PhoneNumber(final String number) { + this.number = number; + } + + public String getNumber() { + return number; + } + + public void setNumber(final String number) { + this.number = number; + } + + @Override + public String toString() { + return "PhoneNumber{" + + "number='" + number + '\'' + + '}'; + } +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/emptyfields/Salary.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/emptyfields/Salary.java new file mode 100644 index 0000000000..d66cbb365a --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/emptyfields/Salary.java @@ -0,0 +1,30 @@ +package com.baeldung.jsonignore.emptyfields; + +import java.math.BigDecimal; + +public class Salary { + + private BigDecimal hourlyRate; + + public Salary() { + } + + public Salary(BigDecimal hourlyRate) { + this.hourlyRate = hourlyRate; + } + + public BigDecimal getHourlyRate() { + return hourlyRate; + } + + public void setHourlyRate(final BigDecimal hourlyRate) { + this.hourlyRate = hourlyRate; + } + + @Override + public String toString() { + return "Salary{" + + "hourlyRate=" + hourlyRate + + '}'; + } +} diff --git a/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/nullfields/Employee.java b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/nullfields/Employee.java new file mode 100644 index 0000000000..7e8d3f1bb4 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/main/java/com/baeldung/jsonignore/nullfields/Employee.java @@ -0,0 +1,83 @@ +package com.baeldung.jsonignore.nullfields; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import java.util.Objects; + +@JsonInclude(Include.NON_NULL) +public class Employee { + + private String lastName; + private String firstName; + private long id; + + public Employee() { + } + + public Employee(final long id, final String firstName, final String lastName) { + this.id = id; + this.firstName = firstName; + this.lastName = lastName; + } + + public String getLastName() { + return lastName; + } + + public String getFirstName() { + return firstName; + } + + public long getId() { + return id; + } + + public void setLastName(final String lastName) { + this.lastName = lastName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public void setId(final long id) { + this.id = id; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + final Employee employee = (Employee) o; + + if (id != employee.id) { + return false; + } + if (!Objects.equals(lastName, employee.lastName)) { + return false; + } + return Objects.equals(firstName, employee.firstName); + } + + @Override + public int hashCode() { + int result = lastName != null ? lastName.hashCode() : 0; + result = 31 * result + (firstName != null ? firstName.hashCode() : 0); + result = 31 * result + (int) (id ^ (id >>> 32)); + return result; + } + + @Override + public String toString() { + return "User{" + + "lastName='" + lastName + '\'' + + ", firstName='" + firstName + '\'' + + ", id=" + id + + '}'; + } +} diff --git a/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/jsonignore/AbstractEmployeeEchoControllerBaseIntegrationTest.java b/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/jsonignore/AbstractEmployeeEchoControllerBaseIntegrationTest.java new file mode 100644 index 0000000000..13b181493d --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/jsonignore/AbstractEmployeeEchoControllerBaseIntegrationTest.java @@ -0,0 +1,123 @@ +package com.baeldung.jsonignore; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.baeldung.jsonignore.controller.AbsentEmployeeEchoController; +import com.baeldung.jsonignore.controller.EmployeeEchoController; +import com.baeldung.jsonignore.controller.EmptyEmployeeEchoController; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.lang.reflect.Field; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import org.junit.platform.commons.util.ReflectionUtils; +import org.junit.platform.commons.util.ReflectionUtils.HierarchyTraversalMode; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +@WebMvcTest(controllers = {EmployeeEchoController.class, AbsentEmployeeEchoController.class, + EmptyEmployeeEchoController.class}) +abstract class AbstractEmployeeEchoControllerBaseIntegrationTest { + + @Autowired + protected ObjectMapper mapper = new ObjectMapper(); + + @Autowired + protected MockMvc mockMvc; + + protected MvcResult sendRequestAndGetResult(final T expected, final String endpoint) throws Exception { + final String payload = mapper.writeValueAsString(expected); + return mockMvc.perform(post(endpoint) + .contentType(MediaType.APPLICATION_JSON) + .accept(MediaType.APPLICATION_JSON) + .content(payload)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); + } + + protected static void nonNullFieldsShouldNonBeMissing(final List nonNullFields, final JsonNode jsonNode) { + nonNullFields.forEach(nullField -> { + final JsonNode nameNode = jsonNode.path(nullField); + assertThat(nameNode.isMissingNode()).isFalse(); + }); + } + + protected static void nullFieldsShouldBeMissing(final List nullFields, final JsonNode jsonNode) { + nullFields.forEach(nullField -> { + final JsonNode nameNode = jsonNode.path(nullField); + assertThat(nameNode.isMissingNode()).isTrue(); + }); + } + + protected static List filterFieldsAndGetNames(final T object, final Predicate predicate) { + return ReflectionUtils.findFields(object.getClass(), predicate, HierarchyTraversalMode.BOTTOM_UP) + .stream().map(Field::getName).collect(Collectors.toList()); + } + + protected static boolean isFieldNull(final T object, final Field s) { + try { + if (Object.class.isAssignableFrom(s.getType())) { + s.setAccessible(true); + return s.get(object) == null; + } else { + return false; + } + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + protected static boolean isFieldAbsent(final T object, final Field s) { + try { + if (Optional.class.isAssignableFrom(s.getType())) { + s.setAccessible(true); + final Optional optional = ((Optional) s.get(object)); + if (optional != null) { + return !optional.isPresent(); + } else { + return false; + } + } else { + return false; + } + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + protected static boolean isFieldEmpty(final T object, final Field s) { + try { + if (String.class.isAssignableFrom(s.getType())) { + s.setAccessible(true); + final String string = ((String) s.get(object)); + if (string != null) { + return string.isEmpty(); + } else { + return false; + } + } else if (Collection.class.isAssignableFrom(s.getType())) { + s.setAccessible(true); + final Collection collection = ((Collection) s.get(object)); + if (collection != null) { + return collection.isEmpty(); + } else { + return false; + } + } else { + return false; + } + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/jsonignore/NonAbsentEmployeeFieldsEchoControllerIntegrationTest.java b/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/jsonignore/NonAbsentEmployeeFieldsEchoControllerIntegrationTest.java new file mode 100644 index 0000000000..52ebdca247 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/jsonignore/NonAbsentEmployeeFieldsEchoControllerIntegrationTest.java @@ -0,0 +1,50 @@ +package com.baeldung.jsonignore; + +import static com.baeldung.jsonignore.controller.AbsentEmployeeEchoController.USERS; + +import com.baeldung.jsonignore.absentfields.Employee; +import com.baeldung.jsonignore.absentfields.Salary; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.test.web.servlet.MvcResult; + +class NonAbsentEmployeeFieldsEchoControllerIntegrationTest extends AbstractEmployeeEchoControllerBaseIntegrationTest { + + @ParameterizedTest + @MethodSource + void giveEndpointWhenSendEmployeeThanReceiveThatUserBackIgnoringAbsentValues(final Employee expected) throws Exception { + final MvcResult result = sendRequestAndGetResult(expected, USERS); + final String response = result.getResponse().getContentAsString(); + validateJsonFields(expected, response); + } + + private void validateJsonFields(final Employee expected, final String response) throws JsonProcessingException { + final JsonNode jsonNode = mapper.readTree(response); + final Predicate nullField = s -> isFieldNull(expected, s); + final Predicate absentField = s -> isFieldAbsent(expected, s); + List nullOrAbsentFields = filterFieldsAndGetNames(expected, nullField.or(absentField)); + List nonNullAndNonAbsentFields = filterFieldsAndGetNames(expected, nullField.negate().and(absentField.negate())); + nullFieldsShouldBeMissing(nullOrAbsentFields, jsonNode); + nonNullFieldsShouldNonBeMissing(nonNullAndNonAbsentFields, jsonNode); + } + + static Stream giveEndpointWhenSendEmployeeThanReceiveThatUserBackIgnoringAbsentValues() { + final Salary baseSalary = new Salary(BigDecimal.TEN); + return Stream.of( + Arguments.of(new Employee(1L, "John", "Doe", Optional.empty())), + Arguments.of(new Employee(1L, null, "Doe", Optional.of(baseSalary))), + Arguments.of(new Employee(1L, "John", null, Optional.empty())), + Arguments.of(new Employee(1L, null, null, Optional.of(baseSalary))) + ); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/jsonignore/NonEmptyEmployeeFieldsEchoControllerIntegrationTest.java b/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/jsonignore/NonEmptyEmployeeFieldsEchoControllerIntegrationTest.java new file mode 100644 index 0000000000..12b328a3cb --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/jsonignore/NonEmptyEmployeeFieldsEchoControllerIntegrationTest.java @@ -0,0 +1,60 @@ +package com.baeldung.jsonignore; + +import static com.baeldung.jsonignore.controller.EmptyEmployeeEchoController.USERS; + +import com.baeldung.jsonignore.emptyfields.Employee; +import com.baeldung.jsonignore.emptyfields.PhoneNumber; +import com.baeldung.jsonignore.emptyfields.Salary; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.test.web.servlet.MvcResult; + +class NonEmptyEmployeeFieldsEchoControllerIntegrationTest extends AbstractEmployeeEchoControllerBaseIntegrationTest { + + @ParameterizedTest + @MethodSource + void giveEndpointWhenSendEmployeeThanReceiveThatUserBackIgnoringEmptyValues(final Employee expected) throws Exception { + final MvcResult result = sendRequestAndGetResult(expected, USERS); + final String response = result.getResponse().getContentAsString(); + validateJsonFields(expected, response); + } + + private void validateJsonFields(final Employee expected, final String response) throws JsonProcessingException { + final JsonNode jsonNode = mapper.readTree(response); + final Predicate nullField = s -> isFieldNull(expected, s); + final Predicate absentField = s -> isFieldAbsent(expected, s); + final Predicate emptyField = s -> isFieldEmpty(expected, s); + List nullOrAbsentOrEmptyFields = filterFieldsAndGetNames(expected, nullField.or(absentField).or(emptyField)); + List nonNullAndNonAbsentAndNonEmptyFields = filterFieldsAndGetNames(expected, + nullField.negate().and(absentField.negate().and(emptyField.negate()))); + nullFieldsShouldBeMissing(nullOrAbsentOrEmptyFields, jsonNode); + nonNullFieldsShouldNonBeMissing(nonNullAndNonAbsentAndNonEmptyFields, jsonNode); + } + + static Stream giveEndpointWhenSendEmployeeThanReceiveThatUserBackIgnoringEmptyValues() { + final Salary baseSalary = new Salary(BigDecimal.TEN); + final List phones = Arrays.asList(new PhoneNumber("123-456"), new PhoneNumber("789-012")); + return Stream.of( + Arguments.of(new Employee(1L, "John", "Doe", Optional.empty(), "ʤɒn dəʊ", new ArrayList<>())), + Arguments.of(new Employee(1L, null, "Doe", Optional.of(baseSalary), "dəʊ", new ArrayList<>())), + Arguments.of(new Employee(1L, "John", null, Optional.empty(), "ʤɒn", new ArrayList<>())), + Arguments.of(new Employee(1L, null, null, Optional.of(baseSalary), null, new ArrayList<>())), + Arguments.of(new Employee(1L, "John", "Doe", Optional.empty(), "ʤɒn dəʊ", phones)), + Arguments.of(new Employee(1L, null, "Doe", Optional.of(baseSalary), "dəʊ", phones)), + Arguments.of(new Employee(1L, "John", null, Optional.empty(), "ʤɒn", phones)), + Arguments.of(new Employee(1L, null, null, Optional.of(baseSalary), null, phones)) + ); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/jsonignore/NonNullEmployeeFieldsEchoControllerIntegrationTest.java b/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/jsonignore/NonNullEmployeeFieldsEchoControllerIntegrationTest.java new file mode 100644 index 0000000000..6bac80219d --- /dev/null +++ b/spring-boot-modules/spring-boot-data-3/src/test/java/com/baeldung/jsonignore/NonNullEmployeeFieldsEchoControllerIntegrationTest.java @@ -0,0 +1,45 @@ +package com.baeldung.jsonignore; + +import static com.baeldung.jsonignore.controller.EmployeeEchoController.USERS; + +import com.baeldung.jsonignore.nullfields.Employee; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import java.lang.reflect.Field; +import java.util.List; +import java.util.function.Predicate; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.test.web.servlet.MvcResult; + +class NonNullEmployeeFieldsEchoControllerIntegrationTest extends AbstractEmployeeEchoControllerBaseIntegrationTest { + + @ParameterizedTest + @MethodSource + void giveEndpointWhenSendEmployeeThanReceiveThatUserBackIgnoringNullValues(final Employee expected) throws Exception { + final MvcResult result = sendRequestAndGetResult(expected, USERS); + final String response = result.getResponse().getContentAsString(); + validateJsonFields(expected, response); + } + + private void validateJsonFields(final Employee expected, final String response) throws JsonProcessingException { + final JsonNode jsonNode = mapper.readTree(response); + final Predicate nullField = s -> isFieldNull(expected, s); + List nullFields = filterFieldsAndGetNames(expected, nullField); + List nonNullFields = filterFieldsAndGetNames(expected, nullField.negate()); + nullFieldsShouldBeMissing(nullFields, jsonNode); + nonNullFieldsShouldNonBeMissing(nonNullFields, jsonNode); + } + + static Stream giveEndpointWhenSendEmployeeThanReceiveThatUserBackIgnoringNullValues() { + return Stream.of( + Arguments.of(new Employee(1L, "John", "Doe")), + Arguments.of(new Employee(1L, null, "Doe")), + Arguments.of(new Employee(1L, "John", null)), + Arguments.of(new Employee(1L, null, null)) + ); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data/README.md b/spring-boot-modules/spring-boot-data/README.md index aa745b77a2..49a6eedbed 100644 --- a/spring-boot-modules/spring-boot-data/README.md +++ b/spring-boot-modules/spring-boot-data/README.md @@ -8,7 +8,6 @@ This module contains articles about Spring Boot with Spring Data - [Rendering Exceptions in JSON with Spring](https://www.baeldung.com/spring-exceptions-json) - [Disable Spring Data Auto Configuration](https://www.baeldung.com/spring-data-disable-auto-config) - [Repositories with Multiple Spring Data Modules](https://www.baeldung.com/spring-multiple-data-modules) -- [Spring Custom Property Editor](https://www.baeldung.com/spring-mvc-custom-property-editor) - [Using @JsonComponent in Spring Boot](https://www.baeldung.com/spring-boot-jsoncomponent) - [Guide To Running Logic on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) - [Spring Boot: Customize the Jackson ObjectMapper](https://www.baeldung.com/spring-boot-customize-jackson-objectmapper) diff --git a/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/converter/CaseInsensitiveWeekDayConverter.java b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/converter/CaseInsensitiveWeekDayConverter.java new file mode 100644 index 0000000000..8b06fedc78 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/converter/CaseInsensitiveWeekDayConverter.java @@ -0,0 +1,16 @@ +package com.baeldung.caseinsensitiveenum.converter; + +import com.baeldung.caseinsensitiveenum.week.WeekDays; +import org.springframework.core.convert.converter.Converter; + +public class CaseInsensitiveWeekDayConverter implements Converter { + + @Override + public WeekDays convert(final String source) { + try { + return WeekDays.valueOf(source.trim()); + } catch (IllegalArgumentException exception) { + return WeekDays.valueOf(source.trim().toUpperCase()); + } + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/converter/StrictNullableWeekDayConverter.java b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/converter/StrictNullableWeekDayConverter.java new file mode 100644 index 0000000000..dd9f7fb92a --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/converter/StrictNullableWeekDayConverter.java @@ -0,0 +1,15 @@ +package com.baeldung.caseinsensitiveenum.converter; + +import com.baeldung.caseinsensitiveenum.week.WeekDays; +import org.springframework.core.convert.converter.Converter; + +public class StrictNullableWeekDayConverter implements Converter { + @Override + public WeekDays convert(final String source) { + try { + return WeekDays.valueOf(source.trim()); + } catch (IllegalArgumentException e) { + return null; + } + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/nonconventionalweek/NonConventionalWeekDays.java b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/nonconventionalweek/NonConventionalWeekDays.java new file mode 100644 index 0000000000..72e1589de7 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/nonconventionalweek/NonConventionalWeekDays.java @@ -0,0 +1,5 @@ +package com.baeldung.caseinsensitiveenum.nonconventionalweek; + +public enum NonConventionalWeekDays { + Mon$Day, Tues$DAY_, Wednes$day, THURS$day_, Fri$Day$_$, Satur$DAY_, Sun$Day +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/nonconventionalweek/NonConventionalWeekDaysHolder.java b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/nonconventionalweek/NonConventionalWeekDaysHolder.java new file mode 100644 index 0000000000..9cd2cf4369 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/nonconventionalweek/NonConventionalWeekDaysHolder.java @@ -0,0 +1,85 @@ +package com.baeldung.caseinsensitiveenum.nonconventionalweek; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class NonConventionalWeekDaysHolder { + + @Value("${monday}") + private NonConventionalWeekDays monday; + + @Value("${tuesday}") + private NonConventionalWeekDays tuesday; + + @Value("${wednesday}") + private NonConventionalWeekDays wednesday; + + @Value("${thursday}") + private NonConventionalWeekDays thursday; + + @Value("${friday}") + private NonConventionalWeekDays friday; + + @Value("${saturday}") + private NonConventionalWeekDays saturday; + + @Value("${sunday}") + private NonConventionalWeekDays sunday; + + public NonConventionalWeekDays getMonday() { + return monday; + } + + public void setMonday(final NonConventionalWeekDays monday) { + this.monday = monday; + } + + public NonConventionalWeekDays getTuesday() { + return tuesday; + } + + public void setTuesday(final NonConventionalWeekDays tuesday) { + this.tuesday = tuesday; + } + + public NonConventionalWeekDays getWednesday() { + return wednesday; + } + + public void setWednesday(final NonConventionalWeekDays wednesday) { + this.wednesday = wednesday; + } + + public NonConventionalWeekDays getThursday() { + return thursday; + } + + public void setThursday(final NonConventionalWeekDays thursday) { + this.thursday = thursday; + } + + public NonConventionalWeekDays getFriday() { + return friday; + } + + public void setFriday(final NonConventionalWeekDays friday) { + this.friday = friday; + } + + public NonConventionalWeekDays getSaturday() { + return saturday; + } + + public void setSaturday(final NonConventionalWeekDays saturday) { + this.saturday = saturday; + } + + public NonConventionalWeekDays getSunday() { + return sunday; + } + + public void setSunday(final NonConventionalWeekDays sunday) { + this.sunday = sunday; + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/week/SpELWeekDaysHolder.java b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/week/SpELWeekDaysHolder.java new file mode 100644 index 0000000000..6c56c0a9fe --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/week/SpELWeekDaysHolder.java @@ -0,0 +1,85 @@ +package com.baeldung.caseinsensitiveenum.week; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class SpELWeekDaysHolder { + + @Value("#{'${monday}'.toUpperCase()}") + private WeekDays monday; + + @Value("#{'${tuesday}'.toUpperCase()}") + private WeekDays tuesday; + + @Value("#{'${wednesday}'.toUpperCase()}") + private WeekDays wednesday; + + @Value("#{'${thursday}'.toUpperCase()}") + private WeekDays thursday; + + @Value("#{'${friday}'.toUpperCase()}") + private WeekDays friday; + + @Value("#{'${saturday}'.toUpperCase()}") + private WeekDays saturday; + + @Value("#{'${sunday}'.toUpperCase()}") + private WeekDays sunday; + + public WeekDays getMonday() { + return monday; + } + + public void setMonday(final WeekDays monday) { + this.monday = monday; + } + + public WeekDays getTuesday() { + return tuesday; + } + + public void setTuesday(final WeekDays tuesday) { + this.tuesday = tuesday; + } + + public WeekDays getWednesday() { + return wednesday; + } + + public void setWednesday(final WeekDays wednesday) { + this.wednesday = wednesday; + } + + public WeekDays getThursday() { + return thursday; + } + + public void setThursday(final WeekDays thursday) { + this.thursday = thursday; + } + + public WeekDays getFriday() { + return friday; + } + + public void setFriday(final WeekDays friday) { + this.friday = friday; + } + + public WeekDays getSaturday() { + return saturday; + } + + public void setSaturday(final WeekDays saturday) { + this.saturday = saturday; + } + + public WeekDays getSunday() { + return sunday; + } + + public void setSunday(final WeekDays sunday) { + this.sunday = sunday; + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/week/WeekDays.java b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/week/WeekDays.java new file mode 100644 index 0000000000..21e7b6662a --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/week/WeekDays.java @@ -0,0 +1,5 @@ +package com.baeldung.caseinsensitiveenum.week; + +public enum WeekDays { + MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/week/WeekDaysHolder.java b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/week/WeekDaysHolder.java new file mode 100644 index 0000000000..299a61a3fd --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/main/java/com/baeldung/caseinsensitiveenum/week/WeekDaysHolder.java @@ -0,0 +1,85 @@ +package com.baeldung.caseinsensitiveenum.week; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Component +public class WeekDaysHolder { + + @Value("${monday}") + private WeekDays monday; + + @Value("${tuesday}") + private WeekDays tuesday; + + @Value("${wednesday}") + private WeekDays wednesday; + + @Value("${thursday}") + private WeekDays thursday; + + @Value("${friday}") + private WeekDays friday; + + @Value("${saturday}") + private WeekDays saturday; + + @Value("${sunday}") + private WeekDays sunday; + + public WeekDays getMonday() { + return monday; + } + + public void setMonday(final WeekDays monday) { + this.monday = monday; + } + + public WeekDays getTuesday() { + return tuesday; + } + + public void setTuesday(final WeekDays tuesday) { + this.tuesday = tuesday; + } + + public WeekDays getWednesday() { + return wednesday; + } + + public void setWednesday(final WeekDays wednesday) { + this.wednesday = wednesday; + } + + public WeekDays getThursday() { + return thursday; + } + + public void setThursday(final WeekDays thursday) { + this.thursday = thursday; + } + + public WeekDays getFriday() { + return friday; + } + + public void setFriday(final WeekDays friday) { + this.friday = friday; + } + + public WeekDays getSaturday() { + return saturday; + } + + public void setSaturday(final WeekDays saturday) { + this.saturday = saturday; + } + + public WeekDays getSunday() { + return sunday; + } + + public void setSunday(final WeekDays sunday) { + this.sunday = sunday; + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/CaseInsensitiveStringToEnumConverterUnitTest.java b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/CaseInsensitiveStringToEnumConverterUnitTest.java new file mode 100644 index 0000000000..7470b3d9dd --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/CaseInsensitiveStringToEnumConverterUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.caseinsensitiveenum; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.caseinsensitiveenum.CaseInsensitiveStringToEnumConverterUnitTest.WeekDayConverterConfiguration; +import com.baeldung.caseinsensitiveenum.converter.CaseInsensitiveWeekDayConverter; +import com.baeldung.caseinsensitiveenum.providers.WeekDayHolderArgumentsProvider; +import com.baeldung.caseinsensitiveenum.week.WeekDays; +import com.baeldung.caseinsensitiveenum.week.WeekDaysHolder; +import java.util.function.Function; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Bean; +import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.support.DefaultConversionService; + +@SpringBootTest(properties = { + "monday=monday", + "tuesday=tuesday", + "wednesday=wednesday", + "thursday=THURSDAY", + "friday=Friday", + "saturday=saturDAY", + "sunday=sUndAy", +}, classes = {WeekDaysHolder.class, WeekDayConverterConfiguration.class}) +class CaseInsensitiveStringToEnumConverterUnitTest { + + public static class WeekDayConverterConfiguration { + @Bean + public ConversionService conversionService() { + final DefaultConversionService defaultConversionService = new DefaultConversionService(); + defaultConversionService.addConverter(new CaseInsensitiveWeekDayConverter()); + return defaultConversionService; + } + } + + @Autowired + private WeekDaysHolder holder; + + @ParameterizedTest + @ArgumentsSource(WeekDayHolderArgumentsProvider.class) + void givenPropertiesWhenInjectEnumThenValueIsNull( + Function methodReference, WeekDays expected) { + WeekDays actual = methodReference.apply(holder); + assertThat(actual).isEqualTo(expected); + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/LenientStringToEnumConverterUnitTest.java b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/LenientStringToEnumConverterUnitTest.java new file mode 100644 index 0000000000..3f739b10cf --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/LenientStringToEnumConverterUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.caseinsensitiveenum; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.caseinsensitiveenum.providers.WeekDayHolderArgumentsProvider; +import com.baeldung.caseinsensitiveenum.week.WeekDays; +import com.baeldung.caseinsensitiveenum.week.WeekDaysHolder; +import java.util.function.Function; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest(properties = { + "monday=Mon-Day!", + "tuesday=TuesDAY#", + "wednesday=Wednes@day", + "thursday=THURSday^", + "friday=Fri:Day_%", + "saturday=Satur_DAY*", + "sunday=Sun+Day", +}, classes = WeekDaysHolder.class) +class LenientStringToEnumConverterUnitTest { + + @Autowired + private WeekDaysHolder holder; + + @ParameterizedTest + @ArgumentsSource(WeekDayHolderArgumentsProvider.class) + void givenPropertiesWhenInjectEnumThenValueIsPresent( + Function methodReference, WeekDays expected) { + WeekDays actual = methodReference.apply(holder); + assertThat(actual).isEqualTo(expected); + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/NonConventionalStringToEnumLenientConverterUnitTest.java b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/NonConventionalStringToEnumLenientConverterUnitTest.java new file mode 100644 index 0000000000..21c2e35799 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/NonConventionalStringToEnumLenientConverterUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.caseinsensitiveenum; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.caseinsensitiveenum.nonconventionalweek.NonConventionalWeekDays; +import com.baeldung.caseinsensitiveenum.nonconventionalweek.NonConventionalWeekDaysHolder; +import com.baeldung.caseinsensitiveenum.providers.NonConventionalWeekDayHolderArgumentsProvider; +import java.util.function.Function; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest(properties = { + "monday=Mon-Day!", + "tuesday=TuesDAY#", + "wednesday=Wednes@day", + "thursday=THURSday^", + "friday=Fri:Day_%", + "saturday=Satur_DAY*", + "sunday=Sun+Day", +}, classes = NonConventionalWeekDaysHolder.class) +class NonConventionalStringToEnumLenientConverterUnitTest { + + @Autowired + private NonConventionalWeekDaysHolder holder; + + @ParameterizedTest + @ArgumentsSource(NonConventionalWeekDayHolderArgumentsProvider.class) + void givenPropertiesWhenInjectEnumThenValueIsPresent( + Function methodReference, NonConventionalWeekDays expected) { + NonConventionalWeekDays actual = methodReference.apply(holder); + assertThat(actual).isEqualTo(expected); + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/SpELCaseInsensitiveStringToEnumConverterUnitTest.java b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/SpELCaseInsensitiveStringToEnumConverterUnitTest.java new file mode 100644 index 0000000000..7d259c6de4 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/SpELCaseInsensitiveStringToEnumConverterUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.caseinsensitiveenum; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.caseinsensitiveenum.CaseInsensitiveStringToEnumConverterUnitTest.WeekDayConverterConfiguration; +import com.baeldung.caseinsensitiveenum.converter.StrictNullableWeekDayConverter; +import com.baeldung.caseinsensitiveenum.providers.SpELWeekDayHolderArgumentsProvider; +import com.baeldung.caseinsensitiveenum.week.SpELWeekDaysHolder; +import com.baeldung.caseinsensitiveenum.week.WeekDays; +import java.util.function.Function; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Bean; +import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.support.DefaultConversionService; + +@SpringBootTest(properties = { + "monday=monday", + "tuesday=tuesday", + "wednesday=wednesday", + "thursday=THURSDAY", + "friday=Friday", + "saturday=saturDAY", + "sunday=sUndAy", +}, classes = {SpELWeekDaysHolder.class, WeekDayConverterConfiguration.class}) +class SpELCaseInsensitiveStringToEnumConverterUnitTest { + + public static class WeekDayConverterConfiguration { + @Bean + public ConversionService conversionService() { + final DefaultConversionService defaultConversionService = new DefaultConversionService(); + defaultConversionService.addConverter(new StrictNullableWeekDayConverter()); + return defaultConversionService; + } + } + + @Autowired + private SpELWeekDaysHolder holder; + + @ParameterizedTest + @ArgumentsSource(SpELWeekDayHolderArgumentsProvider.class) + void givenPropertiesWhenInjectEnumThenValueIsNull( + Function methodReference, WeekDays expected) { + WeekDays actual = methodReference.apply(holder); + assertThat(actual).isEqualTo(expected); + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/StrictStringToEnumConverterNegativeUnitTest.java b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/StrictStringToEnumConverterNegativeUnitTest.java new file mode 100644 index 0000000000..ffa3ee14be --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/StrictStringToEnumConverterNegativeUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.caseinsensitiveenum; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.caseinsensitiveenum.StrictStringToEnumConverterNegativeUnitTest.WeekDayConverterConfiguration; +import com.baeldung.caseinsensitiveenum.converter.StrictNullableWeekDayConverter; +import com.baeldung.caseinsensitiveenum.providers.WeekDayHolderArgumentsProvider; +import com.baeldung.caseinsensitiveenum.week.WeekDays; +import com.baeldung.caseinsensitiveenum.week.WeekDaysHolder; +import java.util.function.Function; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Bean; +import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.support.DefaultConversionService; + +@SpringBootTest(properties = { + "monday=monday", + "tuesday=tuesday", + "wednesday=wednesday", + "thursday=thursday", + "friday=friday", + "saturday=saturday", + "sunday=sunday", +}, classes = {WeekDaysHolder.class, WeekDayConverterConfiguration.class}) +class StrictStringToEnumConverterNegativeUnitTest { + + public static class WeekDayConverterConfiguration { + @Bean + public ConversionService conversionService() { + final DefaultConversionService defaultConversionService = new DefaultConversionService(); + defaultConversionService.addConverter(new StrictNullableWeekDayConverter()); + return defaultConversionService; + } + } + + @Autowired + private WeekDaysHolder holder; + + @ParameterizedTest + @ArgumentsSource(WeekDayHolderArgumentsProvider.class) + void givenPropertiesWhenInjectEnumThenValueIsNull( + Function methodReference, WeekDays ignored) { + WeekDays actual = methodReference.apply(holder); + assertThat(actual).isNull(); + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/StrictStringToEnumConverterPositiveUnitTest.java b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/StrictStringToEnumConverterPositiveUnitTest.java new file mode 100644 index 0000000000..2d057a4f4d --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/StrictStringToEnumConverterPositiveUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.caseinsensitiveenum; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.caseinsensitiveenum.StrictStringToEnumConverterNegativeUnitTest.WeekDayConverterConfiguration; +import com.baeldung.caseinsensitiveenum.converter.StrictNullableWeekDayConverter; +import com.baeldung.caseinsensitiveenum.providers.WeekDayHolderArgumentsProvider; +import com.baeldung.caseinsensitiveenum.week.WeekDays; +import com.baeldung.caseinsensitiveenum.week.WeekDaysHolder; +import java.util.function.Function; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ArgumentsSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Bean; +import org.springframework.core.convert.ConversionService; +import org.springframework.core.convert.support.DefaultConversionService; + +@SpringBootTest(properties = { + "monday=MONDAY", + "tuesday=TUESDAY", + "wednesday=WEDNESDAY", + "thursday=THURSDAY", + "friday=FRIDAY", + "saturday=SATURDAY", + "sunday=SUNDAY", +}, classes = {WeekDaysHolder.class, WeekDayConverterConfiguration.class}) +class StrictStringToEnumConverterPositiveUnitTest { + + public static class WeekDayConverterConfiguration { + @Bean + public ConversionService conversionService() { + final DefaultConversionService defaultConversionService = new DefaultConversionService(); + defaultConversionService.addConverter(new StrictNullableWeekDayConverter()); + return defaultConversionService; + } + } + + @Autowired + private WeekDaysHolder holder; + + @ParameterizedTest + @ArgumentsSource(WeekDayHolderArgumentsProvider.class) + void givenPropertiesWhenInjectEnumThenValueIsNull( + Function methodReference, WeekDays expected) { + WeekDays actual = methodReference.apply(holder); + assertThat(actual).isEqualTo(expected); + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/providers/NonConventionalWeekDayHolderArgumentsProvider.java b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/providers/NonConventionalWeekDayHolderArgumentsProvider.java new file mode 100644 index 0000000000..b4ed8f8388 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/providers/NonConventionalWeekDayHolderArgumentsProvider.java @@ -0,0 +1,35 @@ +package com.baeldung.caseinsensitiveenum.providers; + + + +import static com.baeldung.caseinsensitiveenum.nonconventionalweek.NonConventionalWeekDays.Fri$Day$_$; +import static com.baeldung.caseinsensitiveenum.nonconventionalweek.NonConventionalWeekDays.Mon$Day; +import static com.baeldung.caseinsensitiveenum.nonconventionalweek.NonConventionalWeekDays.Satur$DAY_; +import static com.baeldung.caseinsensitiveenum.nonconventionalweek.NonConventionalWeekDays.Sun$Day; +import static com.baeldung.caseinsensitiveenum.nonconventionalweek.NonConventionalWeekDays.THURS$day_; +import static com.baeldung.caseinsensitiveenum.nonconventionalweek.NonConventionalWeekDays.Tues$DAY_; +import static com.baeldung.caseinsensitiveenum.nonconventionalweek.NonConventionalWeekDays.Wednes$day; + +import com.baeldung.caseinsensitiveenum.nonconventionalweek.NonConventionalWeekDays; +import com.baeldung.caseinsensitiveenum.nonconventionalweek.NonConventionalWeekDaysHolder; +import java.util.function.Function; +import java.util.stream.Stream; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; + +public class NonConventionalWeekDayHolderArgumentsProvider implements ArgumentsProvider { + + @Override + public Stream provideArguments(final ExtensionContext extensionContext) { + return Stream.of( + Arguments.of(((Function) NonConventionalWeekDaysHolder::getMonday),Mon$Day), + Arguments.of(((Function) NonConventionalWeekDaysHolder::getTuesday),Tues$DAY_), + Arguments.of(((Function) NonConventionalWeekDaysHolder::getWednesday),Wednes$day), + Arguments.of(((Function) NonConventionalWeekDaysHolder::getThursday),THURS$day_), + Arguments.of(((Function) NonConventionalWeekDaysHolder::getFriday),Fri$Day$_$), + Arguments.of(((Function) NonConventionalWeekDaysHolder::getSaturday),Satur$DAY_), + Arguments.of(((Function) NonConventionalWeekDaysHolder::getSunday),Sun$Day) + ); + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/providers/SpELWeekDayHolderArgumentsProvider.java b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/providers/SpELWeekDayHolderArgumentsProvider.java new file mode 100644 index 0000000000..d6e91be0a1 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/providers/SpELWeekDayHolderArgumentsProvider.java @@ -0,0 +1,34 @@ +package com.baeldung.caseinsensitiveenum.providers; + + +import static com.baeldung.caseinsensitiveenum.week.WeekDays.FRIDAY; +import static com.baeldung.caseinsensitiveenum.week.WeekDays.MONDAY; +import static com.baeldung.caseinsensitiveenum.week.WeekDays.SATURDAY; +import static com.baeldung.caseinsensitiveenum.week.WeekDays.SUNDAY; +import static com.baeldung.caseinsensitiveenum.week.WeekDays.THURSDAY; +import static com.baeldung.caseinsensitiveenum.week.WeekDays.TUESDAY; +import static com.baeldung.caseinsensitiveenum.week.WeekDays.WEDNESDAY; + +import com.baeldung.caseinsensitiveenum.week.WeekDays; +import com.baeldung.caseinsensitiveenum.week.SpELWeekDaysHolder; +import java.util.function.Function; +import java.util.stream.Stream; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; + +public class SpELWeekDayHolderArgumentsProvider implements ArgumentsProvider { + + @Override + public Stream provideArguments(final ExtensionContext extensionContext) { + return Stream.of( + Arguments.of(((Function) SpELWeekDaysHolder::getMonday), MONDAY), + Arguments.of(((Function) SpELWeekDaysHolder::getTuesday), TUESDAY), + Arguments.of(((Function) SpELWeekDaysHolder::getWednesday), WEDNESDAY), + Arguments.of(((Function) SpELWeekDaysHolder::getThursday), THURSDAY), + Arguments.of(((Function) SpELWeekDaysHolder::getFriday), FRIDAY), + Arguments.of(((Function) SpELWeekDaysHolder::getSaturday), SATURDAY), + Arguments.of(((Function) SpELWeekDaysHolder::getSunday), SUNDAY) + ); + } +} diff --git a/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/providers/WeekDayHolderArgumentsProvider.java b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/providers/WeekDayHolderArgumentsProvider.java new file mode 100644 index 0000000000..6c0ebd2a20 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties-4/src/test/java/com/baeldung/caseinsensitiveenum/providers/WeekDayHolderArgumentsProvider.java @@ -0,0 +1,34 @@ +package com.baeldung.caseinsensitiveenum.providers; + + +import static com.baeldung.caseinsensitiveenum.week.WeekDays.FRIDAY; +import static com.baeldung.caseinsensitiveenum.week.WeekDays.MONDAY; +import static com.baeldung.caseinsensitiveenum.week.WeekDays.SATURDAY; +import static com.baeldung.caseinsensitiveenum.week.WeekDays.SUNDAY; +import static com.baeldung.caseinsensitiveenum.week.WeekDays.THURSDAY; +import static com.baeldung.caseinsensitiveenum.week.WeekDays.TUESDAY; +import static com.baeldung.caseinsensitiveenum.week.WeekDays.WEDNESDAY; + +import com.baeldung.caseinsensitiveenum.week.WeekDays; +import com.baeldung.caseinsensitiveenum.week.WeekDaysHolder; +import java.util.function.Function; +import java.util.stream.Stream; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; + +public class WeekDayHolderArgumentsProvider implements ArgumentsProvider { + + @Override + public Stream provideArguments(final ExtensionContext extensionContext) { + return Stream.of( + Arguments.of(((Function) WeekDaysHolder::getMonday), MONDAY), + Arguments.of(((Function) WeekDaysHolder::getTuesday), TUESDAY), + Arguments.of(((Function) WeekDaysHolder::getWednesday), WEDNESDAY), + Arguments.of(((Function) WeekDaysHolder::getThursday), THURSDAY), + Arguments.of(((Function) WeekDaysHolder::getFriday), FRIDAY), + Arguments.of(((Function) WeekDaysHolder::getSaturday), SATURDAY), + Arguments.of(((Function) WeekDaysHolder::getSunday), SUNDAY) + ); + } +} diff --git a/spring-boot-modules/spring-boot-runtime-2/README.md b/spring-boot-modules/spring-boot-runtime-2/README.md index 3ee05ccc83..c22f7cbc18 100644 --- a/spring-boot-modules/spring-boot-runtime-2/README.md +++ b/spring-boot-modules/spring-boot-runtime-2/README.md @@ -5,3 +5,6 @@ This module contains articles about administering a Spring Boot runtime ### Relevant Articles: - [Configure the Heap Size When Starting a Spring Boot Application](https://www.baeldung.com/spring-boot-heap-size) - [Max-HTTP-Header-Size in Spring Boot 2](https://www.baeldung.com/spring-boot-max-http-header-size) + - [Programmatically Restarting a Spring Boot Application](https://www.baeldung.com/java-restart-spring-boot-app) + + - More articles: [[<-- prev]](../spring-boot-runtime) diff --git a/spring-boot-modules/spring-boot-runtime-2/pom.xml b/spring-boot-modules/spring-boot-runtime-2/pom.xml index 5174900c79..356880975a 100644 --- a/spring-boot-modules/spring-boot-runtime-2/pom.xml +++ b/spring-boot-modules/spring-boot-runtime-2/pom.xml @@ -28,6 +28,15 @@ org.springframework.security spring-security-test + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.cloud + spring-cloud-starter + ${springcloud.version} + @@ -64,4 +73,7 @@ + + 3.1.3 + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/Application.java b/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/restart/Application.java similarity index 100% rename from spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/Application.java rename to spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/restart/Application.java diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/RestartController.java b/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/restart/RestartController.java similarity index 100% rename from spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/RestartController.java rename to spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/restart/RestartController.java diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/RestartService.java b/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/restart/RestartService.java similarity index 100% rename from spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/RestartService.java rename to spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/restart/RestartService.java index 9883ec653b..f197efb067 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/restart/RestartService.java +++ b/spring-boot-modules/spring-boot-runtime-2/src/main/java/com/baeldung/restart/RestartService.java @@ -1,8 +1,8 @@ package com.baeldung.restart; -import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.context.restart.RestartEndpoint; +import org.springframework.stereotype.Service; @Service public class RestartService { diff --git a/spring-boot-modules/spring-boot-runtime-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-runtime-2/src/main/resources/application.properties new file mode 100644 index 0000000000..f6bd08e5dd --- /dev/null +++ b/spring-boot-modules/spring-boot-runtime-2/src/main/resources/application.properties @@ -0,0 +1,7 @@ +management.endpoints.web.exposure.include=* +management.metrics.enable.root=true +management.metrics.enable.jvm=true +management.endpoint.restart.enabled=true +spring.datasource.jmx-enabled=false +spring.jmx.enabled=true +management.endpoint.shutdown.enabled=true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime/src/test/java/com/baeldung/restart/RestartApplicationManualTest.java b/spring-boot-modules/spring-boot-runtime-2/src/test/java/com/baeldung/restart/RestartApplicationManualTest.java similarity index 100% rename from spring-boot-modules/spring-boot-runtime/src/test/java/com/baeldung/restart/RestartApplicationManualTest.java rename to spring-boot-modules/spring-boot-runtime-2/src/test/java/com/baeldung/restart/RestartApplicationManualTest.java diff --git a/spring-boot-modules/spring-boot-runtime/README.md b/spring-boot-modules/spring-boot-runtime/README.md index 6463aaa6c3..44b217ae77 100644 --- a/spring-boot-modules/spring-boot-runtime/README.md +++ b/spring-boot-modules/spring-boot-runtime/README.md @@ -4,10 +4,11 @@ This module contains articles about administering a Spring Boot runtime ### Relevant Articles: - [Shutdown a Spring Boot Application](https://www.baeldung.com/spring-boot-shutdown) - - [Programmatically Restarting a Spring Boot Application](https://www.baeldung.com/java-restart-spring-boot-app) - [Logging HTTP Requests with Spring Boot Actuator HTTP Tracing](https://www.baeldung.com/spring-boot-actuator-http) - [Spring Boot Embedded Tomcat Logs](https://www.baeldung.com/spring-boot-embedded-tomcat-logs) - [Project Configuration with Spring](https://www.baeldung.com/project-configuration-with-spring) - [Spring – Log Incoming Requests](https://www.baeldung.com/spring-http-logging) - [How to Configure Spring Boot Tomcat](https://www.baeldung.com/spring-boot-configure-tomcat) - [CORS with Spring](https://www.baeldung.com/spring-cors) + + - More articles: [[more -->]](../spring-boot-runtime-2) diff --git a/spring-boot-modules/spring-caching-2/pom.xml b/spring-boot-modules/spring-caching-2/pom.xml index ee28ac5ed5..4675b5162e 100644 --- a/spring-boot-modules/spring-caching-2/pom.xml +++ b/spring-boot-modules/spring-caching-2/pom.xml @@ -35,6 +35,7 @@ org.projectlombok lombok + ${lombok.version} org.springframework.boot diff --git a/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-demo/pom.xml b/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-demo/pom.xml index f8552aba93..60b68fc4bd 100644 --- a/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-demo/pom.xml +++ b/spring-cloud-modules/spring-cloud-netflix-sidecar/spring-cloud-netflix-sidecar-demo/pom.xml @@ -26,6 +26,7 @@ io.projectreactor reactor-core + ${reactor-core.version} org.springframework.boot @@ -53,4 +54,7 @@ + + 3.6.0 + \ No newline at end of file diff --git a/spring-di-2/pom.xml b/spring-di-2/pom.xml index 898dd182f1..6b4ecc6039 100644 --- a/spring-di-2/pom.xml +++ b/spring-di-2/pom.xml @@ -9,46 +9,21 @@ com.baeldung - parent-spring-6 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-spring-6 + ../parent-boot-3 - - - - org.apache.logging.log4j - log4j-bom - ${log4j2.version} - import - pom - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - org.springframework.boot spring-boot-starter-web + ${spring-boot.version} org.springframework.boot spring-boot-starter-data-jpa - - - org.springframework - spring-aspects - - - org.springframework.boot - spring-boot-starter-test + ${spring-boot.version} @@ -79,7 +54,6 @@ - 3.1.2 1.13.1 2.17.1 diff --git a/spring-di-3/pom.xml b/spring-di-3/pom.xml index ba1a18ae8c..818ecc509c 100644 --- a/spring-di-3/pom.xml +++ b/spring-di-3/pom.xml @@ -9,44 +9,20 @@ com.baeldung - parent-spring-6 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-spring-6 + ../parent-boot-3 - - - - org.apache.logging.log4j - log4j-bom - ${log4j2.version} - import - pom - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - - - org.springframework.boot - spring-boot-starter-web - org.springframework.boot spring-boot-starter-test + ${spring-boot.version} - 3.1.2 - 2.17.1 2.0.9 1.4.11 diff --git a/spring-di-3/src/main/java/com/baeldung/autowiring/App.java b/spring-di-3/src/main/java/com/baeldung/autowiring/App.java index d2d0db7a60..873b152da1 100644 --- a/spring-di-3/src/main/java/com/baeldung/autowiring/App.java +++ b/spring-di-3/src/main/java/com/baeldung/autowiring/App.java @@ -2,7 +2,6 @@ package com.baeldung.autowiring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.ComponentScan; @SpringBootApplication public class App { diff --git a/spring-di/pom.xml b/spring-di/pom.xml index d073f5359d..a1be835af7 100644 --- a/spring-di/pom.xml +++ b/spring-di/pom.xml @@ -10,44 +10,12 @@ com.baeldung - parent-spring-6 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-spring-6 + ../parent-boot-3 - - - - org.springframework - spring-framework-bom - ${spring.version} - pom - import - - - org.springframework - spring-core - ${spring.version} - - - - - - org.springframework - spring-test - ${spring.version} - - - org.springframework - spring-beans - ${spring.version} - - - org.springframework - spring-context - ${spring.version} - com.google.guava guava @@ -63,12 +31,6 @@ spring-boot-starter ${spring-boot.version} - - org.springframework.boot - spring-boot-test - ${spring-boot.version} - test - commons-io commons-io @@ -79,17 +41,6 @@ aspectjweaver ${aspectjweaver.version} - - - - - - - - - - - @@ -132,8 +83,6 @@ org.baeldung.org.baeldung.sample.App - - 3.1.2 1.9.20.1 diff --git a/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/KafkaConsumerConfig.java b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/KafkaConsumerConfig.java new file mode 100644 index 0000000000..557fa11ed3 --- /dev/null +++ b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/KafkaConsumerConfig.java @@ -0,0 +1,36 @@ +package com.baeldung.spring.kafka.dlt; + +import java.util.HashMap; +import java.util.Map; + +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.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.support.serializer.JsonDeserializer; + +@Configuration +public class KafkaConsumerConfig { + + @Value(value = "${spring.kafka.bootstrap-servers}") + private String bootstrapServers; + + @Bean + public ConsumerFactory consumerFactory() { + Map config = new HashMap<>(); + config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + + return new DefaultKafkaConsumerFactory<>(config, new StringDeserializer(), new JsonDeserializer<>(Payment.class)); + } + + @Bean + public ConcurrentKafkaListenerContainerFactory containerFactory() { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory()); + return factory; + } +} \ No newline at end of file diff --git a/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/KafkaDltApplication.java b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/KafkaDltApplication.java new file mode 100644 index 0000000000..7aa2e3cdb8 --- /dev/null +++ b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/KafkaDltApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.kafka.dlt; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.kafka.annotation.EnableKafka; + +@EnableKafka +@SpringBootApplication +public class KafkaDltApplication { + public static void main(String[] args) { + SpringApplication.run(KafkaDltApplication.class, args); + } +} diff --git a/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/KafkaRetryConfig.java b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/KafkaRetryConfig.java new file mode 100644 index 0000000000..35a2b31168 --- /dev/null +++ b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/KafkaRetryConfig.java @@ -0,0 +1,34 @@ +package com.baeldung.spring.kafka.dlt; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.common.serialization.StringSerializer; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; +import org.springframework.kafka.support.serializer.JsonSerializer; + +@Configuration +public class KafkaRetryConfig { + + @Value(value = "${spring.kafka.bootstrap-servers}") + private String bootstrapServers; + + @Bean + public ProducerFactory producerFactory() { + Map config = new HashMap<>(); + config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + + return new DefaultKafkaProducerFactory<>(config, new StringSerializer(), new JsonSerializer<>()); + } + + @Bean + public KafkaTemplate retryableTopicKafkaTemplate() { + return new KafkaTemplate<>(producerFactory()); + } +} \ No newline at end of file diff --git a/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/Payment.java b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/Payment.java new file mode 100644 index 0000000000..1554c1671b --- /dev/null +++ b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/Payment.java @@ -0,0 +1,43 @@ +package com.baeldung.spring.kafka.dlt; + +import java.math.BigDecimal; +import java.util.Currency; +import java.util.StringJoiner; + +public class Payment { + private String reference; + private BigDecimal amount; + private Currency currency; + + public String getReference() { + return reference; + } + + public void setReference(String reference) { + this.reference = reference; + } + + public BigDecimal getAmount() { + return amount; + } + + public void setAmount(BigDecimal amount) { + this.amount = amount; + } + + public Currency getCurrency() { + return currency; + } + + public void setCurrency(Currency currency) { + this.currency = currency; + } + + @Override + public String toString() { + return new StringJoiner(", ", Payment.class.getSimpleName() + "[", "]").add("reference='" + reference + "'") + .add("amount=" + amount) + .add("currency=" + currency) + .toString(); + } +} \ No newline at end of file diff --git a/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/listener/PaymentListenerDltFailOnError.java b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/listener/PaymentListenerDltFailOnError.java new file mode 100644 index 0000000000..c407310074 --- /dev/null +++ b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/listener/PaymentListenerDltFailOnError.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.kafka.dlt.listener; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.kafka.annotation.DltHandler; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.annotation.RetryableTopic; +import org.springframework.kafka.retrytopic.DltStrategy; +import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.messaging.handler.annotation.Header; +import org.springframework.stereotype.Service; + +import com.baeldung.spring.kafka.dlt.Payment; + +@Service +public class PaymentListenerDltFailOnError { + private final Logger log = LoggerFactory.getLogger(PaymentListenerDltFailOnError.class); + + @RetryableTopic(attempts = "1", kafkaTemplate = "retryableTopicKafkaTemplate", dltStrategy = DltStrategy.FAIL_ON_ERROR) + @KafkaListener(topics = { "payments-fail-on-error-dlt" }, groupId = "payments") + public void handlePayment(Payment payment, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) { + log.info("Event on main topic={}, payload={}", topic, payment); + } + + @DltHandler + public void handleDltPayment(Payment payment, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) { + log.info("Event on dlt topic={}, payload={}", topic, payment); + } +} \ No newline at end of file diff --git a/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/listener/PaymentListenerDltRetryOnError.java b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/listener/PaymentListenerDltRetryOnError.java new file mode 100644 index 0000000000..9c6666c938 --- /dev/null +++ b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/listener/PaymentListenerDltRetryOnError.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.kafka.dlt.listener; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.kafka.annotation.DltHandler; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.annotation.RetryableTopic; +import org.springframework.kafka.retrytopic.DltStrategy; +import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.messaging.handler.annotation.Header; +import org.springframework.stereotype.Service; + +import com.baeldung.spring.kafka.dlt.Payment; + +@Service +public class PaymentListenerDltRetryOnError { + private final Logger log = LoggerFactory.getLogger(PaymentListenerDltRetryOnError.class); + + @RetryableTopic(attempts = "1", kafkaTemplate = "retryableTopicKafkaTemplate", dltStrategy = DltStrategy.ALWAYS_RETRY_ON_ERROR) + @KafkaListener(topics = { "payments-retry-on-error-dlt" }, groupId = "payments") + public void handlePayment(Payment payment, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) { + log.info("Event on main topic={}, payload={}", topic, payment); + } + + @DltHandler + public void handleDltPayment(Payment payment, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) { + log.info("Event on dlt topic={}, payload={}", topic, payment); + } +} \ No newline at end of file diff --git a/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/listener/PaymentListenerNoDlt.java b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/listener/PaymentListenerNoDlt.java new file mode 100644 index 0000000000..a12d423b30 --- /dev/null +++ b/spring-kafka-2/src/main/java/com/baeldung/spring/kafka/dlt/listener/PaymentListenerNoDlt.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.kafka.dlt.listener; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.kafka.annotation.DltHandler; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.kafka.annotation.RetryableTopic; +import org.springframework.kafka.retrytopic.DltStrategy; +import org.springframework.kafka.support.KafkaHeaders; +import org.springframework.messaging.handler.annotation.Header; +import org.springframework.stereotype.Service; + +import com.baeldung.spring.kafka.dlt.Payment; + +@Service +public class PaymentListenerNoDlt { + private final Logger log = LoggerFactory.getLogger(PaymentListenerNoDlt.class); + + @RetryableTopic(attempts = "1", kafkaTemplate = "retryableTopicKafkaTemplate", dltStrategy = DltStrategy.NO_DLT) + @KafkaListener(topics = { "payments-no-dlt" }, groupId = "payments") + public void handlePayment(Payment payment, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) { + log.info("Event on main topic={}, payload={}", topic, payment); + } + + @DltHandler + public void handleDltPayment(Payment payment, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) { + log.info("Event on dlt topic={}, payload={}", topic, payment); + } +} \ No newline at end of file diff --git a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/dlt/KafkaDltFailOnErrorIntegrationTest.java b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/dlt/KafkaDltFailOnErrorIntegrationTest.java new file mode 100644 index 0000000000..b20ee2ea12 --- /dev/null +++ b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/dlt/KafkaDltFailOnErrorIntegrationTest.java @@ -0,0 +1,87 @@ +package com.baeldung.spring.kafka.dlt; + +import static com.baeldung.spring.kafka.dlt.PaymentTestUtils.createPayment; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +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.boot.test.mock.mockito.SpyBean; +import org.springframework.kafka.config.KafkaListenerEndpointRegistry; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.listener.MessageListenerContainer; +import org.springframework.kafka.test.context.EmbeddedKafka; +import org.springframework.kafka.test.utils.ContainerTestUtils; + +import com.baeldung.spring.kafka.dlt.listener.PaymentListenerDltFailOnError; + +@SpringBootTest(classes = KafkaDltApplication.class) +@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9099", "port=9099" }) +public class KafkaDltFailOnErrorIntegrationTest { + private static final String TOPIC = "payments-fail-on-error-dlt"; + + @Autowired + private KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry; + + @Autowired + private KafkaTemplate kafkaProducer; + + @SpyBean + private PaymentListenerDltFailOnError paymentsConsumer; + + @BeforeEach + void setUp() { + // wait for embedded Kafka + for (MessageListenerContainer messageListenerContainer : kafkaListenerEndpointRegistry.getListenerContainers()) { + ContainerTestUtils.waitForAssignment(messageListenerContainer, 1); + } + } + + @Test + public void whenMainConsumerSucceeds_thenNoDltMessage() throws Exception { + CountDownLatch mainTopicCountDownLatch = new CountDownLatch(1); + + doAnswer(invocation -> { + mainTopicCountDownLatch.countDown(); + return null; + }).when(paymentsConsumer) + .handlePayment(any(), any()); + + kafkaProducer.send(TOPIC, createPayment("dlt-fail-main")); + + assertThat(mainTopicCountDownLatch.await(5, TimeUnit.SECONDS)).isTrue(); + verify(paymentsConsumer, never()).handleDltPayment(any(), any()); + } + + @Test + public void whenDltConsumerFails_thenDltProcessingStops() throws Exception { + CountDownLatch mainTopicCountDownLatch = new CountDownLatch(1); + CountDownLatch dlTTopicCountDownLatch = new CountDownLatch(2); + + doAnswer(invocation -> { + mainTopicCountDownLatch.countDown(); + throw new Exception("Simulating error in main consumer"); + }).when(paymentsConsumer) + .handlePayment(any(), any()); + + doAnswer(invocation -> { + dlTTopicCountDownLatch.countDown(); + throw new Exception("Simulating error in dlt consumer"); + }).when(paymentsConsumer) + .handleDltPayment(any(), any()); + + kafkaProducer.send(TOPIC, createPayment("dlt-fail")); + + assertThat(mainTopicCountDownLatch.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(dlTTopicCountDownLatch.await(5, TimeUnit.SECONDS)).isFalse(); + assertThat(dlTTopicCountDownLatch.getCount()).isEqualTo(1); + } +} \ No newline at end of file diff --git a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/dlt/KafkaDltRetryOnErrorIntegrationTest.java b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/dlt/KafkaDltRetryOnErrorIntegrationTest.java new file mode 100644 index 0000000000..393eb2ae46 --- /dev/null +++ b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/dlt/KafkaDltRetryOnErrorIntegrationTest.java @@ -0,0 +1,88 @@ +package com.baeldung.spring.kafka.dlt; + +import static com.baeldung.spring.kafka.dlt.PaymentTestUtils.createPayment; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +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.boot.test.mock.mockito.SpyBean; +import org.springframework.kafka.config.KafkaListenerEndpointRegistry; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.listener.MessageListenerContainer; +import org.springframework.kafka.test.context.EmbeddedKafka; +import org.springframework.kafka.test.utils.ContainerTestUtils; + +import com.baeldung.spring.kafka.dlt.listener.PaymentListenerDltRetryOnError; + +@SpringBootTest(classes = KafkaDltApplication.class) +@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9099", "port=9099" }) +public class KafkaDltRetryOnErrorIntegrationTest { + private static final String TOPIC = "payments-retry-on-error-dlt"; + + @Autowired + private KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry; + + @Autowired + private KafkaTemplate kafkaProducer; + + @SpyBean + private PaymentListenerDltRetryOnError paymentsConsumer; + + @BeforeEach + void setUp() { + // wait for embedded Kafka + for (MessageListenerContainer messageListenerContainer : kafkaListenerEndpointRegistry.getListenerContainers()) { + ContainerTestUtils.waitForAssignment(messageListenerContainer, 1); + } + } + + @Test + public void whenMainConsumerSucceeds_thenNoDltMessage() throws Exception { + CountDownLatch mainTopicCountDownLatch = new CountDownLatch(1); + + doAnswer(invocation -> { + mainTopicCountDownLatch.countDown(); + return null; + }).when(paymentsConsumer) + .handlePayment(any(), any()); + + kafkaProducer.send(TOPIC, createPayment("dlt-retry-main")); + + assertThat(mainTopicCountDownLatch.await(5, TimeUnit.SECONDS)).isTrue(); + verify(paymentsConsumer, never()).handleDltPayment(any(), any()); + } + + @Test + public void whenDltConsumerFails_thenDltConsumerRetriesMessage() throws Exception { + CountDownLatch mainTopicCountDownLatch = new CountDownLatch(1); + CountDownLatch dlTTopicCountDownLatch = new CountDownLatch(3); + + doAnswer(invocation -> { + mainTopicCountDownLatch.countDown(); + throw new Exception("Simulating error in main consumer"); + }).when(paymentsConsumer) + .handlePayment(any(), any()); + + doAnswer(invocation -> { + dlTTopicCountDownLatch.countDown(); + throw new Exception("Simulating error in dlt consumer"); + }).when(paymentsConsumer) + .handleDltPayment(any(), any()); + + kafkaProducer.send(TOPIC, createPayment("dlt-retry")); + + assertThat(mainTopicCountDownLatch.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(dlTTopicCountDownLatch.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(dlTTopicCountDownLatch.getCount()).isEqualTo(0); + } +} \ No newline at end of file diff --git a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/dlt/KafkaNoDltIntegrationTest.java b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/dlt/KafkaNoDltIntegrationTest.java new file mode 100644 index 0000000000..81cca9fec3 --- /dev/null +++ b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/dlt/KafkaNoDltIntegrationTest.java @@ -0,0 +1,87 @@ +package com.baeldung.spring.kafka.dlt; + +import static com.baeldung.spring.kafka.dlt.PaymentTestUtils.createPayment; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +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.boot.test.mock.mockito.SpyBean; +import org.springframework.kafka.config.KafkaListenerEndpointRegistry; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.listener.MessageListenerContainer; +import org.springframework.kafka.test.context.EmbeddedKafka; +import org.springframework.kafka.test.utils.ContainerTestUtils; + +import com.baeldung.spring.kafka.dlt.listener.PaymentListenerNoDlt; + +@SpringBootTest(classes = KafkaDltApplication.class) +@EmbeddedKafka(partitions = 1, brokerProperties = { "listeners=PLAINTEXT://localhost:9099", "port=9099" }) +public class KafkaNoDltIntegrationTest { + private static final String TOPIC = "payments-no-dlt"; + + @Autowired + private KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry; + + @Autowired + private KafkaTemplate kafkaProducer; + + @SpyBean + private PaymentListenerNoDlt paymentsConsumer; + + @BeforeEach + void setUp() { + // wait for embedded Kafka + for (MessageListenerContainer messageListenerContainer : kafkaListenerEndpointRegistry.getListenerContainers()) { + ContainerTestUtils.waitForAssignment(messageListenerContainer, 1); + } + } + + @Test + public void whenMainConsumerSucceeds_thenNoDltMessage() throws Exception { + CountDownLatch mainTopicCountDownLatch = new CountDownLatch(1); + + doAnswer(invocation -> { + mainTopicCountDownLatch.countDown(); + return null; + }).when(paymentsConsumer) + .handlePayment(any(), any()); + + kafkaProducer.send(TOPIC, createPayment("no-dlt-main")); + + assertThat(mainTopicCountDownLatch.await(5, TimeUnit.SECONDS)).isTrue(); + verify(paymentsConsumer, never()).handleDltPayment(any(), any()); + } + + @Test + public void whenMainConsumerFails_thenDltConsumerDoesNotReceiveMessage() throws Exception { + CountDownLatch mainTopicCountDownLatch = new CountDownLatch(1); + CountDownLatch dlTTopicCountDownLatch = new CountDownLatch(1); + + doAnswer(invocation -> { + mainTopicCountDownLatch.countDown(); + throw new Exception("Simulating error in main consumer"); + }).when(paymentsConsumer) + .handlePayment(any(), any()); + + doAnswer(invocation -> { + dlTTopicCountDownLatch.countDown(); + return null; + }).when(paymentsConsumer) + .handleDltPayment(any(), any()); + + kafkaProducer.send(TOPIC, createPayment("no-dlt")); + + assertThat(mainTopicCountDownLatch.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(dlTTopicCountDownLatch.await(5, TimeUnit.SECONDS)).isFalse(); + assertThat(dlTTopicCountDownLatch.getCount()).isEqualTo(1); + } +} \ No newline at end of file diff --git a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/dlt/PaymentTestUtils.java b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/dlt/PaymentTestUtils.java new file mode 100644 index 0000000000..7b8a574779 --- /dev/null +++ b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/dlt/PaymentTestUtils.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.kafka.dlt; + +import java.math.BigDecimal; +import java.util.Currency; + +class PaymentTestUtils { + + static Payment createPayment(String reference) { + Payment payment = new Payment(); + payment.setAmount(BigDecimal.valueOf(71)); + payment.setCurrency(Currency.getInstance("GBP")); + payment.setReference(reference); + return payment; + } +} \ No newline at end of file diff --git a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/managingkafkaconsumergroups/ManagingConsumerGroupsIntegrationTest.java b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/managingkafkaconsumergroups/ManagingConsumerGroupsIntegrationTest.java index 1620add9ca..ddbb105a67 100644 --- a/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/managingkafkaconsumergroups/ManagingConsumerGroupsIntegrationTest.java +++ b/spring-kafka-2/src/test/java/com/baeldung/spring/kafka/managingkafkaconsumergroups/ManagingConsumerGroupsIntegrationTest.java @@ -14,7 +14,7 @@ import java.util.Objects; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest(classes = ManagingConsumerGroupsApplicationKafkaApp.class) -@EmbeddedKafka(partitions = 2, brokerProperties = {"listeners=PLAINTEXT://localhost:9092", "port=9092"}) +@EmbeddedKafka(partitions = 2, brokerProperties = {"listeners=PLAINTEXT://localhost:9098", "port=9098"}) public class ManagingConsumerGroupsIntegrationTest { private static final String CONSUMER_1_IDENTIFIER = "org.springframework.kafka.KafkaListenerEndpointContainer#1"; diff --git a/spring-kafka-3/README.md b/spring-kafka-3/README.md new file mode 100644 index 0000000000..f9c0036ce3 --- /dev/null +++ b/spring-kafka-3/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Spring Kafka Trusted Packages Feature](https://www.baeldung.com/spring-kafka-trusted-packages-feature) diff --git a/spring-reactive-modules/pom.xml b/spring-reactive-modules/pom.xml index 61a3c3d17d..6ab85c88b4 100644 --- a/spring-reactive-modules/pom.xml +++ b/spring-reactive-modules/pom.xml @@ -30,6 +30,9 @@ spring-reactive-exceptions spring-reactor spring-webflux-amqp + + + @@ -59,7 +62,22 @@ pom import + + io.projectreactor + reactor-core + ${reactor.version} + + + io.projectreactor + reactor-test + ${reactor.version} + test + + + 3.6.0 + + \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-client-2/pom.xml b/spring-reactive-modules/spring-reactive-client-2/pom.xml index 5d5f3ebc2e..f7d82053bb 100644 --- a/spring-reactive-modules/spring-reactive-client-2/pom.xml +++ b/spring-reactive-modules/spring-reactive-client-2/pom.xml @@ -135,7 +135,6 @@ 1.0.1.RELEASE 1.1.6 - 3.2.10.RELEASE 1.7.1 diff --git a/spring-reactive-modules/spring-reactive-client/pom.xml b/spring-reactive-modules/spring-reactive-client/pom.xml index fe53584cc9..634fef1273 100644 --- a/spring-reactive-modules/spring-reactive-client/pom.xml +++ b/spring-reactive-modules/spring-reactive-client/pom.xml @@ -117,7 +117,6 @@ io.projectreactor reactor-test - ${reactor-test.version} test diff --git a/spring-reactive-modules/spring-reactive-client/src/test/java/com/baeldung/reactive/logging/WebClientLoggingIntegrationTest.java b/spring-reactive-modules/spring-reactive-client/src/test/java/com/baeldung/reactive/logging/WebClientLoggingIntegrationTest.java index e1eefe4d61..27dde13608 100644 --- a/spring-reactive-modules/spring-reactive-client/src/test/java/com/baeldung/reactive/logging/WebClientLoggingIntegrationTest.java +++ b/spring-reactive-modules/spring-reactive-client/src/test/java/com/baeldung/reactive/logging/WebClientLoggingIntegrationTest.java @@ -2,6 +2,7 @@ package com.baeldung.reactive.logging; import static com.baeldung.reactive.logging.jetty.RequestLogEnhancer.enhance; import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -136,9 +137,7 @@ public class WebClientLoggingIntegrationTest { public void givenDefaultHttpClientWithFilter_whenEndpointIsConsumed_thenRequestAndResponseLogged() { WebClient .builder() - .filters(exchangeFilterFunctions -> { - exchangeFilterFunctions.addAll(LogFilters.prepareFilters()); - }) + .filters(exchangeFilterFunctions -> exchangeFilterFunctions.addAll(LogFilters.prepareFilters())) .build() .post() .uri(sampleUrl) @@ -146,8 +145,6 @@ public class WebClientLoggingIntegrationTest { .exchange() .block(); - verify(mockAppender).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains(sampleUrl))); + verify(mockAppender, atLeast(1)).doAppend(argThat(argument -> (((LoggingEvent) argument).getFormattedMessage()).contains(sampleUrl))); } - - } diff --git a/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml index e0b21087fa..7dbee7d93d 100644 --- a/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml +++ b/spring-reactive-modules/spring-reactive-data-couchbase/pom.xml @@ -29,7 +29,6 @@ io.projectreactor reactor-core - ${reactor-core.version} org.springframework.boot @@ -136,10 +135,13 @@ 5.2.2.RELEASE 4.5.2 1.5.23 - 3.3.1.RELEASE 2.2.6.RELEASE 2.17.1 + + 11 + 11 + 11 \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-data/pom.xml b/spring-reactive-modules/spring-reactive-data/pom.xml index 576a1d9f86..d72072e419 100644 --- a/spring-reactive-modules/spring-reactive-data/pom.xml +++ b/spring-reactive-modules/spring-reactive-data/pom.xml @@ -13,9 +13,6 @@ 1.0.0-SNAPSHOT - - UTF-8 - @@ -63,7 +60,7 @@ javax.validation validation-api - 2.0.1.Final + ${validation-api.version} io.r2dbc @@ -71,4 +68,9 @@ + + UTF-8 + 2.0.1.Final + + \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-performance/.gitignore b/spring-reactive-modules/spring-reactive-performance/.gitignore new file mode 100644 index 0000000000..82eca336e3 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/.gitignore @@ -0,0 +1,25 @@ +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/build/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-performance/README.md b/spring-reactive-modules/spring-reactive-performance/README.md new file mode 100644 index 0000000000..ea62ebab56 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/README.md @@ -0,0 +1,6 @@ +## Spring Reactive Performance + +This module contains articles about reactive Spring Boot. + +## Relevant Articles +- [Reactor WebFlux vs Virtual Threads](https://www.baeldung.com/java-reactor-webflux-vs-virtual-threads) diff --git a/spring-reactive-modules/spring-reactive-performance/pom.xml b/spring-reactive-modules/spring-reactive-performance/pom.xml new file mode 100644 index 0000000000..d7a69560dd --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/pom.xml @@ -0,0 +1,77 @@ + + + 4.0.0 + com.baeldung.spring + spring-reactive-performance + 1.0.0-SNAPSHOT + spring-reactive-performance + jar + Spring Reactive Performance + + + com.baeldung.spring.reactive + spring-reactive-modules + 1.0.0-SNAPSHOT + + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + 21 + 21 + + false + + + + org.apache.maven.plugins + maven-surefire-plugin + + --enable-preview + + + + + + + 21 + 3.2.0 + + \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/Application.java b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/Application.java new file mode 100644 index 0000000000..284ddfce30 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/Application.java @@ -0,0 +1,13 @@ +package com.baeldung.spring.reactive.performance; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/KafkaTemplate.java b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/KafkaTemplate.java new file mode 100644 index 0000000000..cf8684690e --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/KafkaTemplate.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.reactive.performance; + +import java.util.concurrent.CompletableFuture; + +public class KafkaTemplate { + + // For simplicity in this example and article, an actual Kafka client isn't utilized. + // The focus remains on demonstrating the basic principles without the complexities of a full Kafka client setup. + + public CompletableFuture send(String topic, K key, V value) { + System.out.println("Sending message to topic: " + topic + " with value: " + value); + return CompletableFuture.completedFuture(null); + } +} \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/ProductAddedToCartEvent.java b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/ProductAddedToCartEvent.java new file mode 100644 index 0000000000..08743d109c --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/ProductAddedToCartEvent.java @@ -0,0 +1,6 @@ +package com.baeldung.spring.reactive.performance; + +import java.math.BigDecimal; + +public record ProductAddedToCartEvent(String productId, BigDecimal price, String currency, String cartId) { +} \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/model/Price.java b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/model/Price.java new file mode 100644 index 0000000000..271ca26c96 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/model/Price.java @@ -0,0 +1,9 @@ +package com.baeldung.spring.reactive.performance.model; + +import java.math.BigDecimal; + +public record Price(BigDecimal value, String currency) { + public Price applyDiscount(BigDecimal discount) { + return new Price(value.subtract(discount), currency); + } +} \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/model/Product.java b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/model/Product.java new file mode 100644 index 0000000000..d4aa751089 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/model/Product.java @@ -0,0 +1,43 @@ +package com.baeldung.spring.reactive.performance.model; + +import java.math.BigDecimal; + +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document(collation = "products") +public record Product ( + @Id + String id, + String name, + BigDecimal basePriceValue, + String currency, + Category category +) { + + public Price basePrice() { + return new Price(basePriceValue, currency); + } + + public enum Category { + ELECTRONICS(false), + CLOTHING(true), + ACCESSORIES(false), + GARDENING(false), + SPORTS(true); + + private final boolean eligibleForPromotion; + + Category(boolean eligibleForPromotion) { + this.eligibleForPromotion = eligibleForPromotion; + } + + public boolean isEligibleForDiscount() { + return eligibleForPromotion; + } + + public boolean notEligibleForPromotion() { + return !eligibleForPromotion; + } + } +} \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/virtualthreads/DiscountService.java b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/virtualthreads/DiscountService.java new file mode 100644 index 0000000000..89554396b2 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/virtualthreads/DiscountService.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.reactive.performance.virtualthreads; + +import java.math.BigDecimal; + +class DiscountService { + + public BigDecimal discountForProduct(String productId) { + return BigDecimal.valueOf(10); + } + +} \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/virtualthreads/ProductRepository.java b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/virtualthreads/ProductRepository.java new file mode 100644 index 0000000000..f0ebff5cfd --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/virtualthreads/ProductRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.spring.reactive.performance.virtualthreads; + +import org.springframework.data.mongodb.repository.MongoRepository; + +import com.baeldung.spring.reactive.performance.model.Product; + +interface ProductRepository extends MongoRepository { +} \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/virtualthreads/ProductService.java b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/virtualthreads/ProductService.java new file mode 100644 index 0000000000..f174e4c6fe --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/virtualthreads/ProductService.java @@ -0,0 +1,45 @@ +package com.baeldung.spring.reactive.performance.virtualthreads; + +import java.math.BigDecimal; + +import com.baeldung.spring.reactive.performance.KafkaTemplate; +import com.baeldung.spring.reactive.performance.ProductAddedToCartEvent; +import com.baeldung.spring.reactive.performance.model.Price; +import com.baeldung.spring.reactive.performance.model.Product; + +class ProductService { + private final String PRODUCT_ADDED_TO_CART_TOPIC = "product-added-to-cart"; + + private final ProductRepository repository; + private final DiscountService discountService; + private final KafkaTemplate kafkaTemplate; + + public ProductService(ProductRepository repository, DiscountService discountService) { + this.repository = repository; + this.discountService = discountService; + this.kafkaTemplate = new KafkaTemplate<>(); + } + + public void addProductToCart(String productId, String cartId) { + Thread.startVirtualThread(() -> computePriceAndPublishMessage(productId, cartId)); + } + + private void computePriceAndPublishMessage(String productId, String cartId) { + Product product = repository.findById(productId) + .orElseThrow(() -> new IllegalArgumentException("not found!")); + + Price price = computePrice(productId, product); + + var event = new ProductAddedToCartEvent(productId, price.value(), price.currency(), cartId); + kafkaTemplate.send(PRODUCT_ADDED_TO_CART_TOPIC, cartId, event); + } + + private Price computePrice(String productId, Product product) { + if (product.category().isEligibleForDiscount()) { + BigDecimal discount = discountService.discountForProduct(productId); + return product.basePrice().applyDiscount(discount); + } + return product.basePrice(); + } + +} \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/webflux/DiscountService.java b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/webflux/DiscountService.java new file mode 100644 index 0000000000..ebe6b9a8a4 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/webflux/DiscountService.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.reactive.performance.webflux; + +import java.math.BigDecimal; + +import reactor.core.publisher.Mono; + +class DiscountService { + public Mono discountForProduct(String productId) { + return Mono.just(BigDecimal.valueOf(10)); + } +} \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/webflux/ProductRepository.java b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/webflux/ProductRepository.java new file mode 100644 index 0000000000..5ab4497a27 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/webflux/ProductRepository.java @@ -0,0 +1,8 @@ +package com.baeldung.spring.reactive.performance.webflux; + +import org.springframework.data.mongodb.repository.ReactiveMongoRepository; + +import com.baeldung.spring.reactive.performance.model.Product; + +interface ProductRepository extends ReactiveMongoRepository { +} \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/webflux/ProductService.java b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/webflux/ProductService.java new file mode 100644 index 0000000000..90519ec627 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/src/main/java/com/baeldung/spring/reactive/performance/webflux/ProductService.java @@ -0,0 +1,39 @@ +package com.baeldung.spring.reactive.performance.webflux; + +import com.baeldung.spring.reactive.performance.KafkaTemplate; +import com.baeldung.spring.reactive.performance.ProductAddedToCartEvent; +import com.baeldung.spring.reactive.performance.model.Price; +import com.baeldung.spring.reactive.performance.model.Product; + +import reactor.core.publisher.Mono; + +class ProductService { + private final String PRODUCT_ADDED_TO_CART_TOPIC = "product-added-to-cart"; + + private final ProductRepository repository; + private final DiscountService discountService; + private final KafkaTemplate kafkaTemplate; + + public ProductService(ProductRepository repository, DiscountService discountService) { + this.repository = repository; + this.discountService = discountService; + this.kafkaTemplate = new KafkaTemplate<>(); + } + + public void addProductToCart(String productId, String cartId) { + repository.findById(productId) + .switchIfEmpty(Mono.error(() -> new IllegalArgumentException("not found!"))) + .flatMap(this::computePrice) + .map(price -> new ProductAddedToCartEvent(productId, price.value(), price.currency(), cartId)) + .subscribe(event -> kafkaTemplate.send(PRODUCT_ADDED_TO_CART_TOPIC, cartId, event)); + } + + private Mono computePrice(Product product) { + if (product.category().isEligibleForDiscount()) { + return discountService.discountForProduct(product.id()) + .map(product.basePrice()::applyDiscount); + } + return Mono.just(product.basePrice()); + } + +} \ No newline at end of file diff --git a/lagom/weather-api/src/main/resources/logback.xml b/spring-reactive-modules/spring-reactive-performance/src/main/resources/logback.xml similarity index 100% rename from lagom/weather-api/src/main/resources/logback.xml rename to spring-reactive-modules/spring-reactive-performance/src/main/resources/logback.xml diff --git a/spring-reactive-modules/spring-reactive-performance/src/test/java/com/baeldung/spring/reactive/performance/ApplicationUnitTest.java b/spring-reactive-modules/spring-reactive-performance/src/test/java/com/baeldung/spring/reactive/performance/ApplicationUnitTest.java new file mode 100644 index 0000000000..df69e7eb72 --- /dev/null +++ b/spring-reactive-modules/spring-reactive-performance/src/test/java/com/baeldung/spring/reactive/performance/ApplicationUnitTest.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.reactive.performance; + +import org.junit.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +public class ApplicationUnitTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-reactive-modules/spring-reactive-security/pom.xml b/spring-reactive-modules/spring-reactive-security/pom.xml index 25b9f4c38f..d501a03c46 100644 --- a/spring-reactive-modules/spring-reactive-security/pom.xml +++ b/spring-reactive-modules/spring-reactive-security/pom.xml @@ -82,7 +82,7 @@ io.projectreactor reactor-test - ${project-reactor-test.version} + ${reactor-test.version} test @@ -115,7 +115,8 @@ 1.1.3 1.0 1.0 - 3.1.6.RELEASE + 3.1.6.RELEASE + 3.4.29 \ No newline at end of file diff --git a/spring-reactive-modules/spring-reactive/pom.xml b/spring-reactive-modules/spring-reactive/pom.xml index f19809e302..04bd32d632 100644 --- a/spring-reactive-modules/spring-reactive/pom.xml +++ b/spring-reactive-modules/spring-reactive/pom.xml @@ -104,7 +104,7 @@ - 3.4.16 + 3.6.0 1.3.10 2.2.21 diff --git a/spring-reactive-modules/spring-reactor/pom.xml b/spring-reactive-modules/spring-reactor/pom.xml index c2635765f0..54a97b92de 100644 --- a/spring-reactive-modules/spring-reactor/pom.xml +++ b/spring-reactive-modules/spring-reactor/pom.xml @@ -27,17 +27,18 @@ io.projectreactor reactor-bus - ${reactor.version} + ${reactor-bus.version} io.projectreactor reactor-core - ${reactor.version} + ${reactor-core.version} - 2.0.8.RELEASE + 2.0.8.RELEASE + 2.0.8.RELEASE \ No newline at end of file diff --git a/spring-remoting-modules/pom.xml b/spring-remoting-modules/pom.xml index 8a5990fd1d..e7de7c5740 100644 --- a/spring-remoting-modules/pom.xml +++ b/spring-remoting-modules/pom.xml @@ -42,7 +42,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} diff --git a/spring-security-modules/spring-security-web-boot-1/pom.xml b/spring-security-modules/spring-security-web-boot-1/pom.xml index e93b0b4f03..af9a02b7b2 100644 --- a/spring-security-modules/spring-security-web-boot-1/pom.xml +++ b/spring-security-modules/spring-security-web-boot-1/pom.xml @@ -11,8 +11,9 @@ com.baeldung - spring-security-modules + parent-boot-3 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -34,7 +35,7 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity5 + thymeleaf-extras-springsecurity6 org.springframework.boot @@ -81,11 +82,6 @@ org.springframework.security spring-security-core - - javax.servlet.jsp.jstl - jstl-api - ${jstl.version} - org.springframework.security spring-security-config @@ -100,6 +96,11 @@ ${ehcache-core.version} jar + + io.rest-assured + rest-assured + test + diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java index ab2cc71fec..8023ef7c78 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/AppConfig.java @@ -15,14 +15,14 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @SpringBootApplication @PropertySource({"classpath:persistence-h2.properties", "classpath:application-defaults.properties"}) @EnableJpaRepositories(basePackages = {"com.baeldung.relationships.repositories"}) @EnableWebMvc @Import(SpringSecurityConfig.class) -public class AppConfig extends WebMvcConfigurerAdapter { +public class AppConfig implements WebMvcConfigurer { @Autowired private Environment env; @@ -41,7 +41,7 @@ public class AppConfig extends WebMvcConfigurerAdapter { public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); - em.setPackagesToScan(new String[] { "com.baeldung.relationships.models" }); + em.setPackagesToScan("com.baeldung.relationships.models"); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java index bce0e21e7a..9b0e8f32b9 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/SpringSecurityConfig.java @@ -1,6 +1,6 @@ package com.baeldung.relationships; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; @@ -13,6 +13,7 @@ import org.springframework.security.config.annotation.authentication.builders.Au 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.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension; @@ -47,12 +48,10 @@ public class SpringSecurityConfig { @Bean public UserDetailsManager users(HttpSecurity http) throws Exception { - AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManagerBuilder.class) - .userDetailsService(userDetailsService) - .passwordEncoder(encoder()) - .and() - .authenticationProvider(authenticationProvider()) - .build(); + AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); + authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(encoder()); + authenticationManagerBuilder.authenticationProvider(authenticationProvider()); + AuthenticationManager authenticationManager = authenticationManagerBuilder.build(); JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource); jdbcUserDetailsManager.setAuthenticationManager(authenticationManager); @@ -61,22 +60,16 @@ public class SpringSecurityConfig { @Bean public WebSecurityCustomizer webSecurityCustomizer() { - return (web) -> web.ignoring() - .antMatchers("/resources/**"); + return web -> web.ignoring().requestMatchers("/resources/**"); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/login") - .permitAll() - .and() - .formLogin() - .permitAll() - .successHandler(successHandler) - .and() - .csrf() - .disable(); + http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> + authorizationManagerRequestMatcherRegistry.requestMatchers("/login").permitAll()) + .formLogin(httpSecurityFormLoginConfigurer -> + httpSecurityFormLoginConfigurer.permitAll().successHandler(successHandler)) + .csrf(AbstractHttpConfigurer::disable); return http.build(); } diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java index 34bf775c1c..56e0fac833 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/models/AppUser.java @@ -2,12 +2,12 @@ package com.baeldung.relationships.models; import java.util.Date; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +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") diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java index 2f593d5784..6c8921a941 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/models/Tweet.java @@ -3,14 +3,14 @@ package com.baeldung.relationships.models; import java.util.HashSet; import java.util.Set; -import javax.persistence.CollectionTable; -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; +import jakarta.persistence.CollectionTable; +import jakarta.persistence.ElementCollection; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; @Entity @Table(name = "Tweet") diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java index 685a1a8ab9..ebefe104b1 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/repositories/TweetRepository.java @@ -3,11 +3,12 @@ package com.baeldung.relationships.repositories; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.PagingAndSortingRepository; import com.baeldung.relationships.models.Tweet; -public interface TweetRepository extends PagingAndSortingRepository { +public interface TweetRepository extends PagingAndSortingRepository, CrudRepository { @Query("SELECT twt FROM Tweet twt JOIN twt.likes AS lk WHERE lk = ?#{ principal?.username } OR twt.owner = ?#{ principal?.username }") Page getMyTweetsAndTheOnesILiked(Pageable pageable); diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java index 3636a20c2d..f1375d4fd1 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/security/AuthenticationSuccessHandlerImpl.java @@ -2,8 +2,8 @@ package com.baeldung.relationships.security; import java.util.Date; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java index f8a0f00d90..6f46386939 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/relationships/security/CustomUserDetailsService.java @@ -1,6 +1,6 @@ package com.baeldung.relationships.security; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java index ea882f7ba9..60fe5eebf4 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/config/SecurityConfig.java @@ -2,8 +2,11 @@ package com.baeldung.roles.custom.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +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.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; @@ -14,14 +17,9 @@ public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.csrf() - .disable() - .authorizeRequests() - .anyRequest() - .authenticated() - .and() - .formLogin() - .permitAll(); + http.csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.anyRequest().authenticated()) + .formLogin(AbstractAuthenticationFilterConfigurer::permitAll); return http.build(); } diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java index 25bf51507a..b8836eb55a 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/SetupData.java @@ -3,7 +3,7 @@ package com.baeldung.roles.custom.persistence; import java.util.Arrays; import java.util.HashSet; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import com.baeldung.roles.custom.persistence.dao.OrganizationRepository; import com.baeldung.roles.custom.persistence.dao.PrivilegeRepository; diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java index eab7696b47..5bf4c7b76d 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Foo.java @@ -1,10 +1,10 @@ package com.baeldung.roles.custom.persistence.model; -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-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java index f9dc992b8c..532deab4dd 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Organization.java @@ -1,10 +1,10 @@ package com.baeldung.roles.custom.persistence.model; -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 Organization { diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java index 7757ec1bf6..259cae24a3 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/Privilege.java @@ -1,10 +1,10 @@ package com.baeldung.roles.custom.persistence.model; -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 Privilege { diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java index 45ae8c64ca..9a6198bf2d 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/custom/persistence/model/User.java @@ -2,17 +2,17 @@ package com.baeldung.roles.custom.persistence.model; import java.util.Set; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.ManyToOne; -import javax.persistence.Table; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; @Entity @Table(name = "user_table") @@ -28,7 +28,9 @@ public class User { private String password; @ManyToMany(fetch = FetchType.EAGER) - @JoinTable(name = "users_privileges", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id")) + @JoinTable(name = "users_privileges", joinColumns = + @JoinColumn(name = "user_id", referencedColumnName = "id"), + inverseJoinColumns = @JoinColumn(name = "privilege_id", referencedColumnName = "id")) private Set privileges; @ManyToOne(fetch = FetchType.EAGER) diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java index 6b6fa8c6a3..696dd9c1e5 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/ip/config/SecurityConfig.java @@ -6,10 +6,13 @@ 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.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer; +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; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.access.expression.WebExpressionAuthorizationManager; @Configuration @EnableWebSecurity @@ -32,19 +35,12 @@ public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/login") - .permitAll() - .antMatchers("/foos/**") - .access("isAuthenticated() and hasIpAddress('11.11.11.11')") - .anyRequest() - .authenticated() - .and() - .formLogin() - .permitAll() - .and() - .csrf() - .disable(); + http.authorizeHttpRequests( + authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/login").permitAll() + .requestMatchers("/foos/**") + .access(new WebExpressionAuthorizationManager("isAuthenticated() and hasIpAddress('11.11.11.11')")).anyRequest().authenticated()) + .formLogin(AbstractAuthenticationFilterConfigurer::permitAll) + .csrf(AbstractHttpConfigurer::disable); return http.build(); } } \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java index 6fa165433a..c010d1fa3d 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/ip/web/MainController.java @@ -2,8 +2,8 @@ package com.baeldung.roles.ip.web; import java.util.List; -import javax.servlet.Filter; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.Filter; +import jakarta.servlet.http.HttpServletRequest; import com.baeldung.roles.custom.persistence.model.Foo; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java index 0ee4707d1b..7d1dd47397 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/MyLogoutSuccessHandler.java @@ -2,9 +2,9 @@ package com.baeldung.roles.rolesauthorities; import java.io.IOException; -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.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java index d464b82d1c..682f1faad8 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/config/SecurityConfig.java @@ -10,6 +10,7 @@ import org.springframework.security.config.annotation.authentication.builders.Au 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.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @@ -42,33 +43,22 @@ public class SecurityConfig { @Bean public WebSecurityCustomizer webSecurityCustomizer() { - return (web) -> web.ignoring() - .antMatchers("/resources/**"); + return (web) -> web.ignoring().requestMatchers("/resources/**"); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.csrf() - .disable() - .authorizeRequests() - .antMatchers("/login*", "/logout*", "/protectedbynothing*", "/home*") - .permitAll() - .antMatchers("/protectedbyrole") - .hasRole("USER") - .antMatchers("/protectedbyauthority") - .hasAuthority("READ_PRIVILEGE") - .and() - .formLogin() - .loginPage("/login") - .failureUrl("/login?error=true") - .permitAll() - .and() - .logout() - .logoutSuccessHandler(myLogoutSuccessHandler) - .invalidateHttpSession(false) - .logoutSuccessUrl("/logout.html?logSucc=true") - .deleteCookies("JSESSIONID") - .permitAll(); + http.csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests( + authorizationManagerRequestMatcherRegistry -> + authorizationManagerRequestMatcherRegistry.requestMatchers("/login*", "/logout*", "/protectedbynothing*", "/home*").permitAll() + .requestMatchers("/protectedbyrole").hasRole("USER") + .requestMatchers("/protectedbyauthority").hasAuthority("READ_PRIVILEGE")) + .formLogin(httpSecurityFormLoginConfigurer -> + httpSecurityFormLoginConfigurer.loginPage("/login").failureUrl("/login?error=true").permitAll()) + .logout(httpSecurityLogoutConfigurer -> + httpSecurityLogoutConfigurer.logoutSuccessHandler(myLogoutSuccessHandler).invalidateHttpSession(false) + .logoutSuccessUrl("/logout.html?logSucc=true").deleteCookies("JSESSIONID").permitAll()); return http.build(); } diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java index 1e444faf2d..2b07d63031 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Privilege.java @@ -2,11 +2,11 @@ package com.baeldung.roles.rolesauthorities.model; import java.util.Collection; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; @Entity public class Privilege { diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java index 031c9f0828..fa581b5fa0 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/Role.java @@ -2,13 +2,13 @@ package com.baeldung.roles.rolesauthorities.model; import java.util.Collection; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; @Entity public class Role { diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java index cb90947ed6..6c31ac5f03 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/model/User.java @@ -2,17 +2,16 @@ package com.baeldung.roles.rolesauthorities.model; import java.util.Collection; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.Table; - +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.JoinTable; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; @Entity @Table(name = "user_account") diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java index 17770e5cd0..89f183e60f 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/rolesauthorities/persistence/UserService.java @@ -1,6 +1,6 @@ package com.baeldung.roles.rolesauthorities.persistence; -import javax.transaction.Transactional; +import jakarta.transaction.Transactional; import com.baeldung.roles.rolesauthorities.model.User; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java index 403d02ff9c..efd6cd514a 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/voter/MinuteBasedVoter.java @@ -1,33 +1,28 @@ package com.baeldung.roles.voter; import java.time.LocalDateTime; -import java.util.Collection; +import java.util.function.Supplier; -import org.springframework.security.access.AccessDecisionVoter; -import org.springframework.security.access.ConfigAttribute; +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.authorization.AuthorizationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.web.access.intercept.RequestAuthorizationContext; -public class MinuteBasedVoter implements AccessDecisionVoter { +public class MinuteBasedVoter implements AuthorizationManager { @Override - public boolean supports(ConfigAttribute attribute) { - return true; + public void verify(Supplier authentication, RequestAuthorizationContext object) { + AuthorizationManager.super.verify(authentication, object); } @Override - public boolean supports(Class clazz) { - return true; - } - - @Override - public int vote(Authentication authentication, Object object, Collection collection) { - return authentication.getAuthorities() + public AuthorizationDecision check(Supplier authentication, RequestAuthorizationContext object) { + return authentication.get().getAuthorities() .stream() .map(GrantedAuthority::getAuthority) .filter(r -> "ROLE_USER".equals(r) && LocalDateTime.now().getMinute() % 2 != 0) - .findAny() - .map(s -> ACCESS_DENIED) - .orElse(ACCESS_ABSTAIN); + .findAny().map(s -> new AuthorizationDecision(false)) + .orElse(new AuthorizationDecision(true)); } } diff --git a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java index 146853c18b..b6bad5fc77 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java +++ b/spring-security-modules/spring-security-web-boot-1/src/main/java/com/baeldung/roles/voter/WebSecurityConfig.java @@ -1,23 +1,19 @@ package com.baeldung.roles.voter; -import java.util.Arrays; -import java.util.List; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.access.AccessDecisionManager; -import org.springframework.security.access.AccessDecisionVoter; -import org.springframework.security.access.vote.AuthenticatedVoter; -import org.springframework.security.access.vote.RoleVoter; -import org.springframework.security.access.vote.UnanimousBased; +import org.springframework.security.authorization.AuthorizationManager; +import org.springframework.security.authorization.AuthorizationManagers; 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.AbstractAuthenticationFilterConfigurer; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.access.expression.WebExpressionVoter; +import org.springframework.security.web.access.intercept.RequestAuthorizationContext; @Configuration @EnableWebSecurity @@ -38,32 +34,20 @@ public class WebSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.csrf() - .disable() - .authorizeRequests() - .anyRequest() - .authenticated() - .accessDecisionManager(accessDecisionManager()) - .and() - .formLogin() - .permitAll() - .and() - .logout() - .permitAll() - .deleteCookies("JSESSIONID") - .logoutSuccessUrl("/login"); + http.csrf(AbstractHttpConfigurer::disable) + .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> + authorizationManagerRequestMatcherRegistry.anyRequest().authenticated() + .anyRequest().access(accessDecisionManager())) + .formLogin(AbstractAuthenticationFilterConfigurer::permitAll) + .logout(httpSecurityLogoutConfigurer -> + httpSecurityLogoutConfigurer.permitAll().deleteCookies("JSESSIONID") + .logoutSuccessUrl("/login")); return http.build(); } @Bean - public AccessDecisionManager accessDecisionManager() { - List> decisionVoters = Arrays.asList( - new WebExpressionVoter(), - new RoleVoter(), - new AuthenticatedVoter(), - new MinuteBasedVoter()); - - return new UnanimousBased(decisionVoters); + public AuthorizationManager accessDecisionManager() { + return AuthorizationManagers.allOf(new MinuteBasedVoter()); } @Bean diff --git a/spring-security-modules/spring-security-web-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java b/spring-security-modules/spring-security-web-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java index 10c32de5d7..5750b0daa9 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java +++ b/spring-security-modules/spring-security-web-boot-1/src/test/java/com/baeldung/relationships/SpringDataWithSecurityIntegrationTest.java @@ -11,9 +11,9 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; +import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; @@ -25,7 +25,7 @@ import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.jdbc.JdbcTestUtils; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import javax.servlet.ServletContext; +import jakarta.servlet.ServletContext; import java.util.Date; import java.util.List; @@ -83,7 +83,7 @@ public class SpringDataWithSecurityIntegrationTest { userRepository.updateLastLogin(new Date()); } - @Test(expected = InvalidDataAccessApiUsageException.class) + @Test(expected = SpelEvaluationException.class) public void givenNoAppUserInSecurityContext_whenUpdateLastLoginAttempted_shouldFail() { userRepository.updateLastLogin(new Date()); } @@ -104,7 +104,7 @@ public class SpringDataWithSecurityIntegrationTest { } while (page.hasNext()); } - @Test(expected = InvalidDataAccessApiUsageException.class) + @Test(expected = SpelEvaluationException.class) public void givenNoAppUser_whenPaginatedResultsRetrievalAttempted_shouldFail() { Page page = null; do { diff --git a/spring-security-modules/spring-security-web-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java b/spring-security-modules/spring-security-web-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java index 23ec605a36..085d5df551 100644 --- a/spring-security-modules/spring-security-web-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java +++ b/spring-security-modules/spring-security-web-boot-1/src/test/java/com/baeldung/roles/web/CustomUserDetailsServiceIntegrationTest.java @@ -6,13 +6,13 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import org.apache.http.HttpHeaders; import com.baeldung.roles.custom.Application; import com.baeldung.roles.custom.persistence.model.Foo; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithAnonymousUser; import org.springframework.security.test.context.support.WithUserDetails; diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml b/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml index 9a3b21af92..1b63860b92 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml +++ b/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml @@ -10,8 +10,9 @@ com.baeldung - spring-security-modules + parent-boot-3 0.0.1-SNAPSHOT + ../../parent-boot-3 @@ -92,8 +93,8 @@ - org.apache.httpcomponents - httpclient + org.apache.httpcomponents.client5 + httpclient5 commons-logging @@ -101,19 +102,6 @@ - - - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - provided - - - javax.servlet - jstl - ${jstl.version} - runtime - com.google.guava @@ -127,9 +115,9 @@ test - javax.xml.bind - jaxb-api - ${jaxb-api.version} + jakarta.xml.bind + jakarta.xml.bind-api + 4.0.1 @@ -230,6 +218,7 @@ 4.5.8 1.6.1 + com.baeldung.inmemory.InMemoryAuthApplication \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java index 07344819c0..01d0c83bb5 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -4,9 +4,8 @@ import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; import org.springframework.stereotype.Component; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java index 81f82a2c1c..c903fe12bb 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java @@ -2,13 +2,13 @@ package com.baeldung.client; import java.net.URI; -import org.apache.http.HttpHost; -import org.apache.http.client.AuthCache; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.auth.BasicScheme; -import org.apache.http.impl.client.BasicAuthCache; -import org.apache.http.protocol.BasicHttpContext; -import org.apache.http.protocol.HttpContext; +import org.apache.hc.client5.http.auth.AuthCache; +import org.apache.hc.client5.http.impl.auth.BasicAuthCache; +import org.apache.hc.client5.http.impl.auth.BasicScheme; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.core5.http.protocol.BasicHttpContext; +import org.apache.hc.core5.http.protocol.HttpContext; import org.springframework.http.HttpMethod; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/client/RestTemplateFactory.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/client/RestTemplateFactory.java index aac4f8cebd..425708abc8 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/client/RestTemplateFactory.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/client/RestTemplateFactory.java @@ -1,6 +1,6 @@ package com.baeldung.client; -import org.apache.http.HttpHost; +import org.apache.hc.core5.http.HttpHost; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.http.client.ClientHttpRequestFactory; @@ -35,7 +35,7 @@ public class RestTemplateFactory implements FactoryBean, Initializ @Override public void afterPropertiesSet() { - HttpHost host = new HttpHost("localhost", 8082, "http"); + HttpHost host = new HttpHost( "http", "localhost", 8082); final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host); restTemplate = new RestTemplate(requestFactory); restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("user1", "user1Pass")); diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/filter/CustomFilter.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/filter/CustomFilter.java index 6bb12610fa..a9509ddafa 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/filter/CustomFilter.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/filter/CustomFilter.java @@ -2,10 +2,10 @@ package com.baeldung.filter; import org.springframework.web.filter.GenericFilterBean; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import java.io.IOException; public class CustomFilter extends GenericFilterBean { diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java index 5714b2fb3e..ce50448605 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java @@ -30,14 +30,10 @@ public class CustomWebSecurityConfigurerAdapter { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/securityNone") - .permitAll() - .anyRequest() - .authenticated() - .and() - .httpBasic() - .authenticationEntryPoint(authenticationEntryPoint); + http.authorizeHttpRequests(expressionInterceptUrlRegistry -> + expressionInterceptUrlRegistry.requestMatchers("/securityNone").permitAll() + .anyRequest().authenticated()) + .httpBasic(httpSecurityHttpBasicConfigurer -> httpSecurityHttpBasicConfigurer.authenticationEntryPoint(authenticationEntryPoint)); http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); return http.build(); } diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java index 839fa15734..5af2a68ac3 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java @@ -2,6 +2,7 @@ package com.baeldung.inmemory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; @@ -25,13 +26,11 @@ public class InMemoryAuthWebSecurityConfigurer { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/private/**") - .authenticated() - .antMatchers("/public/**") - .permitAll() - .and() - .httpBasic(); + http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> + authorizationManagerRequestMatcherRegistry.requestMatchers("/private/**").authenticated() + .requestMatchers("/public/**").permitAll() + ) + .httpBasic(Customizer.withDefaults()); return http.build(); } diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryNoOpAuthWebSecurityConfigurer.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryNoOpAuthWebSecurityConfigurer.java index 72d3ef79d7..ba86d14aa5 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryNoOpAuthWebSecurityConfigurer.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryNoOpAuthWebSecurityConfigurer.java @@ -1,6 +1,7 @@ package com.baeldung.inmemory; import org.springframework.context.annotation.Bean; +import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; @@ -21,13 +22,9 @@ public class InMemoryNoOpAuthWebSecurityConfigurer { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/private/**") - .authenticated() - .antMatchers("/public/**") - .permitAll() - .and() - .httpBasic(); + http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/private/**").authenticated() + .requestMatchers("/public/**").permitAll()) + .httpBasic(Customizer.withDefaults()); return http.build(); } } diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/PasswordStorageWebSecurityConfigurer.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/PasswordStorageWebSecurityConfigurer.java index a1c6e1ee76..5892762ac9 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/PasswordStorageWebSecurityConfigurer.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/PasswordStorageWebSecurityConfigurer.java @@ -46,7 +46,7 @@ public class PasswordStorageWebSecurityConfigurer { PasswordEncoder defaultEncoder = new StandardPasswordEncoder(); Map encoders = new HashMap<>(); encoders.put("bcrypt", new BCryptPasswordEncoder()); - encoders.put("scrypt", new SCryptPasswordEncoder()); + encoders.put("scrypt", new SCryptPasswordEncoder(1, 1, 1, 1, 10)); encoders.put("noop", NoOpPasswordEncoder.getInstance()); DelegatingPasswordEncoder passwordEncoder = new DelegatingPasswordEncoder("bcrypt", encoders); diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java index 7dc53e3e1e..d53aa5bdfe 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java @@ -2,9 +2,9 @@ package com.baeldung.security; import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java index 1ae89adb89..cf7e9ee212 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java @@ -2,8 +2,8 @@ package com.baeldung.security; import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; @@ -16,8 +16,7 @@ import org.springframework.stereotype.Component; public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override - public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException { + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } - } \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/web/controller/BarController.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/web/controller/BarController.java index 6f7dc91e7e..0fd0bdac4f 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/web/controller/BarController.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/web/controller/BarController.java @@ -2,8 +2,9 @@ package com.baeldung.web.controller; import java.nio.charset.Charset; -import org.apache.commons.codec.binary.Base64; import com.baeldung.web.dto.Bar; + +import org.apache.hc.client5.http.utils.Base64; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.http.HttpHeaders; @@ -35,7 +36,7 @@ public class BarController { public HttpHeaders createHeaders(String username, String password){ return new HttpHeaders() {{ String auth = username + ":" + password; - byte[] encodedAuth = Base64.encodeBase64( + byte[] encodedAuth = Base64.encodeBase64( auth.getBytes(Charset.forName("US-ASCII")) ); String authHeader = "Basic " + new String( encodedAuth ); set( "Authorization", authHeader ); diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/web/dto/Bar.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/web/dto/Bar.java index eb139b0ec1..1bb7476669 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/web/dto/Bar.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/web/dto/Bar.java @@ -2,7 +2,7 @@ package com.baeldung.web.dto; import java.io.Serializable; -import javax.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Bar implements Serializable { diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/web/dto/Foo.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/web/dto/Foo.java index 23cfab132d..f904be0ad9 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/web/dto/Foo.java +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/web/dto/Foo.java @@ -2,7 +2,7 @@ package com.baeldung.web.dto; import java.io.Serializable; -import javax.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Foo implements Serializable { diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/resources/webSecurityConfig.xml b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/resources/webSecurityConfig.xml index 2ff9a1de15..d3d47579de 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/resources/webSecurityConfig.xml +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/resources/webSecurityConfig.xml @@ -11,6 +11,7 @@ + @@ -22,7 +23,7 @@ - + \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-sockets/pom.xml b/spring-security-modules/spring-security-web-sockets/pom.xml index 513ee28c85..5f11bc9580 100644 --- a/spring-security-modules/spring-security-web-sockets/pom.xml +++ b/spring-security-modules/spring-security-web-sockets/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-spring-5 + parent-spring-6 0.0.1-SNAPSHOT - ../../parent-spring-5 + ../../parent-spring-6 @@ -73,6 +73,16 @@ hibernate-core ${hibernate-core.version} + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + + + org.glassfish.expressly + expressly + ${expressly.version} + com.h2database h2 @@ -92,7 +102,7 @@ org.springframework.security spring-security-messaging - ${spring-security.version} + ${spring-security-messaging.version} @@ -107,24 +117,9 @@ - javax.servlet - javax.servlet-api - ${javax.servlet-api.version} - - - javax.servlet.jsp.jstl - jstl-api - ${jstl-api.version} - - - javax.servlet.jsp - javax.servlet.jsp-api - ${javax.servlet.jsp-api.version} - - - javax.servlet - jstl - ${jstl.version} + jakarta.platform + jakarta.jakartaee-api + ${jakartaee-api.version} @@ -144,17 +139,11 @@ - org.springframework.boot - spring-boot-starter-test - ${spring-boot-starter-test.version} + org.springframework + spring-test + ${spring.version} test - - - javax.xml.bind - jaxb-api - ${jaxb-api.version} - @@ -194,11 +183,15 @@ - 5.2.10.Final - 1.11.3.RELEASE - 1.5.10.RELEASE + 6.1.5 + 6.0.2 + 6.1.7.Final + 8.0.1.Final + 5.0.0 + 3.1.0 + 3.1.0 + 10.0.0 1.7.6 - 2.3.1 \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/AppConfig.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/AppConfig.java index afb1970b25..0329f91373 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/AppConfig.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/AppConfig.java @@ -9,7 +9,7 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 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.resource.PathResourceResolver; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.UrlBasedViewResolver; @@ -20,8 +20,9 @@ import java.sql.SQLException; @EnableJpaRepositories @ComponentScan("com.baeldung.springsecuredsockets") @Import({ SecurityConfig.class, DataStoreConfig.class, SocketBrokerConfig.class, SocketSecurityConfig.class }) -public class AppConfig extends WebMvcConfigurerAdapter { +public class AppConfig implements WebMvcConfigurer { + @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("index"); registry.addViewController("/login").setViewName("login"); diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/DataStoreConfig.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/DataStoreConfig.java index 2246c0055b..16ace5ed88 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/DataStoreConfig.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/DataStoreConfig.java @@ -13,7 +13,7 @@ import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; -import javax.persistence.EntityManagerFactory; +import jakarta.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.util.Properties; diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/SecurityConfig.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/SecurityConfig.java index 64f5169d2d..24687e6f21 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/SecurityConfig.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/SecurityConfig.java @@ -6,11 +6,14 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +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.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.config.annotation.web.configurers.HeadersConfigurer; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; @@ -86,43 +89,30 @@ public class SecurityConfig { */ @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/", "/index", "/authenticate") - .permitAll() - .antMatchers("/secured/**/**", "/secured/**/**/**", "/secured/socket", "/secured/success") - .authenticated() - .anyRequest() - .authenticated() - .and() - .formLogin() - .loginPage("/login") - .permitAll() - .usernameParameter("username") - .passwordParameter("password") - .loginProcessingUrl("/authenticate") - .successHandler(loginSuccessHandler()) - .failureUrl("/denied") - .permitAll() - .and() - .logout() - .logoutSuccessHandler(logoutSuccessHandler()) - .and() + http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> + authorizationManagerRequestMatcherRegistry + .requestMatchers("/", "/index", "/authenticate").permitAll() + .requestMatchers("/secured/**/**", "/secured/**/**/**", "/secured/socket", "/secured/success").authenticated() + .anyRequest().authenticated()) + .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login").permitAll() + .usernameParameter("username") + .passwordParameter("password") + .loginProcessingUrl("/authenticate") + .successHandler(loginSuccessHandler()) + .failureUrl("/denied").permitAll()) + .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutSuccessHandler(logoutSuccessHandler())) /** * Applies to User Roles - not to login failures or unauthenticated access attempts. */ - .exceptionHandling() - .accessDeniedHandler(accessDeniedHandler()) - .and() + .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.accessDeniedHandler(accessDeniedHandler())) .authenticationProvider(authenticationProvider()); /** Disabled for local testing */ - http.csrf() - .disable(); + http.csrf(AbstractHttpConfigurer::disable); /** This is solely required to support H2 console viewing in Spring MVC with Spring Security */ - http.headers() - .frameOptions() - .disable(); + http.headers(httpSecurityHeadersConfigurer -> httpSecurityHeadersConfigurer.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)) + .authorizeHttpRequests(Customizer.withDefaults()); return http.build(); } @@ -135,8 +125,7 @@ public class SecurityConfig { @Bean public WebSecurityCustomizer webSecurityCustomizer() { - return (web) -> web.ignoring() - .antMatchers("/resources/**"); + return (web) -> web.ignoring().requestMatchers("/resources/**"); } } diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/SocketBrokerConfig.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/SocketBrokerConfig.java index 9b19de7b5a..4e641980e5 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/SocketBrokerConfig.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/SocketBrokerConfig.java @@ -8,14 +8,14 @@ import static com.baeldung.springsecuredsockets.Constants.SECURED_CHAT_SPECIFIC_ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; -import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration @EnableWebSocketMessageBroker @ComponentScan("com.baeldung.springsecuredsockets.controllers") -public class SocketBrokerConfig extends AbstractWebSocketMessageBrokerConfigurer { +public class SocketBrokerConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/WebAppInitializer.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/WebAppInitializer.java index 84c045a75a..244d5dd93b 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/WebAppInitializer.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/config/WebAppInitializer.java @@ -4,9 +4,9 @@ import org.springframework.web.WebApplicationInitializer; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; +import jakarta.servlet.ServletContext; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRegistration; public class WebAppInitializer implements WebApplicationInitializer { diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/controllers/CsrfTokenController.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/controllers/CsrfTokenController.java index 3d10dad391..97fe6ff1ee 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/controllers/CsrfTokenController.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/controllers/CsrfTokenController.java @@ -5,7 +5,7 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; @Controller public class CsrfTokenController { diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/controllers/SocketController.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/controllers/SocketController.java index 6a74009c16..570d603fad 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/controllers/SocketController.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/controllers/SocketController.java @@ -30,8 +30,7 @@ public class SocketController { @MessageMapping(SECURED_CHAT) @SendTo(SECURED_CHAT_HISTORY) public OutputMessage sendAll(Message msg) throws Exception { - OutputMessage out = new OutputMessage(msg.getFrom(), msg.getText(), new SimpleDateFormat("HH:mm").format(new Date())); - return out; + return new OutputMessage(msg.getFrom(), msg.getText(), new SimpleDateFormat("HH:mm").format(new Date())); } /** diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/domain/Role.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/domain/Role.java index 09fee9a31b..1f3ba3b283 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/domain/Role.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/domain/Role.java @@ -1,6 +1,6 @@ package com.baeldung.springsecuredsockets.domain; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.Set; @Entity diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/domain/User.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/domain/User.java index 8f84b2246d..96daff8427 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/domain/User.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/domain/User.java @@ -1,12 +1,12 @@ package com.baeldung.springsecuredsockets.domain; -import javax.persistence.*; +import jakarta.persistence.*; import java.util.Set; //Custom User Model @Entity -@Table(name = "user") +@Table(name = "users") public class User { @Id diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomAccessDeniedHandler.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomAccessDeniedHandler.java index 0ab31a9c86..54d3f60232 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomAccessDeniedHandler.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomAccessDeniedHandler.java @@ -4,9 +4,9 @@ import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.web.access.AccessDeniedHandler; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; /** diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomLoginSuccessHandler.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomLoginSuccessHandler.java index 281fd0f163..c78aa20690 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomLoginSuccessHandler.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomLoginSuccessHandler.java @@ -7,8 +7,8 @@ import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; public class CustomLoginSuccessHandler implements AuthenticationSuccessHandler { diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomLogoutSuccessHandler.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomLogoutSuccessHandler.java index 620e75fb39..3f8e43f590 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomLogoutSuccessHandler.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomLogoutSuccessHandler.java @@ -5,15 +5,14 @@ import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; public class CustomLogoutSuccessHandler implements LogoutSuccessHandler { @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) - throws IOException, ServletException { + throws IOException { response.setStatus(HttpStatus.OK.value()); response.sendRedirect(request.getContextPath() + "/index"); diff --git a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomUserDetailsService.java b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomUserDetailsService.java index a0eb4d4bde..52f8fe315b 100644 --- a/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomUserDetailsService.java +++ b/spring-security-modules/spring-security-web-sockets/src/main/java/com/baeldung/springsecuredsockets/security/CustomUserDetailsService.java @@ -17,7 +17,7 @@ import org.springframework.stereotype.Service; import java.util.Collection; import java.util.HashSet; -@Service() +@Service public class CustomUserDetailsService implements UserDetailsService { Logger log = LoggerFactory.getLogger(CustomUserDetailsService.class); diff --git a/spring-security-modules/spring-security-web-x509/pom.xml b/spring-security-modules/spring-security-web-x509/pom.xml index ec0331fd53..6a4ca78484 100644 --- a/spring-security-modules/spring-security-web-x509/pom.xml +++ b/spring-security-modules/spring-security-web-x509/pom.xml @@ -10,8 +10,9 @@ com.baeldung - spring-security-modules + parent-boot-3 0.0.1-SNAPSHOT + ../../parent-boot-3 diff --git a/spring-soap/pom.xml b/spring-soap/pom.xml index c796b08e9a..d1dff51a3e 100644 --- a/spring-soap/pom.xml +++ b/spring-soap/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,10 +42,6 @@ jaxb-runtime - - javax.xml.bind - jaxb-api - @@ -77,9 +73,9 @@ - org.jvnet.jaxb2.maven2 - maven-jaxb2-plugin - ${maven-jaxb2-plugin.version} + org.jvnet.jaxb + jaxb-maven-plugin + ${jaxb-maven-plugin.version} @@ -103,7 +99,7 @@ 4.0.0 + 4.0.0 3.1.0 - 0.15.3 \ No newline at end of file diff --git a/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java b/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java index 183027cdb6..3688854f98 100644 --- a/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java +++ b/spring-soap/src/main/java/com/baeldung/springsoap/CountryRepository.java @@ -3,7 +3,7 @@ package com.baeldung.springsoap; import java.util.HashMap; import java.util.Map; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import org.springframework.stereotype.Component; import org.springframework.util.Assert; diff --git a/spring-web-modules/spring-mvc-basics-4/pom.xml b/spring-web-modules/spring-mvc-basics-4/pom.xml index 455e4e488c..7e8ef257c7 100644 --- a/spring-web-modules/spring-mvc-basics-4/pom.xml +++ b/spring-web-modules/spring-mvc-basics-4/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -31,6 +31,7 @@ javax.servlet jstl + 1.2 org.springframework.boot diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/config/WebConfig.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/config/WebConfig.java index e9b59a2b23..7ccbbd6410 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/config/WebConfig.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/config/WebConfig.java @@ -1,22 +1,12 @@ package com.baeldung.config; +import com.baeldung.contexts.Greeting; +import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.context.annotation.Bean; 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.view.InternalResourceViewResolver; -import org.springframework.web.servlet.view.JstlView; -import org.thymeleaf.spring5.SpringTemplateEngine; -import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; -import org.thymeleaf.spring5.view.ThymeleafViewResolver; -import org.thymeleaf.templatemode.TemplateMode; -import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; -import org.thymeleaf.templateresolver.ITemplateResolver; - -import com.baeldung.contexts.Greeting; -import com.fasterxml.jackson.databind.ObjectMapper; /** * Web Configuration for the entire app diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/services/GreeterService.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/services/GreeterService.java index f68b2fe5af..dfff103d7e 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/services/GreeterService.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/contexts/services/GreeterService.java @@ -1,7 +1,7 @@ package com.baeldung.contexts.services; -import javax.annotation.Resource; +import jakarta.annotation.Resource; import org.springframework.stereotype.Service; import com.baeldung.contexts.Greeting; diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java index b5adab5d86..d96607e1e9 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraint.java @@ -1,11 +1,11 @@ package com.baeldung.validation.listvalidation.constraint; +import jakarta.validation.Constraint; +import jakarta.validation.Payload; + import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; -import javax.validation.Constraint; -import javax.validation.Payload; - @Constraint(validatedBy = MaxSizeConstraintValidator.class) @Retention(RetentionPolicy.RUNTIME) public @interface MaxSizeConstraint { diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java index 409b6e1ab5..edf140c6b1 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/constraint/MaxSizeConstraintValidator.java @@ -2,10 +2,9 @@ package com.baeldung.validation.listvalidation.constraint; import java.util.List; -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorContext; - import com.baeldung.validation.listvalidation.model.Movie; +import jakarta.validation.ConstraintValidator; +import jakarta.validation.ConstraintValidatorContext; public class MaxSizeConstraintValidator implements ConstraintValidator> { diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java index 45639cf303..f29818a393 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/controller/MovieController.java @@ -1,10 +1,10 @@ package com.baeldung.validation.listvalidation.controller; -import java.util.List; - -import javax.validation.Valid; -import javax.validation.constraints.NotEmpty; - +import com.baeldung.validation.listvalidation.constraint.MaxSizeConstraint; +import com.baeldung.validation.listvalidation.model.Movie; +import com.baeldung.validation.listvalidation.service.MovieService; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotEmpty; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; @@ -12,9 +12,7 @@ import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import com.baeldung.validation.listvalidation.constraint.MaxSizeConstraint; -import com.baeldung.validation.listvalidation.model.Movie; -import com.baeldung.validation.listvalidation.service.MovieService; +import java.util.List; @Validated @RestController diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java index 742be27f61..38a9b558a9 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/exception/ConstraintViolationExceptionHandler.java @@ -1,10 +1,7 @@ package com.baeldung.validation.listvalidation.exception; -import java.util.Set; - -import javax.validation.ConstraintViolation; -import javax.validation.ConstraintViolationException; - +import jakarta.validation.ConstraintViolation; +import jakarta.validation.ConstraintViolationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -12,6 +9,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; +import java.util.Set; + @RestControllerAdvice public class ConstraintViolationExceptionHandler { diff --git a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java index f5a49877bf..5302ea4a5a 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java +++ b/spring-web-modules/spring-mvc-basics-4/src/main/java/com/baeldung/validation/listvalidation/model/Movie.java @@ -1,8 +1,9 @@ package com.baeldung.validation.listvalidation.model; +import jakarta.validation.constraints.NotEmpty; + import java.util.UUID; -import javax.validation.constraints.NotEmpty; public class Movie { diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java index 7fd8f0c97f..cb70f80afe 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerAnnotationIntegrationTest.java @@ -40,7 +40,7 @@ public class ControllerAnnotationIntegrationTest { @Test public void testTestController() throws Exception { - ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView(); + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test")).andReturn().getModelAndView(); // validate modal data Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man"); diff --git a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java index a7e6bd6c4b..3431d74997 100644 --- a/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java +++ b/spring-web-modules/spring-mvc-basics-4/src/test/java/com/baeldung/controller/ControllerIntegrationTest.java @@ -40,7 +40,7 @@ public class ControllerIntegrationTest { @Test public void testTestController() throws Exception { - ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test/")).andReturn().getModelAndView(); + ModelAndView mv = this.mockMvc.perform(MockMvcRequestBuilders.get("/test")).andReturn().getModelAndView(); // validate modal data Assert.assertSame(mv.getModelMap().get("data").toString(), "Welcome home man"); diff --git a/spring-web-modules/spring-mvc-java-2/README.md b/spring-web-modules/spring-mvc-java-2/README.md index 1f8231bada..61549b539a 100644 --- a/spring-web-modules/spring-mvc-java-2/README.md +++ b/spring-web-modules/spring-mvc-java-2/README.md @@ -5,3 +5,5 @@ - [A Quick Guide to Spring MVC Matrix Variables](https://www.baeldung.com/spring-mvc-matrix-variables) - [Converting a Spring MultipartFile to a File](https://www.baeldung.com/spring-multipartfile-to-file) - [Testing a Spring Multipart POST Request](https://www.baeldung.com/spring-multipart-post-request-test) +- [Introduction to HtmlUnit](https://www.baeldung.com/htmlunit) +- [Upload and Display Excel Files with Spring MVC](https://www.baeldung.com/spring-mvc-excel-files) diff --git a/spring-web-modules/spring-mvc-java-2/pom.xml b/spring-web-modules/spring-mvc-java-2/pom.xml index b1b5a797f8..a4484ed56d 100644 --- a/spring-web-modules/spring-mvc-java-2/pom.xml +++ b/spring-web-modules/spring-mvc-java-2/pom.xml @@ -46,6 +46,57 @@ commons-fileupload ${commons-fileupload.version} + + net.sourceforge.htmlunit + htmlunit + ${htmlunit.version} + + + commons-logging + commons-logging + + + commons-io + commons-io + + + + + + org.apache.poi + poi-ooxml + ${poi.version} + + + org.glassfish + javax.el + ${javax.el.version} + + + javax.servlet.jsp + javax.servlet.jsp-api + ${javax-servlet-api.version} + + + javax.servlet + jstl + + + org.apache.tomcat.embed + tomcat-embed-jasper + provided + + + + org.thymeleaf + thymeleaf-spring4 + ${thymeleaf.version} + + + org.thymeleaf + thymeleaf + ${thymeleaf.version} + @@ -63,6 +114,11 @@ 5.2.2.RELEASE 2.3.5 1.5 + 2.32 + 3.16-beta1 + 3.0.1-b09 + 2.3.3 + 3.0.9.RELEASE \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelController.java similarity index 97% rename from spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java rename to spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelController.java index f76f7441a5..5cb5de7124 100644 --- a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/web/controller/ExcelController.java +++ b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelController.java @@ -1,18 +1,19 @@ -package com.baeldung.web.controller; +package com.baeldung.excel; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import com.baeldung.excel.*; -import java.util.Map; -import java.util.List; -import javax.annotation.Resource; @Controller public class ExcelController { diff --git a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelPOIHelper.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java rename to spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelPOIHelper.java index 0519a8f3c7..7a213d523b 100644 --- a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/ExcelPOIHelper.java +++ b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/ExcelPOIHelper.java @@ -1,13 +1,14 @@ package com.baeldung.excel; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFFont; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.IntStream; + import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; @@ -15,16 +16,15 @@ import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Map; -import java.util.HashMap; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.IntStream; +import org.apache.poi.xssf.usermodel.XSSFCell; +import org.apache.poi.xssf.usermodel.XSSFCellStyle; +import org.apache.poi.xssf.usermodel.XSSFColor; +import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.xssf.usermodel.XSSFRow; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelPOIHelper { diff --git a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/MyCell.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/excel/MyCell.java rename to spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/MyCell.java diff --git a/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/WebConfig.java b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/WebConfig.java new file mode 100644 index 0000000000..f6a4d4dba3 --- /dev/null +++ b/spring-web-modules/spring-mvc-java-2/src/main/java/com/baeldung/excel/WebConfig.java @@ -0,0 +1,32 @@ +package com.baeldung.excel; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + + +@EnableWebMvc +@Configuration +@ComponentScan(basePackages = { "com.baeldung.excel" }) +public class WebConfig implements WebMvcConfigurer { + + @Override + public void addViewControllers(final ViewControllerRegistry registry) { + registry.addViewController("/").setViewName("index"); + } + + @Override + public void addResourceHandlers(final ResourceHandlerRegistry registry) { + registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); + } + + + @Bean + public ExcelPOIHelper excelPOIHelper() { + return new ExcelPOIHelper(); + } +} diff --git a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java rename to spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndJUnitLiveTest.java diff --git a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java rename to spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitAndSpringLiveTest.java diff --git a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java similarity index 100% rename from spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java rename to spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/HtmlUnitWebScrapingLiveTest.java diff --git a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/TestConfig.java similarity index 99% rename from spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java rename to spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/TestConfig.java index 75efd57ae4..6e55f01454 100644 --- a/spring-web-modules/spring-mvc-java/src/test/java/com/baeldung/htmlunit/TestConfig.java +++ b/spring-web-modules/spring-mvc-java-2/src/test/java/com/baeldung/htmlunit/TestConfig.java @@ -20,7 +20,7 @@ public class TestConfig implements WebMvcConfigurer { @Autowired private ServletContext ctx; - + @Bean public ViewResolver thymeleafViewResolver() { final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); @@ -44,4 +44,4 @@ public class TestConfig implements WebMvcConfigurer { templateEngine.setTemplateResolver(templateResolver()); return templateEngine; } -} +} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-java/README.md b/spring-web-modules/spring-mvc-java/README.md index 656e415f6a..d89f33fdc1 100644 --- a/spring-web-modules/spring-mvc-java/README.md +++ b/spring-web-modules/spring-mvc-java/README.md @@ -9,8 +9,6 @@ The "REST With Spring" Classes: https://bit.ly/restwithspring ### Relevant Articles: - [Integration Testing in Spring](https://www.baeldung.com/integration-testing-in-spring) - [File Upload with Spring MVC](https://www.baeldung.com/spring-file-upload) -- [Introduction to HtmlUnit](https://www.baeldung.com/htmlunit) -- [Upload and Display Excel Files with Spring MVC](https://www.baeldung.com/spring-mvc-excel-files) - [web.xml vs Initializer with Spring](https://www.baeldung.com/spring-xml-vs-java-config) - [A Java Web Application Without a web.xml](https://www.baeldung.com/java-web-app-without-web-xml) - [Accessing Spring MVC Model Objects in JavaScript](https://www.baeldung.com/spring-mvc-model-objects-js) diff --git a/spring-web-modules/spring-mvc-java/pom.xml b/spring-web-modules/spring-mvc-java/pom.xml index 395b12a278..d4c8f24431 100644 --- a/spring-web-modules/spring-mvc-java/pom.xml +++ b/spring-web-modules/spring-mvc-java/pom.xml @@ -44,21 +44,7 @@ provided - - net.sourceforge.htmlunit - htmlunit - ${htmlunit.version} - - - commons-logging - commons-logging - - - commons-io - commons-io - - - + commons-io commons-io @@ -91,12 +77,7 @@ spring-boot-starter-test test - - - org.apache.poi - poi-ooxml - ${poi.version} - + org.hibernate.validator @@ -221,19 +202,15 @@ 4.4.5 4.5.2 - 2.23 2.7 1.6.1 3.1.0 1.9.1 - - 3.16-beta1 3.0.1-b09 4.0.1 2.3.3 - 2.32 2.8.0 com.baeldung.SpringMVCApplication diff --git a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java b/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java index 768fda1c4a..c135164a95 100644 --- a/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java +++ b/spring-web-modules/spring-mvc-java/src/main/java/com/baeldung/spring/web/config/WebConfig.java @@ -27,7 +27,6 @@ import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templateresolver.ITemplateResolver; -import com.baeldung.excel.ExcelPOIHelper; @EnableWebMvc @Configuration @@ -118,11 +117,6 @@ public class WebConfig implements WebMvcConfigurer { configurer.setUrlPathHelper(urlPathHelper); } - @Bean - public ExcelPOIHelper excelPOIHelper() { - return new ExcelPOIHelper(); - } - @Bean(name = "multipartResolver") public CommonsMultipartResolver multipartResolver() { CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); diff --git a/spring-web-modules/spring-rest-http-3/pom.xml b/spring-web-modules/spring-rest-http-3/pom.xml index 1f2c66e999..2de635c1f1 100644 --- a/spring-web-modules/spring-rest-http-3/pom.xml +++ b/spring-web-modules/spring-rest-http-3/pom.xml @@ -20,6 +20,10 @@ org.springframework.boot spring-boot-starter-web + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + \ No newline at end of file diff --git a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/AppConfig.java b/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/AppConfig.java new file mode 100644 index 0000000000..c9c370e3cb --- /dev/null +++ b/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/AppConfig.java @@ -0,0 +1,13 @@ +package com.baeldung.xml; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AppConfig { + + public static void main(String[] args) { + SpringApplication.run(AppConfig.class, args); + } + +} diff --git a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/controller/User.java b/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/controller/User.java new file mode 100644 index 0000000000..3b3ba0e91f --- /dev/null +++ b/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/controller/User.java @@ -0,0 +1,79 @@ +package com.baeldung.xml.controller; + +import java.util.Objects; + +public class User { + + private Long id; + private String firstName; + private String secondName; + public User() { + } + + public User(final Long id, final String firstName, final String secondName) { + this.id = id; + this.firstName = firstName; + this.secondName = secondName; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(final String firstName) { + this.firstName = firstName; + } + + public String getSecondName() { + return secondName; + } + + public void setSecondName(final String secondName) { + this.secondName = secondName; + } + + public void setId(final Long id) { + this.id = id; + } + + public Long getId() { + return id; + } + + @Override + public boolean equals(final Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + final User user = (User) o; + + if (!Objects.equals(id, user.id)) { + return false; + } + if (!Objects.equals(firstName, user.firstName)) { + return false; + } + return Objects.equals(secondName, user.secondName); + } + + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (firstName != null ? firstName.hashCode() : 0); + result = 31 * result + (secondName != null ? secondName.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "User{" + + "id=" + id + + ", firstName='" + firstName + '\'' + + ", secondName='" + secondName + '\'' + + '}'; + } +} diff --git a/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/controller/UserEchoController.java b/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/controller/UserEchoController.java new file mode 100644 index 0000000000..7c3b99220c --- /dev/null +++ b/spring-web-modules/spring-rest-http-3/src/main/java/com/baeldung/xml/controller/UserEchoController.java @@ -0,0 +1,25 @@ +package com.baeldung.xml.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/users") +public class UserEchoController { + @ResponseStatus(HttpStatus.CREATED) + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) + public User echoJsonUser(@RequestBody User user) { + return user; + } + + @ResponseStatus(HttpStatus.CREATED) + @PostMapping(consumes = MediaType.APPLICATION_XML_VALUE, produces = MediaType.APPLICATION_XML_VALUE) + public User echoXmlUser(@RequestBody User user) { + return user; + } +} diff --git a/spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/xml/UserEchoControllerIntegrationTest.java b/spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/xml/UserEchoControllerIntegrationTest.java new file mode 100644 index 0000000000..54e7fa7551 --- /dev/null +++ b/spring-web-modules/spring-rest-http-3/src/test/java/com/baeldung/xml/UserEchoControllerIntegrationTest.java @@ -0,0 +1,71 @@ +package com.baeldung.xml; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.baeldung.xml.controller.User; +import com.baeldung.xml.controller.UserEchoController; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; + +@WebMvcTest(UserEchoController.class) +class UserEchoControllerIntegrationTest { + + private static final String URI = "/users"; + private static final User USER = new User(1L, "John", "Doe"); + private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); + private static final XmlMapper XML_MAPPER = new XmlMapper(); + + @Autowired + private UserEchoController controller; + + @Autowired + private MockMvc mockMvc; + + @Test + void whenContextStartBeansArePresent() { + assertThat(controller).isNotNull(); + assertThat(mockMvc).isNotNull(); + } + + @Test + void givenEndpointWhenPostJsonUserReceiveCorrectResponse() throws Exception { + final String payload = JSON_MAPPER.writeValueAsString(USER); + MockHttpServletRequestBuilder builder = + MockMvcRequestBuilders.post(URI) + .contentType(MediaType.APPLICATION_JSON) + .content(payload); + + final MvcResult mvcResult = this.mockMvc.perform(builder) + .andExpect(MockMvcResultMatchers.status() + .isCreated()).andReturn(); + final User actual + = JSON_MAPPER.readValue(mvcResult.getResponse().getContentAsString(), User.class); + assertThat(actual).isEqualTo(USER); + } + @Test + void givenEndpointWhenPostXmlUserReceiveCorrectResponse() throws Exception { + final String payload = XML_MAPPER.writeValueAsString(USER); + MockHttpServletRequestBuilder builder = + MockMvcRequestBuilders.post(URI) + .contentType(MediaType.APPLICATION_XML) + .accept(MediaType.APPLICATION_XML) + .content(payload); + + final MvcResult mvcResult = this.mockMvc.perform(builder) + .andExpect(MockMvcResultMatchers.status() + .isCreated()).andReturn(); + final User actual + = XML_MAPPER.readValue(mvcResult.getResponse().getContentAsString(), User.class); + assertThat(actual).isEqualTo(USER); + } + +} diff --git a/spring-web-modules/spring-resttemplate-3/pom.xml b/spring-web-modules/spring-resttemplate-3/pom.xml index 5ce7d348a2..7353ed38d7 100644 --- a/spring-web-modules/spring-resttemplate-3/pom.xml +++ b/spring-web-modules/spring-resttemplate-3/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -24,6 +24,16 @@ org.springframework.boot spring-boot-starter-test + + org.apache.httpcomponents.client5 + httpclient5 + ${httpclient5.version} + + + com.baeldung.resttemplate.methods.RestTemplateMethodsApplication + 5.2.1 + + diff --git a/spring-web-modules/spring-resttemplate-3/src/main/java/com/baeldung/resttemplate/custom/CustomRestTemplateConfiguration.java b/spring-web-modules/spring-resttemplate-3/src/main/java/com/baeldung/resttemplate/custom/CustomRestTemplateConfiguration.java index 9383b584c4..d29960789e 100644 --- a/spring-web-modules/spring-resttemplate-3/src/main/java/com/baeldung/resttemplate/custom/CustomRestTemplateConfiguration.java +++ b/spring-web-modules/spring-resttemplate-3/src/main/java/com/baeldung/resttemplate/custom/CustomRestTemplateConfiguration.java @@ -9,10 +9,12 @@ import java.security.cert.CertificateException; import javax.net.ssl.SSLContext; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.ssl.SSLContextBuilder; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.client5.http.io.HttpClientConnectionManager; +import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; +import org.apache.hc.core5.ssl.SSLContextBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -38,7 +40,11 @@ public class CustomRestTemplateConfiguration { .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build(); SSLConnectionSocketFactory sslConFactory = new SSLConnectionSocketFactory(sslContext); - CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConFactory).build(); + final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create() + .setSSLSocketFactory(sslConFactory) + .build(); + + CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build(); ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); return new RestTemplate(requestFactory); } diff --git a/spring-web-modules/spring-session/spring-session-jdbc/pom.xml b/spring-web-modules/spring-session/spring-session-jdbc/pom.xml index 3cc2b8d18e..24194f5426 100644 --- a/spring-web-modules/spring-session/spring-session-jdbc/pom.xml +++ b/spring-web-modules/spring-session/spring-session-jdbc/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-web-modules/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java b/spring-web-modules/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java index 509a5f292b..a173636ed8 100644 --- a/spring-web-modules/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java +++ b/spring-web-modules/spring-session/spring-session-jdbc/src/main/java/com/baeldung/springsessionjdbc/controller/SpringSessionJdbcController.java @@ -7,11 +7,12 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.List; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpSession; + @Controller public class SpringSessionJdbcController { diff --git a/spring-web-modules/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java b/spring-web-modules/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java index 2dcc0b3af8..7133111e4c 100644 --- a/spring-web-modules/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java +++ b/spring-web-modules/spring-session/spring-session-jdbc/src/test/java/com/baeldung/springsessionjdbc/SpringSessionJdbcIntegrationTest.java @@ -9,7 +9,7 @@ import org.junit.runners.MethodSorters; 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.test.context.junit4.SpringRunner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; diff --git a/spring-websockets/pom.xml b/spring-websockets/pom.xml index a28ef8749a..d6c5fbe561 100644 --- a/spring-websockets/pom.xml +++ b/spring-websockets/pom.xml @@ -22,11 +22,12 @@ io.projectreactor reactor-core + ${reactor-core.version} com.github.javafaker javafaker - 1.0.2 + ${javafaker.version} com.google.code.gson @@ -44,4 +45,9 @@ + + 3.6.0 + 1.0.2 + + \ No newline at end of file diff --git a/static-analysis/README.md b/static-analysis/README.md index 235b79853b..ea0d797407 100644 --- a/static-analysis/README.md +++ b/static-analysis/README.md @@ -6,3 +6,4 @@ This module contains articles about static program analysis - [Introduction to PMD](https://www.baeldung.com/pmd) - [Java Static Analysis Tools in Eclipse and IntelliJ IDEA](https://www.baeldung.com/java-static-analysis-tools) +- [Catch Common Mistakes with Error Prone Library in Java](https://www.baeldung.com/java-error-prone-library) diff --git a/static-analysis/error-prone-project/pom.xml b/static-analysis/error-prone-project/pom.xml index 59f7bb7270..6747a3d3ed 100644 --- a/static-analysis/error-prone-project/pom.xml +++ b/static-analysis/error-prone-project/pom.xml @@ -3,23 +3,21 @@ 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 + error-prone-project + com.baeldung static-analysis 1.0-SNAPSHOT - error-prone-project - org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} 17 - UTF-8 true -XDcompilePolicy=simple @@ -44,7 +42,7 @@ com.baeldung my-bugchecker-plugin - 1.0-SNAPSHOT + ${my-bugchecker-plugin.version} @@ -53,9 +51,7 @@ - 17 - 17 - UTF-8 + 1.0-SNAPSHOT diff --git a/static-analysis/my-bugchecker-plugin/pom.xml b/static-analysis/my-bugchecker-plugin/pom.xml index cbe16b0a14..03f7761759 100644 --- a/static-analysis/my-bugchecker-plugin/pom.xml +++ b/static-analysis/my-bugchecker-plugin/pom.xml @@ -3,20 +3,20 @@ 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 + my-bugchecker-plugin + jar + com.baeldung static-analysis 1.0-SNAPSHOT - jar - my-bugchecker-plugin org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} @@ -47,10 +47,4 @@ - - 17 - 17 - UTF-8 - - diff --git a/static-analysis/pmd/pom.xml b/static-analysis/pmd/pom.xml index 31914fe9f0..372c122776 100644 --- a/static-analysis/pmd/pom.xml +++ b/static-analysis/pmd/pom.xml @@ -3,18 +3,12 @@ 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 + pmd + com.baeldung static-analysis 1.0-SNAPSHOT - pmd - - - 17 - 17 - UTF-8 - - diff --git a/tablesaw/pom.xml b/tablesaw/pom.xml index f38e4cb8b4..c45931a9e2 100644 --- a/tablesaw/pom.xml +++ b/tablesaw/pom.xml @@ -25,11 +25,6 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 - - 17 - 17 - diff --git a/testing-modules/cucumber/pom.xml b/testing-modules/cucumber/pom.xml index c1d99bb492..088a75a941 100644 --- a/testing-modules/cucumber/pom.xml +++ b/testing-modules/cucumber/pom.xml @@ -121,8 +121,6 @@ - 14 - 14 6.10.3 5.4.0 3.141.59 diff --git a/testing-modules/gatling-java/pom.xml b/testing-modules/gatling-java/pom.xml index abe033f298..d28876b42c 100644 --- a/testing-modules/gatling-java/pom.xml +++ b/testing-modules/gatling-java/pom.xml @@ -33,7 +33,7 @@ org.projectlombok lombok - 1.18.24 + ${lombok.version} provided @@ -72,9 +72,6 @@ - 1.8 - 1.8 - UTF-8 3.9.5 4.3.0 1.0.2 diff --git a/testing-modules/gatling/pom.xml b/testing-modules/gatling/pom.xml index 82ce988bac..e5b1db2bfb 100644 --- a/testing-modules/gatling/pom.xml +++ b/testing-modules/gatling/pom.xml @@ -105,9 +105,6 @@ - 1.8 - 1.8 - UTF-8 2.12.6 3.3.1 4.3.0 diff --git a/testing-modules/groovy-spock/pom.xml b/testing-modules/groovy-spock/pom.xml index 7f456399fe..7920713810 100644 --- a/testing-modules/groovy-spock/pom.xml +++ b/testing-modules/groovy-spock/pom.xml @@ -15,6 +15,12 @@ 1.0.0-SNAPSHOT + + 2.4-M1-groovy-4.0 + 4.0.16 + 3.0.2 + + org.spockframework @@ -23,9 +29,10 @@ test - org.codehaus.groovy + org.apache.groovy groovy-all ${groovy-all.version} + pom @@ -39,18 +46,34 @@ compile - testCompile + compileTests + + + + ${project.basedir}/src/test/groovy + + **/*.groovy + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.2.2 + + src/test/groovy + + **/*Specification.groovy + **/*Test.groovy + + - - 1.3-groovy-2.4 - 2.4.7 - 1.5 - - \ No newline at end of file diff --git a/testing-modules/groovy-spock/src/main/java/mocks/Book.java b/testing-modules/groovy-spock/src/main/java/mocks/Book.java new file mode 100644 index 0000000000..b3f3f78606 --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/mocks/Book.java @@ -0,0 +1,11 @@ +package mocks; + +public class Book { + private String title; + private String author; + + Book(String title, String author) { + this.title = title; + this.author = author; + } +} diff --git a/testing-modules/groovy-spock/src/main/java/mocks/BookRepository.java b/testing-modules/groovy-spock/src/main/java/mocks/BookRepository.java new file mode 100644 index 0000000000..2628a6cab3 --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/mocks/BookRepository.java @@ -0,0 +1,5 @@ +package mocks; + +public interface BookRepository { + Book findById(Long id); +} \ No newline at end of file diff --git a/testing-modules/groovy-spock/src/main/java/mocks/BookService.java b/testing-modules/groovy-spock/src/main/java/mocks/BookService.java new file mode 100644 index 0000000000..750affec9e --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/mocks/BookService.java @@ -0,0 +1,13 @@ +package mocks; + +public class BookService { + private final BookRepository repository; + + public BookService(BookRepository repository) { + this.repository = repository; + } + + public Book getBookDetails(Long id) { + return repository.findById(id); + } +} diff --git a/testing-modules/groovy-spock/src/main/java/mocks/MessageService.java b/testing-modules/groovy-spock/src/main/java/mocks/MessageService.java new file mode 100644 index 0000000000..f9e4c5d938 --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/mocks/MessageService.java @@ -0,0 +1,7 @@ +package mocks; + +public class MessageService { + public String fetchMessage() { + return UtilityClass.getMessage(); + } +} \ No newline at end of file diff --git a/testing-modules/groovy-spock/src/main/java/mocks/ShoppingCart.java b/testing-modules/groovy-spock/src/main/java/mocks/ShoppingCart.java new file mode 100644 index 0000000000..94444c426f --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/mocks/ShoppingCart.java @@ -0,0 +1,26 @@ +package mocks; + +import java.util.HashMap; +import java.util.Map; + +public class ShoppingCart { + private final Map items = new HashMap<>(); + private double totalPrice = 0.0; + + public void addItem(String item, int quantity) { + items.put(item, items.getOrDefault(item, 0) + quantity); + totalPrice += quantity * 2.00; // Example pricing + } + + public int getTotalItems() { + return items.values().stream().mapToInt(Integer::intValue).sum(); + } + + public double getTotalPrice() { + return totalPrice; + } + + public boolean containsItem(String item) { + return items.containsKey(item); + } +} \ No newline at end of file diff --git a/testing-modules/groovy-spock/src/main/java/mocks/UtilityClass.java b/testing-modules/groovy-spock/src/main/java/mocks/UtilityClass.java new file mode 100644 index 0000000000..a218e9088c --- /dev/null +++ b/testing-modules/groovy-spock/src/main/java/mocks/UtilityClass.java @@ -0,0 +1,7 @@ +package mocks; + +public class UtilityClass { + public static String getMessage() { + return "Original Message"; + } +} \ No newline at end of file diff --git a/testing-modules/groovy-spock/src/test/groovy/extensions/ShoppingCartTest.groovy b/testing-modules/groovy-spock/src/test/groovy/extensions/ShoppingCartTest.groovy new file mode 100644 index 0000000000..116951988d --- /dev/null +++ b/testing-modules/groovy-spock/src/test/groovy/extensions/ShoppingCartTest.groovy @@ -0,0 +1,21 @@ +package extensions + +import mocks.ShoppingCart +import spock.lang.Specification + +class ShoppingCartTest extends Specification { + def "verify multiple properties of a ShoppingCart"() { + given: + ShoppingCart cart = new ShoppingCart() + cart.addItem("Apple", 3) + cart.addItem("Banana", 2) + + expect: + with(cart) { + totalItems == 5 + totalPrice == 10.00 + items.contains("Apple") + items.contains("Banana") + } + } +} \ No newline at end of file diff --git a/testing-modules/groovy-spock/src/test/groovy/mocks/BookServiceTest.groovy b/testing-modules/groovy-spock/src/test/groovy/mocks/BookServiceTest.groovy new file mode 100644 index 0000000000..b33cf6c015 --- /dev/null +++ b/testing-modules/groovy-spock/src/test/groovy/mocks/BookServiceTest.groovy @@ -0,0 +1,25 @@ +package mocks + +import spock.lang.Specification + + +class BookServiceTest extends Specification { + def "should retrieve book details and verify method calls"() { + given: + def bookRepository = Mock(BookRepository) { + findById(1L) >> new Book("Effective Java", "Joshua Bloch") + findById(2L) >> null + } + def bookService = new BookService(bookRepository) + + when: + Book effectiveJava = bookService.getBookDetails(1L) + Book unknownBook = bookService.getBookDetails(2L) + + then: + 1 * bookRepository.findById(1L) + 1 * bookRepository.findById(2L) + effectiveJava.title == "Effective Java" + unknownBook == null + } +} \ No newline at end of file diff --git a/testing-modules/groovy-spock/src/test/groovy/mocks/MessageServiceTest.groovy b/testing-modules/groovy-spock/src/test/groovy/mocks/MessageServiceTest.groovy new file mode 100644 index 0000000000..7eeea90e41 --- /dev/null +++ b/testing-modules/groovy-spock/src/test/groovy/mocks/MessageServiceTest.groovy @@ -0,0 +1,20 @@ +package mocks + +import spock.lang.Specification + + +class MessageServiceTest extends Specification { + def "should use global mock for UtilityClass"() { + given: + def utilityMock = GroovySpy(UtilityClass, global: true) + utilityMock.getMessage() >> "Mocked Message" + + when: + MessageService service = new MessageService() + String message = service.fetchMessage() + + then: + 1 * utilityMock.getMessage() + message == "Mocked Message" + } +} \ No newline at end of file diff --git a/testing-modules/hamcrest/pom.xml b/testing-modules/hamcrest/pom.xml index df8c543edb..0f2f4ba334 100644 --- a/testing-modules/hamcrest/pom.xml +++ b/testing-modules/hamcrest/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + testing-modules + 1.0.0-SNAPSHOT @@ -22,6 +21,11 @@ ${java-hamcrest.version} test + + com.google.guava + guava + ${guava.version} + diff --git a/jmeter/.gitignore b/testing-modules/jmeter/.gitignore similarity index 100% rename from jmeter/.gitignore rename to testing-modules/jmeter/.gitignore diff --git a/jmeter/.mvn/wrapper/maven-wrapper.jar b/testing-modules/jmeter/.mvn/wrapper/maven-wrapper.jar similarity index 100% rename from jmeter/.mvn/wrapper/maven-wrapper.jar rename to testing-modules/jmeter/.mvn/wrapper/maven-wrapper.jar diff --git a/jmeter/.mvn/wrapper/maven-wrapper.properties b/testing-modules/jmeter/.mvn/wrapper/maven-wrapper.properties similarity index 100% rename from jmeter/.mvn/wrapper/maven-wrapper.properties rename to testing-modules/jmeter/.mvn/wrapper/maven-wrapper.properties diff --git a/jmeter/README.md b/testing-modules/jmeter/README.md similarity index 100% rename from jmeter/README.md rename to testing-modules/jmeter/README.md diff --git a/jmeter/jmeter.log b/testing-modules/jmeter/jmeter.log similarity index 100% rename from jmeter/jmeter.log rename to testing-modules/jmeter/jmeter.log diff --git a/jmeter/mvnw b/testing-modules/jmeter/mvnw old mode 100755 new mode 100644 similarity index 100% rename from jmeter/mvnw rename to testing-modules/jmeter/mvnw diff --git a/jmeter/mvnw.cmd b/testing-modules/jmeter/mvnw.cmd similarity index 100% rename from jmeter/mvnw.cmd rename to testing-modules/jmeter/mvnw.cmd diff --git a/jmeter/pom.xml b/testing-modules/jmeter/pom.xml similarity index 99% rename from jmeter/pom.xml rename to testing-modules/jmeter/pom.xml index 5f4105d282..67a21f6c86 100644 --- a/jmeter/pom.xml +++ b/testing-modules/jmeter/pom.xml @@ -12,7 +12,7 @@ com.baeldung parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-2 + ../../parent-boot-2 diff --git a/jmeter/src/main/java/com/baeldung/SpringJMeterJenkinsApplication.java b/testing-modules/jmeter/src/main/java/com/baeldung/SpringJMeterJenkinsApplication.java similarity index 100% rename from jmeter/src/main/java/com/baeldung/SpringJMeterJenkinsApplication.java rename to testing-modules/jmeter/src/main/java/com/baeldung/SpringJMeterJenkinsApplication.java diff --git a/jmeter/src/main/java/com/baeldung/configuration/WebSecurityConfiguration.java b/testing-modules/jmeter/src/main/java/com/baeldung/configuration/WebSecurityConfiguration.java similarity index 100% rename from jmeter/src/main/java/com/baeldung/configuration/WebSecurityConfiguration.java rename to testing-modules/jmeter/src/main/java/com/baeldung/configuration/WebSecurityConfiguration.java diff --git a/jmeter/src/main/java/com/baeldung/controller/RetrieveUuidController.java b/testing-modules/jmeter/src/main/java/com/baeldung/controller/RetrieveUuidController.java similarity index 100% rename from jmeter/src/main/java/com/baeldung/controller/RetrieveUuidController.java rename to testing-modules/jmeter/src/main/java/com/baeldung/controller/RetrieveUuidController.java diff --git a/jmeter/src/main/java/com/baeldung/controller/SecuredUuidController.java b/testing-modules/jmeter/src/main/java/com/baeldung/controller/SecuredUuidController.java similarity index 100% rename from jmeter/src/main/java/com/baeldung/controller/SecuredUuidController.java rename to testing-modules/jmeter/src/main/java/com/baeldung/controller/SecuredUuidController.java diff --git a/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java b/testing-modules/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java similarity index 100% rename from jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java rename to testing-modules/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java diff --git a/jmeter/src/main/java/com/baeldung/dashboard/controllers/Dashboard.java b/testing-modules/jmeter/src/main/java/com/baeldung/dashboard/controllers/Dashboard.java similarity index 100% rename from jmeter/src/main/java/com/baeldung/dashboard/controllers/Dashboard.java rename to testing-modules/jmeter/src/main/java/com/baeldung/dashboard/controllers/Dashboard.java diff --git a/jmeter/src/main/java/com/baeldung/dashboard/models/Quotes.java b/testing-modules/jmeter/src/main/java/com/baeldung/dashboard/models/Quotes.java similarity index 100% rename from jmeter/src/main/java/com/baeldung/dashboard/models/Quotes.java rename to testing-modules/jmeter/src/main/java/com/baeldung/dashboard/models/Quotes.java diff --git a/jmeter/src/main/java/com/baeldung/domain/Student.java b/testing-modules/jmeter/src/main/java/com/baeldung/domain/Student.java similarity index 100% rename from jmeter/src/main/java/com/baeldung/domain/Student.java rename to testing-modules/jmeter/src/main/java/com/baeldung/domain/Student.java diff --git a/jmeter/src/main/java/com/baeldung/model/Response.java b/testing-modules/jmeter/src/main/java/com/baeldung/model/Response.java similarity index 100% rename from jmeter/src/main/java/com/baeldung/model/Response.java rename to testing-modules/jmeter/src/main/java/com/baeldung/model/Response.java diff --git a/jmeter/src/main/java/com/baeldung/repository/StudentRepository.java b/testing-modules/jmeter/src/main/java/com/baeldung/repository/StudentRepository.java similarity index 100% rename from jmeter/src/main/java/com/baeldung/repository/StudentRepository.java rename to testing-modules/jmeter/src/main/java/com/baeldung/repository/StudentRepository.java diff --git a/jmeter/src/main/resources/20171213-JMeter.csv b/testing-modules/jmeter/src/main/resources/20171213-JMeter.csv similarity index 100% rename from jmeter/src/main/resources/20171213-JMeter.csv rename to testing-modules/jmeter/src/main/resources/20171213-JMeter.csv diff --git a/testing-modules/jmeter/src/main/resources/20230218-Basic Authentication - JSR223.csv b/testing-modules/jmeter/src/main/resources/20230218-Basic Authentication - JSR223.csv new file mode 100644 index 0000000000..e5cd1ee8da --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20230218-Basic Authentication - JSR223.csv @@ -0,0 +1,8 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,Latency,IdleTime,Connect +1676710986043,566,Soap Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Number of Users 1-1,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: java.net.ConnectException]]] + +****** comparison: [[[200 ]]] + +/",2215,0,1,1,0,0,565 diff --git a/testing-modules/jmeter/src/main/resources/20230218-Basic Authentication - authorization manager with CSV.csv b/testing-modules/jmeter/src/main/resources/20230218-Basic Authentication - authorization manager with CSV.csv new file mode 100644 index 0000000000..f8f7b1c4aa --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20230218-Basic Authentication - authorization manager with CSV.csv @@ -0,0 +1 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,Latency,IdleTime,Connect diff --git a/testing-modules/jmeter/src/main/resources/20230218-Basic Authentication - authorization manager.csv b/testing-modules/jmeter/src/main/resources/20230218-Basic Authentication - authorization manager.csv new file mode 100644 index 0000000000..046a8b6952 --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20230218-Basic Authentication - authorization manager.csv @@ -0,0 +1,8 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,Latency,IdleTime,Connect +1676711042893,242,Soap Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Number of Users 1-1,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: java.net.ConnectException]]] + +****** comparison: [[[200 ]]] + +/",2215,0,1,1,0,0,241 diff --git a/testing-modules/jmeter/src/main/resources/20230218-Basic Authentication.csv b/testing-modules/jmeter/src/main/resources/20230218-Basic Authentication.csv new file mode 100644 index 0000000000..437a166983 --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20230218-Basic Authentication.csv @@ -0,0 +1,71 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,Latency,IdleTime,Connect +1676711056693,272,Soap Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Number of Users 1-1,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: java.net.ConnectException]]] + +****** comparison: [[[200 ]]] + +/",2215,0,1,1,0,0,271 +1676711056996,4,Soap Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Number of Users 1-1,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: java.net.ConnectException]]] + +****** comparison: [[[200 ]]] + +/",2215,0,1,1,0,0,4 +1676711057419,14,Soap Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Number of Users 1-2,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: java.net.ConnectException]]] + +****** comparison: [[[200 ]]] + +/",2215,0,1,1,0,0,13 +1676711057445,5,Soap Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Number of Users 1-2,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: java.net.ConnectException]]] + +****** comparison: [[[200 ]]] + +/",2215,0,1,1,0,0,4 +1676711058459,4,Soap Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Number of Users 1-3,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: java.net.ConnectException]]] + +****** comparison: [[[200 ]]] + +/",2215,0,1,1,0,0,4 +1676711058467,3,Soap Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Number of Users 1-3,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: java.net.ConnectException]]] + +****** comparison: [[[200 ]]] + +/",2215,0,1,1,0,0,3 +1676711059400,3,Soap Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Number of Users 1-4,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: java.net.ConnectException]]] + +****** comparison: [[[200 ]]] + +/",2215,0,1,1,0,0,3 +1676711059405,2,Soap Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Number of Users 1-4,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: java.net.ConnectException]]] + +****** comparison: [[[200 ]]] + +/",2215,0,1,1,0,0,2 +1676711060398,3,Soap Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Number of Users 1-5,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: java.net.ConnectException]]] + +****** comparison: [[[200 ]]] + +/",2215,0,1,1,0,0,3 +1676711060404,3,Soap Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Number of Users 1-5,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: java.net.ConnectException]]] + +****** comparison: [[[200 ]]] + +/",2215,0,1,1,0,0,3 diff --git a/testing-modules/jmeter/src/main/resources/20230218-JMeter - Latency Vs Load Time.csv b/testing-modules/jmeter/src/main/resources/20230218-JMeter - Latency Vs Load Time.csv new file mode 100644 index 0000000000..af582e356d --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20230218-JMeter - Latency Vs Load Time.csv @@ -0,0 +1,2 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,Latency,IdleTime,Connect +1676711079234,183,HTTP Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Thread Group 1-1,text,false,,2215,0,1,1,0,0,183 diff --git a/testing-modules/jmeter/src/main/resources/20230218-JMeter.csv b/testing-modules/jmeter/src/main/resources/20230218-JMeter.csv new file mode 100644 index 0000000000..5b3af58dd9 --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20230218-JMeter.csv @@ -0,0 +1,6 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,Latency,IdleTime,Connect +1676711094371,176,HTTP Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Thread Group 1-1,text,false,"The operation lasted too long: It took 176 milliseconds, but should not have lasted longer than 10 milliseconds.",2215,0,3,3,0,0,175 +1676711094372,176,HTTP Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Thread Group 1-2,text,false,"The operation lasted too long: It took 176 milliseconds, but should not have lasted longer than 10 milliseconds.",2215,0,3,3,0,0,175 +1676711094556,10,HTTP Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Thread Group 1-3,text,false,,2215,0,1,1,0,0,9 +1676711094755,3,HTTP Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Thread Group 1-4,text,false,,2215,0,1,1,0,0,3 +1676711094954,3,HTTP Request,Non HTTP response code: java.net.ConnectException,Non HTTP response message: Connection refused: connect,Thread Group 1-5,text,false,,2215,0,1,1,0,0,3 diff --git a/testing-modules/jmeter/src/main/resources/20231227-Basic Authentication - JSR223.csv b/testing-modules/jmeter/src/main/resources/20231227-Basic Authentication - JSR223.csv new file mode 100644 index 0000000000..3c58509da1 --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20231227-Basic Authentication - JSR223.csv @@ -0,0 +1,8 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect +1703684618895,36,Soap Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Number of Users 1-1,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: org.apache.http.conn.HttpHostConnectException]]] + +****** comparison: [[[200 ]]] + +/",2630,0,1,1,http://localhost:8080/secured/uuid,0,0,36 diff --git a/testing-modules/jmeter/src/main/resources/20231227-Basic Authentication - authorization manager with CSV.csv b/testing-modules/jmeter/src/main/resources/20231227-Basic Authentication - authorization manager with CSV.csv new file mode 100644 index 0000000000..d9ef28eda1 --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20231227-Basic Authentication - authorization manager with CSV.csv @@ -0,0 +1 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect diff --git a/testing-modules/jmeter/src/main/resources/20231227-Basic Authentication - authorization manager.csv b/testing-modules/jmeter/src/main/resources/20231227-Basic Authentication - authorization manager.csv new file mode 100644 index 0000000000..b6cf8a4eb5 --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20231227-Basic Authentication - authorization manager.csv @@ -0,0 +1,8 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect +1703684613746,78,Soap Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Number of Users 1-1,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: org.apache.http.conn.HttpHostConnectException]]] + +****** comparison: [[[200 ]]] + +/",2630,0,1,1,http://localhost:8080/secured/uuid,0,0,78 diff --git a/testing-modules/jmeter/src/main/resources/20231227-Basic Authentication.csv b/testing-modules/jmeter/src/main/resources/20231227-Basic Authentication.csv new file mode 100644 index 0000000000..9d300b8c7a --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20231227-Basic Authentication.csv @@ -0,0 +1,71 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect +1703684622694,46,Soap Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Number of Users 1-1,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: org.apache.http.conn.HttpHostConnectException]]] + +****** comparison: [[[200 ]]] + +/",2630,0,1,1,http://localhost:8080/secured/uuid,0,0,46 +1703684622755,2,Soap Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Number of Users 1-1,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: org.apache.http.conn.HttpHostConnectException]]] + +****** comparison: [[[200 ]]] + +/",2630,0,1,1,http://localhost:8080/secured/uuid,0,0,2 +1703684623515,4,Soap Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Number of Users 1-2,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: org.apache.http.conn.HttpHostConnectException]]] + +****** comparison: [[[200 ]]] + +/",2630,0,1,1,http://localhost:8080/secured/uuid,0,0,4 +1703684623524,3,Soap Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Number of Users 1-2,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: org.apache.http.conn.HttpHostConnectException]]] + +****** comparison: [[[200 ]]] + +/",2630,0,1,1,http://localhost:8080/secured/uuid,0,0,3 +1703684624513,4,Soap Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Number of Users 1-3,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: org.apache.http.conn.HttpHostConnectException]]] + +****** comparison: [[[200 ]]] + +/",2630,0,1,1,http://localhost:8080/secured/uuid,0,0,4 +1703684624522,5,Soap Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Number of Users 1-3,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: org.apache.http.conn.HttpHostConnectException]]] + +****** comparison: [[[200 ]]] + +/",2630,0,1,1,http://localhost:8080/secured/uuid,0,0,5 +1703684625514,5,Soap Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Number of Users 1-4,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: org.apache.http.conn.HttpHostConnectException]]] + +****** comparison: [[[200 ]]] + +/",2630,0,1,1,http://localhost:8080/secured/uuid,0,0,5 +1703684625523,5,Soap Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Number of Users 1-4,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: org.apache.http.conn.HttpHostConnectException]]] + +****** comparison: [[[200 ]]] + +/",2630,0,1,1,http://localhost:8080/secured/uuid,0,0,5 +1703684626512,6,Soap Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Number of Users 1-5,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: org.apache.http.conn.HttpHostConnectException]]] + +****** comparison: [[[200 ]]] + +/",2630,0,1,1,http://localhost:8080/secured/uuid,0,0,6 +1703684626522,3,Soap Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Number of Users 1-5,text,false,"Test failed: code expected to equal / + +****** received : [[[Non HTTP response code: org.apache.http.conn.HttpHostConnectException]]] + +****** comparison: [[[200 ]]] + +/",2630,0,1,1,http://localhost:8080/secured/uuid,0,0,3 diff --git a/testing-modules/jmeter/src/main/resources/20231227-FileExtractionExample.csv b/testing-modules/jmeter/src/main/resources/20231227-FileExtractionExample.csv new file mode 100644 index 0000000000..7a20e9996b --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20231227-FileExtractionExample.csv @@ -0,0 +1,2 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect +1703684634069,50,Call GET Test endpoint ,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-1,text,false,,2630,0,1,1,http://localhost:8080/api/test,0,0,50 diff --git a/testing-modules/jmeter/src/main/resources/20231227-JMeter - Latency Vs Load Time.csv b/testing-modules/jmeter/src/main/resources/20231227-JMeter - Latency Vs Load Time.csv new file mode 100644 index 0000000000..b96a0282df --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20231227-JMeter - Latency Vs Load Time.csv @@ -0,0 +1,2 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect +1703684637458,61,HTTP Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:3000 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-1,text,false,,2630,0,1,1,http://localhost:3000,0,0,60 diff --git a/testing-modules/jmeter/src/main/resources/20231227-JMeter.csv b/testing-modules/jmeter/src/main/resources/20231227-JMeter.csv new file mode 100644 index 0000000000..81b3054cde --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20231227-JMeter.csv @@ -0,0 +1,6 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect +1703684641070,57,HTTP Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8989 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-2,text,false,"The operation lasted too long: It took 57 milliseconds, but should not have lasted longer than 10 milliseconds.",2630,0,2,2,http://localhost:8989/students,0,0,56 +1703684641072,55,HTTP Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8989 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-1,text,false,"The operation lasted too long: It took 55 milliseconds, but should not have lasted longer than 10 milliseconds.",2630,0,2,2,http://localhost:8989/students,0,0,54 +1703684641237,2,HTTP Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8989 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-3,text,false,,2630,0,1,1,http://localhost:8989/students,0,0,2 +1703684641433,1,HTTP Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8989 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-4,text,false,,2630,0,1,1,http://localhost:8989/students,0,0,1 +1703684641635,5,HTTP Request,Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8989 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-5,text,false,,2630,0,1,1,http://localhost:8989/students,0,0,5 diff --git a/testing-modules/jmeter/src/main/resources/20231227-dashboard_ReportsDashboard.csv b/testing-modules/jmeter/src/main/resources/20231227-dashboard_ReportsDashboard.csv new file mode 100644 index 0000000000..e119f6f08e --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20231227-dashboard_ReportsDashboard.csv @@ -0,0 +1,16 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect +1703684629839,26,HTTP Request (/greeting),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-2,text,false,,2630,0,2,2,http://localhost:8080/greeting,0,0,26 +1703684629818,46,HTTP Request (/greeting),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-1,text,false,,2630,0,2,2,http://localhost:8080/greeting,0,0,46 +1703684629871,2,HTTP Request (/quote),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-1,text,false,,2630,0,2,2,http://localhost:8080/quote,0,0,2 +1703684629871,3,HTTP Request (/quote),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-2,text,false,,2630,0,2,2,http://localhost:8080/quote,0,0,3 +1703684629875,2,HTTP Request (/time),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-1,text,false,,2630,0,2,2,http://localhost:8080/time,0,0,2 +1703684629878,5,HTTP Request (/time),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-2,text,false,,2630,0,1,1,http://localhost:8080/time,0,0,4 +1703684630036,5,HTTP Request (/greeting),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-3,text,false,,2630,0,1,1,http://localhost:8080/greeting,0,0,5 +1703684630045,3,HTTP Request (/quote),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-3,text,false,,2630,0,1,1,http://localhost:8080/quote,0,0,3 +1703684630051,3,HTTP Request (/time),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-3,text,false,,2630,0,1,1,http://localhost:8080/time,0,0,3 +1703684630238,8,HTTP Request (/greeting),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-4,text,false,,2630,0,1,1,http://localhost:8080/greeting,0,0,8 +1703684630257,9,HTTP Request (/quote),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-4,text,false,,2630,0,1,1,http://localhost:8080/quote,0,0,6 +1703684630275,10,HTTP Request (/time),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-4,text,false,,2630,0,1,1,http://localhost:8080/time,0,0,9 +1703684630435,3,HTTP Request (/greeting),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-5,text,false,,2630,0,1,1,http://localhost:8080/greeting,0,0,3 +1703684630443,5,HTTP Request (/quote),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-5,text,false,,2630,0,1,1,http://localhost:8080/quote,0,0,5 +1703684630451,4,HTTP Request (/time),Non HTTP response code: org.apache.http.conn.HttpHostConnectException,"Non HTTP response message: Connect to localhost:8080 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect",Thread Group 1-5,text,false,,2630,0,1,1,http://localhost:8080/time,0,0,4 diff --git a/testing-modules/jmeter/src/main/resources/20231227-summary-report_Summary-Report.csv b/testing-modules/jmeter/src/main/resources/20231227-summary-report_Summary-Report.csv new file mode 100644 index 0000000000..61a9e9ea27 --- /dev/null +++ b/testing-modules/jmeter/src/main/resources/20231227-summary-report_Summary-Report.csv @@ -0,0 +1,51 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect +1703684645545,2050,HTTP Request,200,OK,Thread Group 1-3,text,true,,679,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,1860,0,1606 +1703684645851,1744,HTTP Request,200,OK,Thread Group 1-5,text,true,,679,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,1555,0,1304 +1703684645291,2304,HTTP Request,200,OK,Thread Group 1-2,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,2144,0,1867 +1703684645290,2304,HTTP Request,200,OK,Thread Group 1-1,text,true,,675,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,2162,0,1904 +1703684645662,1933,HTTP Request,200,OK,Thread Group 1-4,text,true,,679,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,1772,0,1500 +1703684647606,223,HTTP Request,200,OK,Thread Group 1-3,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,223,0,0 +1703684647602,235,HTTP Request,200,OK,Thread Group 1-5,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,234,0,0 +1703684647602,234,HTTP Request,200,OK,Thread Group 1-4,text,true,,685,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,233,0,0 +1703684647603,238,HTTP Request,200,OK,Thread Group 1-2,text,true,,675,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,235,0,0 +1703684647604,245,HTTP Request,200,OK,Thread Group 1-1,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,244,0,0 +1703684647831,230,HTTP Request,200,OK,Thread Group 1-3,text,true,,679,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,229,0,0 +1703684647839,257,HTTP Request,200,OK,Thread Group 1-4,text,true,,679,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,256,0,0 +1703684647838,258,HTTP Request,200,OK,Thread Group 1-5,text,true,,679,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,257,0,0 +1703684647842,256,HTTP Request,200,OK,Thread Group 1-2,text,true,,679,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,255,0,0 +1703684647851,251,HTTP Request,200,OK,Thread Group 1-1,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,251,0,0 +1703684648063,227,HTTP Request,200,OK,Thread Group 1-3,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,226,0,0 +1703684648097,246,HTTP Request,200,OK,Thread Group 1-4,text,true,,681,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,245,0,0 +1703684648100,243,HTTP Request,200,OK,Thread Group 1-2,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,242,0,0 +1703684648097,250,HTTP Request,200,OK,Thread Group 1-5,text,true,,675,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,247,0,0 +1703684648103,261,HTTP Request,200,OK,Thread Group 1-1,text,true,,675,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,260,0,0 +1703684648292,224,HTTP Request,200,OK,Thread Group 1-3,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,224,0,0 +1703684648345,234,HTTP Request,200,OK,Thread Group 1-4,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,234,0,0 +1703684648345,253,HTTP Request,200,OK,Thread Group 1-2,text,true,,679,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,252,0,0 +1703684648349,254,HTTP Request,200,OK,Thread Group 1-5,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,253,0,0 +1703684648366,247,HTTP Request,200,OK,Thread Group 1-1,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,246,0,0 +1703684648518,227,HTTP Request,200,OK,Thread Group 1-3,text,true,,679,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,226,0,0 +1703684648580,237,HTTP Request,200,OK,Thread Group 1-4,text,true,,679,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,237,0,0 +1703684648599,234,HTTP Request,200,OK,Thread Group 1-2,text,true,,675,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,234,0,0 +1703684648604,238,HTTP Request,200,OK,Thread Group 1-5,text,true,,679,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,238,0,0 +1703684648614,244,HTTP Request,200,OK,Thread Group 1-1,text,true,,681,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,244,0,0 +1703684648746,222,HTTP Request,200,OK,Thread Group 1-3,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,222,0,0 +1703684648818,232,HTTP Request,200,OK,Thread Group 1-4,text,true,,685,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,232,0,0 +1703684648834,235,HTTP Request,200,OK,Thread Group 1-2,text,true,,675,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,235,0,0 +1703684648844,229,HTTP Request,200,OK,Thread Group 1-5,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,229,0,0 +1703684648859,243,HTTP Request,200,OK,Thread Group 1-1,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,242,0,0 +1703684648969,225,HTTP Request,200,OK,Thread Group 1-3,text,true,,675,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,224,0,0 +1703684649051,232,HTTP Request,200,OK,Thread Group 1-4,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,232,0,0 +1703684649070,231,HTTP Request,200,OK,Thread Group 1-2,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,231,0,0 +1703684649074,230,HTTP Request,200,OK,Thread Group 1-5,text,true,,681,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,230,0,0 +1703684649103,242,HTTP Request,200,OK,Thread Group 1-1,text,true,,679,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,241,0,0 +1703684649194,227,HTTP Request,200,OK,Thread Group 1-3,text,true,,675,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,226,0,0 +1703684649284,233,HTTP Request,200,OK,Thread Group 1-4,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,232,0,0 +1703684649303,232,HTTP Request,200,OK,Thread Group 1-2,text,true,,675,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,231,0,0 +1703684649305,233,HTTP Request,200,OK,Thread Group 1-5,text,true,,675,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,233,0,0 +1703684649346,242,HTTP Request,200,OK,Thread Group 1-1,text,true,,681,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,242,0,0 +1703684649422,227,HTTP Request,200,OK,Thread Group 1-3,text,true,,677,141,5,5,https://postman-echo.com/get?foo1=bar1&foo2=bar2,227,0,0 +1703684649518,232,HTTP Request,200,OK,Thread Group 1-4,text,true,,683,141,4,4,https://postman-echo.com/get?foo1=bar1&foo2=bar2,232,0,0 +1703684649536,234,HTTP Request,200,OK,Thread Group 1-2,text,true,,679,141,3,3,https://postman-echo.com/get?foo1=bar1&foo2=bar2,234,0,0 +1703684649539,234,HTTP Request,200,OK,Thread Group 1-5,text,true,,675,141,2,2,https://postman-echo.com/get?foo1=bar1&foo2=bar2,234,0,0 +1703684649589,249,HTTP Request,200,OK,Thread Group 1-1,text,true,,675,141,1,1,https://postman-echo.com/get?foo1=bar1&foo2=bar2,249,0,0 diff --git a/jmeter/src/main/resources/Basic Authentication - JSR223.jmx b/testing-modules/jmeter/src/main/resources/Basic Authentication - JSR223.jmx similarity index 100% rename from jmeter/src/main/resources/Basic Authentication - JSR223.jmx rename to testing-modules/jmeter/src/main/resources/Basic Authentication - JSR223.jmx diff --git a/jmeter/src/main/resources/Basic Authentication - authorization manager with CSV.jmx b/testing-modules/jmeter/src/main/resources/Basic Authentication - authorization manager with CSV.jmx similarity index 100% rename from jmeter/src/main/resources/Basic Authentication - authorization manager with CSV.jmx rename to testing-modules/jmeter/src/main/resources/Basic Authentication - authorization manager with CSV.jmx diff --git a/jmeter/src/main/resources/Basic Authentication - authorization manager.jmx b/testing-modules/jmeter/src/main/resources/Basic Authentication - authorization manager.jmx similarity index 100% rename from jmeter/src/main/resources/Basic Authentication - authorization manager.jmx rename to testing-modules/jmeter/src/main/resources/Basic Authentication - authorization manager.jmx diff --git a/jmeter/src/main/resources/Basic Authentication.jmx b/testing-modules/jmeter/src/main/resources/Basic Authentication.jmx similarity index 100% rename from jmeter/src/main/resources/Basic Authentication.jmx rename to testing-modules/jmeter/src/main/resources/Basic Authentication.jmx diff --git a/jmeter/src/main/resources/FileExtractionExample.jmx b/testing-modules/jmeter/src/main/resources/FileExtractionExample.jmx similarity index 100% rename from jmeter/src/main/resources/FileExtractionExample.jmx rename to testing-modules/jmeter/src/main/resources/FileExtractionExample.jmx diff --git a/jmeter/src/main/resources/JMeter - Latency Vs Load Time.jmx b/testing-modules/jmeter/src/main/resources/JMeter - Latency Vs Load Time.jmx similarity index 100% rename from jmeter/src/main/resources/JMeter - Latency Vs Load Time.jmx rename to testing-modules/jmeter/src/main/resources/JMeter - Latency Vs Load Time.jmx diff --git a/jmeter/src/main/resources/JMeter.jmx b/testing-modules/jmeter/src/main/resources/JMeter.jmx similarity index 100% rename from jmeter/src/main/resources/JMeter.jmx rename to testing-modules/jmeter/src/main/resources/JMeter.jmx diff --git a/jmeter/src/main/resources/JMeter.jtl b/testing-modules/jmeter/src/main/resources/JMeter.jtl similarity index 100% rename from jmeter/src/main/resources/JMeter.jtl rename to testing-modules/jmeter/src/main/resources/JMeter.jtl diff --git a/jmeter/src/main/resources/application.properties b/testing-modules/jmeter/src/main/resources/application.properties similarity index 100% rename from jmeter/src/main/resources/application.properties rename to testing-modules/jmeter/src/main/resources/application.properties diff --git a/jmeter/src/main/resources/credentials.csv b/testing-modules/jmeter/src/main/resources/credentials.csv similarity index 100% rename from jmeter/src/main/resources/credentials.csv rename to testing-modules/jmeter/src/main/resources/credentials.csv diff --git a/jmeter/src/main/resources/dashboard/ReportsDashboard.csv b/testing-modules/jmeter/src/main/resources/dashboard/ReportsDashboard.csv similarity index 100% rename from jmeter/src/main/resources/dashboard/ReportsDashboard.csv rename to testing-modules/jmeter/src/main/resources/dashboard/ReportsDashboard.csv diff --git a/jmeter/src/main/resources/dashboard/ReportsDashboard.jmx b/testing-modules/jmeter/src/main/resources/dashboard/ReportsDashboard.jmx similarity index 100% rename from jmeter/src/main/resources/dashboard/ReportsDashboard.jmx rename to testing-modules/jmeter/src/main/resources/dashboard/ReportsDashboard.jmx diff --git a/lagom/weather-impl/src/main/resources/logback.xml b/testing-modules/jmeter/src/main/resources/logback.xml similarity index 100% rename from lagom/weather-impl/src/main/resources/logback.xml rename to testing-modules/jmeter/src/main/resources/logback.xml diff --git a/jmeter/src/main/resources/static/index.html b/testing-modules/jmeter/src/main/resources/static/index.html similarity index 100% rename from jmeter/src/main/resources/static/index.html rename to testing-modules/jmeter/src/main/resources/static/index.html diff --git a/jmeter/src/main/resources/summary-report/Summary-Report.jmx b/testing-modules/jmeter/src/main/resources/summary-report/Summary-Report.jmx similarity index 100% rename from jmeter/src/main/resources/summary-report/Summary-Report.jmx rename to testing-modules/jmeter/src/main/resources/summary-report/Summary-Report.jmx diff --git a/jmeter/src/main/resources/summary-report/Summary-Report.jtl b/testing-modules/jmeter/src/main/resources/summary-report/Summary-Report.jtl similarity index 100% rename from jmeter/src/main/resources/summary-report/Summary-Report.jtl rename to testing-modules/jmeter/src/main/resources/summary-report/Summary-Report.jtl diff --git a/jmeter/src/main/resources/templates/greeting.html b/testing-modules/jmeter/src/main/resources/templates/greeting.html similarity index 100% rename from jmeter/src/main/resources/templates/greeting.html rename to testing-modules/jmeter/src/main/resources/templates/greeting.html diff --git a/jmeter/src/main/resources/templates/quote.html b/testing-modules/jmeter/src/main/resources/templates/quote.html similarity index 100% rename from jmeter/src/main/resources/templates/quote.html rename to testing-modules/jmeter/src/main/resources/templates/quote.html diff --git a/jmeter/src/main/resources/templates/time.html b/testing-modules/jmeter/src/main/resources/templates/time.html similarity index 100% rename from jmeter/src/main/resources/templates/time.html rename to testing-modules/jmeter/src/main/resources/templates/time.html diff --git a/jmeter/src/test/java/com/baeldung/JmeterIntegrationTest.java b/testing-modules/jmeter/src/test/java/com/baeldung/JmeterIntegrationTest.java similarity index 100% rename from jmeter/src/test/java/com/baeldung/JmeterIntegrationTest.java rename to testing-modules/jmeter/src/test/java/com/baeldung/JmeterIntegrationTest.java diff --git a/jmeter/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationIntegrationTest.java b/testing-modules/jmeter/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationIntegrationTest.java similarity index 100% rename from jmeter/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationIntegrationTest.java rename to testing-modules/jmeter/src/test/java/com/baeldung/SpringJMeterJenkinsApplicationIntegrationTest.java diff --git a/testing-modules/jqwik/pom.xml b/testing-modules/jqwik/pom.xml index 6ef9b61a6a..85c4ba571a 100644 --- a/testing-modules/jqwik/pom.xml +++ b/testing-modules/jqwik/pom.xml @@ -17,7 +17,7 @@ net.jqwik jqwik - 1.7.4 + ${jqwik.version} test @@ -53,5 +53,9 @@ + + 1.7.4 + + diff --git a/testing-modules/junit-5-advanced/pom.xml b/testing-modules/junit-5-advanced/pom.xml index 411f189638..fc0349ff8e 100644 --- a/testing-modules/junit-5-advanced/pom.xml +++ b/testing-modules/junit-5-advanced/pom.xml @@ -18,7 +18,7 @@ com.github.stefanbirkner system-lambda - 1.2.1 + ${system-lambda.version} test @@ -79,6 +79,7 @@ + 1.2.1 1.49 3.24.2 1.10.1 diff --git a/testing-modules/junit-5-basics-2/pom.xml b/testing-modules/junit-5-basics-2/pom.xml index b430161380..f03b74f47a 100644 --- a/testing-modules/junit-5-basics-2/pom.xml +++ b/testing-modules/junit-5-basics-2/pom.xml @@ -36,18 +36,11 @@ org.apache.maven.plugins maven-compiler-plugin - - 11 - 11 - - 11 - 11 - UTF-8 1.5.0 5.10.0 5.5.0 diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml index 8afaa085b1..cdddf90855 100644 --- a/testing-modules/junit-5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -107,7 +107,6 @@ org.codehaus.mojo exec-maven-plugin - ${exec-maven-plugin.version} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/failurethreshold/FailureThresholdUnitTest.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/failurethreshold/FailureThresholdUnitTest.java new file mode 100644 index 0000000000..de7651ece6 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/failurethreshold/FailureThresholdUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.junit5.failurethreshold; + +import org.junit.jupiter.api.RepeatedTest; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +class FailureThresholdUnitTest { + Random random = new Random(); + + @RepeatedTest(value = 10, failureThreshold = 2) + void givenRandomNumberGenerator_whenGeneratingRandomNumber_thenNumberShouldBeWithinRange() { + int number = random.nextInt(10); + assertTrue(number <= 9); + } +} diff --git a/testing-modules/load-testing-comparison/pom.xml b/testing-modules/load-testing-comparison/pom.xml index d5a389d311..af42523ca9 100644 --- a/testing-modules/load-testing-comparison/pom.xml +++ b/testing-modules/load-testing-comparison/pom.xml @@ -66,9 +66,6 @@ - 1.8 - 1.8 - UTF-8 2.12.12 3.4.0 4.4.0 diff --git a/testing-modules/mockito-2/README.md b/testing-modules/mockito-2/README.md index da8f339e56..5eb4395fa9 100644 --- a/testing-modules/mockito-2/README.md +++ b/testing-modules/mockito-2/README.md @@ -9,3 +9,4 @@ This module contains articles about Mockito - [Mock Same Method with Different Parameters](https://www.baeldung.com/java-mock-same-method-other-parameters) - [How to Mock Constructors for Unit Testing using Mockito](https://www.baeldung.com/java-mockito-constructors-unit-testing) - [Overview of Mockito MockedConstruction](https://www.baeldung.com/java-mockito-mockedconstruction) +- [Verify That Lambda Expression Was Called Using Mockito](https://www.baeldung.com/java-mockito-verify-lambda-expression) diff --git a/testing-modules/mockito-2/pom.xml b/testing-modules/mockito-2/pom.xml index 0e0f19b6b3..100c9d7015 100644 --- a/testing-modules/mockito-2/pom.xml +++ b/testing-modules/mockito-2/pom.xml @@ -21,9 +21,6 @@ - 8 - 8 - UTF-8 4.8.1 diff --git a/testing-modules/mockito-simple/pom.xml b/testing-modules/mockito-simple/pom.xml index 30928cfe35..6f50136de6 100644 --- a/testing-modules/mockito-simple/pom.xml +++ b/testing-modules/mockito-simple/pom.xml @@ -8,9 +8,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + testing-modules + 1.0.0-SNAPSHOT @@ -35,6 +34,11 @@ commons-lang3 ${commons-lang3.version} + + com.google.guava + guava + ${guava.version} + org.mockito diff --git a/testing-modules/parallel-tests-junit/pom.xml b/testing-modules/parallel-tests-junit/pom.xml index b45faf039e..5a038c74b7 100644 --- a/testing-modules/parallel-tests-junit/pom.xml +++ b/testing-modules/parallel-tests-junit/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + testing-modules + 1.0.0-SNAPSHOT diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index 103bcd67f3..8246dae7db 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -23,6 +23,7 @@ groovy-spock hamcrest instancio + jmeter jqwik junit-4 junit-5-advanced diff --git a/testing-modules/rest-testing/pom.xml b/testing-modules/rest-testing/pom.xml index 975b6fb647..b9790287a3 100644 --- a/testing-modules/rest-testing/pom.xml +++ b/testing-modules/rest-testing/pom.xml @@ -9,9 +9,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + testing-modules + 1.0.0-SNAPSHOT diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index 1da53bd77e..52961a1744 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -7,9 +7,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../../parent-java + testing-modules + 1.0.0-SNAPSHOT diff --git a/text-processing-libraries-modules/README.md b/text-processing-libraries-modules/README.md new file mode 100644 index 0000000000..1b21f540a3 --- /dev/null +++ b/text-processing-libraries-modules/README.md @@ -0,0 +1,3 @@ +## Text Processing Libraries + +This module contains modules about Text Processing Libraries. \ No newline at end of file diff --git a/antlr/README.md b/text-processing-libraries-modules/antlr/README.md similarity index 100% rename from antlr/README.md rename to text-processing-libraries-modules/antlr/README.md diff --git a/antlr/pom.xml b/text-processing-libraries-modules/antlr/pom.xml similarity index 96% rename from antlr/pom.xml rename to text-processing-libraries-modules/antlr/pom.xml index f9d6fb1a08..a7cf39eb44 100644 --- a/antlr/pom.xml +++ b/text-processing-libraries-modules/antlr/pom.xml @@ -8,7 +8,7 @@ com.baeldung - parent-modules + text-processing-libraries-modules 1.0.0-SNAPSHOT diff --git a/antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4 b/text-processing-libraries-modules/antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4 similarity index 100% rename from antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4 rename to text-processing-libraries-modules/antlr/src/main/antlr4/com/baeldung/antlr/Java8.g4 diff --git a/antlr/src/main/antlr4/com/baeldung/antlr/Log.g4 b/text-processing-libraries-modules/antlr/src/main/antlr4/com/baeldung/antlr/Log.g4 similarity index 100% rename from antlr/src/main/antlr4/com/baeldung/antlr/Log.g4 rename to text-processing-libraries-modules/antlr/src/main/antlr4/com/baeldung/antlr/Log.g4 diff --git a/antlr/src/main/java/com/baeldung/antlr/java/UppercaseMethodListener.java b/text-processing-libraries-modules/antlr/src/main/java/com/baeldung/antlr/java/UppercaseMethodListener.java similarity index 100% rename from antlr/src/main/java/com/baeldung/antlr/java/UppercaseMethodListener.java rename to text-processing-libraries-modules/antlr/src/main/java/com/baeldung/antlr/java/UppercaseMethodListener.java diff --git a/antlr/src/main/java/com/baeldung/antlr/log/LogListener.java b/text-processing-libraries-modules/antlr/src/main/java/com/baeldung/antlr/log/LogListener.java similarity index 100% rename from antlr/src/main/java/com/baeldung/antlr/log/LogListener.java rename to text-processing-libraries-modules/antlr/src/main/java/com/baeldung/antlr/log/LogListener.java diff --git a/antlr/src/main/java/com/baeldung/antlr/log/model/LogEntry.java b/text-processing-libraries-modules/antlr/src/main/java/com/baeldung/antlr/log/model/LogEntry.java similarity index 100% rename from antlr/src/main/java/com/baeldung/antlr/log/model/LogEntry.java rename to text-processing-libraries-modules/antlr/src/main/java/com/baeldung/antlr/log/model/LogEntry.java diff --git a/antlr/src/main/java/com/baeldung/antlr/log/model/LogLevel.java b/text-processing-libraries-modules/antlr/src/main/java/com/baeldung/antlr/log/model/LogLevel.java similarity index 100% rename from antlr/src/main/java/com/baeldung/antlr/log/model/LogLevel.java rename to text-processing-libraries-modules/antlr/src/main/java/com/baeldung/antlr/log/model/LogLevel.java diff --git a/pdf/src/main/resources/logback.xml b/text-processing-libraries-modules/antlr/src/main/resources/logback.xml similarity index 100% rename from pdf/src/main/resources/logback.xml rename to text-processing-libraries-modules/antlr/src/main/resources/logback.xml diff --git a/antlr/src/test/java/com/baeldung/antlr/JavaParserUnitTest.java b/text-processing-libraries-modules/antlr/src/test/java/com/baeldung/antlr/JavaParserUnitTest.java similarity index 100% rename from antlr/src/test/java/com/baeldung/antlr/JavaParserUnitTest.java rename to text-processing-libraries-modules/antlr/src/test/java/com/baeldung/antlr/JavaParserUnitTest.java diff --git a/antlr/src/test/java/com/baeldung/antlr/LogParserUnitTest.java b/text-processing-libraries-modules/antlr/src/test/java/com/baeldung/antlr/LogParserUnitTest.java similarity index 100% rename from antlr/src/test/java/com/baeldung/antlr/LogParserUnitTest.java rename to text-processing-libraries-modules/antlr/src/test/java/com/baeldung/antlr/LogParserUnitTest.java diff --git a/apache-tika/README.md b/text-processing-libraries-modules/apache-tika/README.md similarity index 100% rename from apache-tika/README.md rename to text-processing-libraries-modules/apache-tika/README.md diff --git a/apache-tika/pom.xml b/text-processing-libraries-modules/apache-tika/pom.xml similarity index 92% rename from apache-tika/pom.xml rename to text-processing-libraries-modules/apache-tika/pom.xml index 896b88ec4b..f48fe34e25 100644 --- a/apache-tika/pom.xml +++ b/text-processing-libraries-modules/apache-tika/pom.xml @@ -9,7 +9,7 @@ com.baeldung - parent-modules + text-processing-libraries-modules 1.0.0-SNAPSHOT diff --git a/apache-tika/src/main/java/com/baeldung/tika/TikaAnalysis.java b/text-processing-libraries-modules/apache-tika/src/main/java/com/baeldung/tika/TikaAnalysis.java similarity index 100% rename from apache-tika/src/main/java/com/baeldung/tika/TikaAnalysis.java rename to text-processing-libraries-modules/apache-tika/src/main/java/com/baeldung/tika/TikaAnalysis.java diff --git a/text-processing-libraries-modules/apache-tika/src/main/resources/logback.xml b/text-processing-libraries-modules/apache-tika/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/text-processing-libraries-modules/apache-tika/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java b/text-processing-libraries-modules/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java similarity index 100% rename from apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java rename to text-processing-libraries-modules/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java diff --git a/apache-tika/src/test/resources/tika.docx b/text-processing-libraries-modules/apache-tika/src/test/resources/tika.docx similarity index 100% rename from apache-tika/src/test/resources/tika.docx rename to text-processing-libraries-modules/apache-tika/src/test/resources/tika.docx diff --git a/apache-tika/src/test/resources/tika.txt b/text-processing-libraries-modules/apache-tika/src/test/resources/tika.txt similarity index 100% rename from apache-tika/src/test/resources/tika.txt rename to text-processing-libraries-modules/apache-tika/src/test/resources/tika.txt diff --git a/apache-tika/src/test/resources/tika.xlsx b/text-processing-libraries-modules/apache-tika/src/test/resources/tika.xlsx similarity index 100% rename from apache-tika/src/test/resources/tika.xlsx rename to text-processing-libraries-modules/apache-tika/src/test/resources/tika.xlsx diff --git a/asciidoctor/README.md b/text-processing-libraries-modules/asciidoctor/README.md similarity index 100% rename from asciidoctor/README.md rename to text-processing-libraries-modules/asciidoctor/README.md diff --git a/asciidoctor/log4j.properties b/text-processing-libraries-modules/asciidoctor/log4j.properties similarity index 100% rename from asciidoctor/log4j.properties rename to text-processing-libraries-modules/asciidoctor/log4j.properties diff --git a/asciidoctor/pom.xml b/text-processing-libraries-modules/asciidoctor/pom.xml similarity index 97% rename from asciidoctor/pom.xml rename to text-processing-libraries-modules/asciidoctor/pom.xml index b72f050379..2ebe9d2f0d 100644 --- a/asciidoctor/pom.xml +++ b/text-processing-libraries-modules/asciidoctor/pom.xml @@ -8,7 +8,7 @@ com.baeldung - parent-modules + text-processing-libraries-modules 1.0.0-SNAPSHOT diff --git a/asciidoctor/src/docs/asciidoc/test.adoc b/text-processing-libraries-modules/asciidoctor/src/docs/asciidoc/test.adoc similarity index 100% rename from asciidoctor/src/docs/asciidoc/test.adoc rename to text-processing-libraries-modules/asciidoctor/src/docs/asciidoc/test.adoc diff --git a/asciidoctor/src/main/java/com/baeldung/asciidoctor/AsciidoctorDemo.java b/text-processing-libraries-modules/asciidoctor/src/main/java/com/baeldung/asciidoctor/AsciidoctorDemo.java similarity index 100% rename from asciidoctor/src/main/java/com/baeldung/asciidoctor/AsciidoctorDemo.java rename to text-processing-libraries-modules/asciidoctor/src/main/java/com/baeldung/asciidoctor/AsciidoctorDemo.java diff --git a/text-processing-libraries-modules/asciidoctor/src/main/resources/logback.xml b/text-processing-libraries-modules/asciidoctor/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/text-processing-libraries-modules/asciidoctor/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java b/text-processing-libraries-modules/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java similarity index 100% rename from asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java rename to text-processing-libraries-modules/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java diff --git a/asciidoctor/src/themes/custom-theme.yml b/text-processing-libraries-modules/asciidoctor/src/themes/custom-theme.yml similarity index 100% rename from asciidoctor/src/themes/custom-theme.yml rename to text-processing-libraries-modules/asciidoctor/src/themes/custom-theme.yml diff --git a/pdf-2/README.md b/text-processing-libraries-modules/pdf-2/README.md similarity index 100% rename from pdf-2/README.md rename to text-processing-libraries-modules/pdf-2/README.md diff --git a/pdf-2/pom.xml b/text-processing-libraries-modules/pdf-2/pom.xml similarity index 69% rename from pdf-2/pom.xml rename to text-processing-libraries-modules/pdf-2/pom.xml index 2079ff70e5..9058e5e634 100644 --- a/pdf-2/pom.xml +++ b/text-processing-libraries-modules/pdf-2/pom.xml @@ -9,7 +9,7 @@ com.baeldung - parent-modules + text-processing-libraries-modules 1.0.0-SNAPSHOT @@ -35,6 +35,21 @@ pdfbox ${pdfbox.version} + + org.apache.poi + poi-ooxml + ${poi-ooxml.version} + + + org.apache.logging.log4j + log4j-api + ${log4j-api.version} + + + org.apache.logging.log4j + log4j-core + ${log4j-core.version} + @@ -52,6 +67,9 @@ 7.2.3 3.0.1 3.0.0 + 5.2.5 + 2.20.0 + 2.20.0 \ No newline at end of file diff --git a/text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/exceltopdf/ExcelToPDFConverter.java b/text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/exceltopdf/ExcelToPDFConverter.java new file mode 100644 index 0000000000..97d7b36bd6 --- /dev/null +++ b/text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/exceltopdf/ExcelToPDFConverter.java @@ -0,0 +1,242 @@ +package com.baeldung.exceltopdf; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Iterator; + +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.HorizontalAlignment; +import org.apache.poi.ss.usermodel.IndexedColors; +import org.apache.poi.ss.usermodel.VerticalAlignment; +import org.apache.poi.xssf.usermodel.XSSFColor; +import org.apache.poi.xssf.usermodel.XSSFFont; +import org.apache.poi.xssf.usermodel.XSSFSheet; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.apache.poi.ss.usermodel.CellType; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Cell; + +import com.itextpdf.text.BaseColor; +import com.itextpdf.text.Document; +import com.itextpdf.text.DocumentException; +import com.itextpdf.text.Element; +import com.itextpdf.text.Font; +import com.itextpdf.text.FontFactory; +import com.itextpdf.text.Paragraph; +import com.itextpdf.text.Phrase; +import com.itextpdf.text.pdf.PdfPCell; +import com.itextpdf.text.pdf.PdfPTable; +import com.itextpdf.text.pdf.PdfWriter; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +public class ExcelToPDFConverter { + + private static final Logger logger = LogManager.getLogger(ExcelToPDFConverter.class); + + public static XSSFWorkbook readExcelFile(String excelFilePath) throws IOException { + FileInputStream inputStream = new FileInputStream(excelFilePath); + XSSFWorkbook workbook = new XSSFWorkbook(inputStream); + inputStream.close(); + return workbook; + } + + private static Document createPDFDocument(String pdfFilePath) throws IOException, DocumentException { + Document document = new Document(); + PdfWriter.getInstance(document, new FileOutputStream(pdfFilePath)); + document.open(); + return document; + } + + public static void convertExcelToPDF(String excelFilePath, String pdfFilePath) throws IOException, DocumentException { + XSSFWorkbook workbook = readExcelFile(excelFilePath); + Document document = createPDFDocument(pdfFilePath); + + for (int i = 0; i < workbook.getNumberOfSheets(); i++) { + XSSFSheet worksheet = workbook.getSheetAt(i); + + // Add header with sheet name as title + Paragraph title = new Paragraph(worksheet.getSheetName(), new Font(Font.FontFamily.HELVETICA, 18, Font.BOLD)); + title.setSpacingAfter(20f); + title.setAlignment(Element.ALIGN_CENTER); + document.add(title); + + createAndAddTable(worksheet, document); + // Add a new page for each sheet (except the last one) + if (i < workbook.getNumberOfSheets() - 1) { + document.newPage(); + } + } + + document.close(); + workbook.close(); + } + + private static void createAndAddTable(XSSFSheet worksheet, Document document) throws DocumentException, IOException { + PdfPTable table = new PdfPTable(worksheet.getRow(0) + .getPhysicalNumberOfCells()); + table.setWidthPercentage(100); + addTableHeader(worksheet, table); + addTableData(worksheet, table); + document.add(table); + } + + private static void addTableHeader(XSSFSheet worksheet, PdfPTable table) throws DocumentException, IOException { + Row headerRow = worksheet.getRow(0); + for (int i = 0; i < headerRow.getPhysicalNumberOfCells(); i++) { + Cell cell = headerRow.getCell(i); + String headerText = getCellText(cell); + PdfPCell headerCell = new PdfPCell(new Phrase(headerText, getCellStyle(cell))); + setBackgroundColor(cell, headerCell); + setCellAlignment(cell, headerCell); + table.addCell(headerCell); + } + } + + public static String getCellText(Cell cell) { + String cellValue; + switch (cell.getCellType()) { + case STRING: + cellValue = cell.getStringCellValue(); + break; + case NUMERIC: + cellValue = String.valueOf(BigDecimal.valueOf(cell.getNumericCellValue())); + break; + case BLANK: + default: + cellValue = ""; + break; + } + return cellValue; + } + + private static void addTableData(XSSFSheet worksheet, PdfPTable table) throws DocumentException, IOException { + Iterator rowIterator = worksheet.iterator(); + while (rowIterator.hasNext()) { + Row row = rowIterator.next(); + if (row.getRowNum() == 0) { + continue; + } + for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) { + Cell cell = row.getCell(i); + String cellValue = getCellText(cell); + PdfPCell cellPdf = new PdfPCell(new Phrase(cellValue, getCellStyle(cell))); + setBackgroundColor(cell, cellPdf); + setCellAlignment(cell, cellPdf); + table.addCell(cellPdf); + } + } + } + + private static void setBackgroundColor(Cell cell, PdfPCell cellPdf) { + // Set background color + short bgColorIndex = cell.getCellStyle() + .getFillForegroundColor(); + if (bgColorIndex != IndexedColors.AUTOMATIC.getIndex()) { + XSSFColor bgColor = (XSSFColor) cell.getCellStyle() + .getFillForegroundColorColor(); + if (bgColor != null) { + byte[] rgb = bgColor.getRGB(); + if (rgb != null && rgb.length == 3) { + cellPdf.setBackgroundColor(new BaseColor(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF)); + } + } + } + } + + private static void setCellAlignment(Cell cell, PdfPCell cellPdf) { + CellStyle cellStyle = cell.getCellStyle(); + + HorizontalAlignment horizontalAlignment = cellStyle.getAlignment(); + VerticalAlignment verticalAlignment = cellStyle.getVerticalAlignment(); + + switch (horizontalAlignment) { + case LEFT: + cellPdf.setHorizontalAlignment(Element.ALIGN_LEFT); + break; + case CENTER: + cellPdf.setHorizontalAlignment(Element.ALIGN_CENTER); + break; + case JUSTIFY: + case FILL: + cellPdf.setVerticalAlignment(Element.ALIGN_JUSTIFIED); + break; + case RIGHT: + cellPdf.setHorizontalAlignment(Element.ALIGN_RIGHT); + break; + } + + switch (verticalAlignment) { + case TOP: + cellPdf.setVerticalAlignment(Element.ALIGN_TOP); + break; + case CENTER: + cellPdf.setVerticalAlignment(Element.ALIGN_MIDDLE); + break; + case JUSTIFY: + cellPdf.setVerticalAlignment(Element.ALIGN_JUSTIFIED); + break; + case BOTTOM: + cellPdf.setVerticalAlignment(Element.ALIGN_BOTTOM); + break; + } + } + + private static Font getCellStyle(Cell cell) throws DocumentException, IOException { + Font font = new Font(); + CellStyle cellStyle = cell.getCellStyle(); + org.apache.poi.ss.usermodel.Font cellFont = cell.getSheet() + .getWorkbook() + .getFontAt(cellStyle.getFontIndexAsInt()); + + short fontColorIndex = cellFont.getColor(); + if (fontColorIndex != IndexedColors.AUTOMATIC.getIndex() && cellFont instanceof XSSFFont) { + XSSFColor fontColor = ((XSSFFont) cellFont).getXSSFColor(); + if (fontColor != null) { + byte[] rgb = fontColor.getRGB(); + if (rgb != null && rgb.length == 3) { + font.setColor(new BaseColor(rgb[0] & 0xFF, rgb[1] & 0xFF, rgb[2] & 0xFF)); + } + } + } + + if (cellFont.getItalic()) { + font.setStyle(Font.ITALIC); + } + + if (cellFont.getStrikeout()) { + font.setStyle(Font.STRIKETHRU); + } + + if (cellFont.getUnderline() == 1) { + font.setStyle(Font.UNDERLINE); + } + + short fontSize = cellFont.getFontHeightInPoints(); + font.setSize(fontSize); + + if (cellFont.getBold()) { + font.setStyle(Font.BOLD); + } + + String fontName = cellFont.getFontName(); + if (FontFactory.isRegistered(fontName)) { + font.setFamily(fontName); // Use extracted font family if supported by iText + } else { + logger.warn("Unsupported font type: {}", fontName); + // - Use a fallback font (e.g., Helvetica) + font.setFamily("Helvetica"); + } + + return font; + } + + public static void main(String[] args) throws DocumentException, IOException { + String excelFilePath = "src/main/resources/excelsample.xlsx"; + String pdfFilePath = "src/main/resources/pdfsample.pdf"; + convertExcelToPDF(excelFilePath, pdfFilePath); + } +} diff --git a/pdf-2/src/main/java/com/baeldung/pdfedition/PdfContentRemover.java b/text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfedition/PdfContentRemover.java similarity index 97% rename from pdf-2/src/main/java/com/baeldung/pdfedition/PdfContentRemover.java rename to text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfedition/PdfContentRemover.java index 62ccdcb51f..36fc498b6b 100644 --- a/pdf-2/src/main/java/com/baeldung/pdfedition/PdfContentRemover.java +++ b/text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfedition/PdfContentRemover.java @@ -1,43 +1,43 @@ -package com.baeldung.pdfedition; - -import java.io.IOException; -import java.util.Arrays; -import java.util.List; - -import com.itextpdf.kernel.geom.Rectangle; -import com.itextpdf.kernel.pdf.PdfDocument; -import com.itextpdf.kernel.pdf.PdfReader; -import com.itextpdf.kernel.pdf.PdfWriter; -import com.itextpdf.pdfcleanup.CleanUpProperties; -import com.itextpdf.pdfcleanup.PdfCleanUpLocation; -import com.itextpdf.pdfcleanup.PdfCleanUpTool; -import com.itextpdf.pdfcleanup.PdfCleaner; -import com.itextpdf.pdfcleanup.autosweep.CompositeCleanupStrategy; -import com.itextpdf.pdfcleanup.autosweep.RegexBasedCleanupStrategy; - -public class PdfContentRemover { - - private static final String SOURCE = "src/main/resources/baeldung-modified.pdf"; - private static final String DESTINATION = "src/main/resources/baeldung-cleaned.pdf"; - - public static void main(String[] args) throws IOException { - PdfReader reader = new PdfReader(SOURCE); - PdfWriter writer = new PdfWriter(DESTINATION); - PdfDocument pdfDocument = new PdfDocument(reader, writer); - removeContentFromDocument(pdfDocument); - pdfDocument.close(); - } - - private static void removeContentFromDocument(PdfDocument pdfDocument) throws IOException { - // 5.1. remove text - CompositeCleanupStrategy strategy = new CompositeCleanupStrategy(); - strategy.add(new RegexBasedCleanupStrategy("Baeldung")); - PdfCleaner.autoSweepCleanUp(pdfDocument, strategy); - - // 5.2. remove other areas - List cleanUpLocations = Arrays.asList(new PdfCleanUpLocation(1, new Rectangle(10, 50, 90, 70)), new PdfCleanUpLocation(2, new Rectangle(35, 400, 100, 35))); - PdfCleanUpTool cleaner = new PdfCleanUpTool(pdfDocument, cleanUpLocations, new CleanUpProperties()); - cleaner.cleanUp(); - } - -} +package com.baeldung.pdfedition; + +import java.io.IOException; +import java.util.Arrays; +import java.util.List; + +import com.itextpdf.kernel.geom.Rectangle; +import com.itextpdf.kernel.pdf.PdfDocument; +import com.itextpdf.kernel.pdf.PdfReader; +import com.itextpdf.kernel.pdf.PdfWriter; +import com.itextpdf.pdfcleanup.CleanUpProperties; +import com.itextpdf.pdfcleanup.PdfCleanUpLocation; +import com.itextpdf.pdfcleanup.PdfCleanUpTool; +import com.itextpdf.pdfcleanup.PdfCleaner; +import com.itextpdf.pdfcleanup.autosweep.CompositeCleanupStrategy; +import com.itextpdf.pdfcleanup.autosweep.RegexBasedCleanupStrategy; + +public class PdfContentRemover { + + private static final String SOURCE = "src/main/resources/baeldung-modified.pdf"; + private static final String DESTINATION = "src/main/resources/baeldung-cleaned.pdf"; + + public static void main(String[] args) throws IOException { + PdfReader reader = new PdfReader(SOURCE); + PdfWriter writer = new PdfWriter(DESTINATION); + PdfDocument pdfDocument = new PdfDocument(reader, writer); + removeContentFromDocument(pdfDocument); + pdfDocument.close(); + } + + private static void removeContentFromDocument(PdfDocument pdfDocument) throws IOException { + // 5.1. remove text + CompositeCleanupStrategy strategy = new CompositeCleanupStrategy(); + strategy.add(new RegexBasedCleanupStrategy("Baeldung")); + PdfCleaner.autoSweepCleanUp(pdfDocument, strategy); + + // 5.2. remove other areas + List cleanUpLocations = Arrays.asList(new PdfCleanUpLocation(1, new Rectangle(10, 50, 90, 70)), new PdfCleanUpLocation(2, new Rectangle(35, 400, 100, 35))); + PdfCleanUpTool cleaner = new PdfCleanUpTool(pdfDocument, cleanUpLocations, new CleanUpProperties()); + cleaner.cleanUp(); + } + +} diff --git a/pdf-2/src/main/java/com/baeldung/pdfedition/PdfEditor.java b/text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfedition/PdfEditor.java similarity index 97% rename from pdf-2/src/main/java/com/baeldung/pdfedition/PdfEditor.java rename to text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfedition/PdfEditor.java index cfdf5917b8..94bf6ae0d6 100644 --- a/pdf-2/src/main/java/com/baeldung/pdfedition/PdfEditor.java +++ b/text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfedition/PdfEditor.java @@ -1,86 +1,86 @@ -package com.baeldung.pdfedition; - -import java.io.IOException; -import java.net.MalformedURLException; - -import com.itextpdf.forms.PdfAcroForm; -import com.itextpdf.forms.fields.PdfFormField; -import com.itextpdf.forms.fields.PdfTextFormField; -import com.itextpdf.io.image.ImageData; -import com.itextpdf.io.image.ImageDataFactory; -import com.itextpdf.kernel.geom.Rectangle; -import com.itextpdf.kernel.pdf.PdfDocument; -import com.itextpdf.kernel.pdf.PdfReader; -import com.itextpdf.kernel.pdf.PdfString; -import com.itextpdf.kernel.pdf.PdfWriter; -import com.itextpdf.kernel.pdf.annot.PdfAnnotation; -import com.itextpdf.kernel.pdf.annot.PdfTextAnnotation; -import com.itextpdf.layout.Document; -import com.itextpdf.layout.element.Image; -import com.itextpdf.layout.element.Paragraph; -import com.itextpdf.layout.element.Table; -import com.itextpdf.layout.element.Text; -import com.itextpdf.layout.properties.UnitValue; - -public class PdfEditor { - - private static final String SOURCE = "src/main/resources/baeldung.pdf"; - private static final String DESTINATION = "src/main/resources/baeldung-modified.pdf"; - - public static void main(String[] args) throws IOException { - PdfReader reader = new PdfReader(SOURCE); - PdfWriter writer = new PdfWriter(DESTINATION); - PdfDocument pdfDocument = new PdfDocument(reader, writer); - addContentToDocument(pdfDocument); - } - - private static void addContentToDocument(PdfDocument pdfDocument) throws MalformedURLException { - // 4.1. add form - PdfFormField personal = PdfFormField.createEmptyField(pdfDocument); - personal.setFieldName("information"); - PdfTextFormField name = PdfFormField.createText(pdfDocument, new Rectangle(35, 400, 100, 30), "name", ""); - personal.addKid(name); - PdfAcroForm.getAcroForm(pdfDocument, true) - .addField(personal, pdfDocument.getFirstPage()); - - // 4.2. add new page - pdfDocument.addNewPage(1); - - // 4.3. add annotation - PdfAnnotation ann = new PdfTextAnnotation(new Rectangle(40, 435, 0, 0)).setTitle(new PdfString("name")) - .setContents("Your name"); - pdfDocument.getPage(2) - .addAnnotation(ann); - - // create document form pdf document - Document document = new Document(pdfDocument); - - // 4.4. add an image - ImageData imageData = ImageDataFactory.create("src/main/resources/baeldung.png"); - Image image = new Image(imageData).scaleAbsolute(550, 100) - .setFixedPosition(1, 10, 50); - document.add(image); - - // 4.5. add a paragraph - Text title = new Text("This is a demo").setFontSize(16); - Text author = new Text("Baeldung tutorials."); - Paragraph p = new Paragraph().setFontSize(8) - .add(title) - .add(" from ") - .add(author); - document.add(p); - - // 4.6. add a table - Table table = new Table(UnitValue.createPercentArray(2)); - table.addHeaderCell("#"); - table.addHeaderCell("company"); - table.addCell("name"); - table.addCell("baeldung"); - document.add(table); - - // close the document - // this automatically closes the pdfDocument, which then closes automatically the pdfReader and pdfWriter - document.close(); - } - -} +package com.baeldung.pdfedition; + +import java.io.IOException; +import java.net.MalformedURLException; + +import com.itextpdf.forms.PdfAcroForm; +import com.itextpdf.forms.fields.PdfFormField; +import com.itextpdf.forms.fields.PdfTextFormField; +import com.itextpdf.io.image.ImageData; +import com.itextpdf.io.image.ImageDataFactory; +import com.itextpdf.kernel.geom.Rectangle; +import com.itextpdf.kernel.pdf.PdfDocument; +import com.itextpdf.kernel.pdf.PdfReader; +import com.itextpdf.kernel.pdf.PdfString; +import com.itextpdf.kernel.pdf.PdfWriter; +import com.itextpdf.kernel.pdf.annot.PdfAnnotation; +import com.itextpdf.kernel.pdf.annot.PdfTextAnnotation; +import com.itextpdf.layout.Document; +import com.itextpdf.layout.element.Image; +import com.itextpdf.layout.element.Paragraph; +import com.itextpdf.layout.element.Table; +import com.itextpdf.layout.element.Text; +import com.itextpdf.layout.properties.UnitValue; + +public class PdfEditor { + + private static final String SOURCE = "src/main/resources/baeldung.pdf"; + private static final String DESTINATION = "src/main/resources/baeldung-modified.pdf"; + + public static void main(String[] args) throws IOException { + PdfReader reader = new PdfReader(SOURCE); + PdfWriter writer = new PdfWriter(DESTINATION); + PdfDocument pdfDocument = new PdfDocument(reader, writer); + addContentToDocument(pdfDocument); + } + + private static void addContentToDocument(PdfDocument pdfDocument) throws MalformedURLException { + // 4.1. add form + PdfFormField personal = PdfFormField.createEmptyField(pdfDocument); + personal.setFieldName("information"); + PdfTextFormField name = PdfFormField.createText(pdfDocument, new Rectangle(35, 400, 100, 30), "name", ""); + personal.addKid(name); + PdfAcroForm.getAcroForm(pdfDocument, true) + .addField(personal, pdfDocument.getFirstPage()); + + // 4.2. add new page + pdfDocument.addNewPage(1); + + // 4.3. add annotation + PdfAnnotation ann = new PdfTextAnnotation(new Rectangle(40, 435, 0, 0)).setTitle(new PdfString("name")) + .setContents("Your name"); + pdfDocument.getPage(2) + .addAnnotation(ann); + + // create document form pdf document + Document document = new Document(pdfDocument); + + // 4.4. add an image + ImageData imageData = ImageDataFactory.create("src/main/resources/baeldung.png"); + Image image = new Image(imageData).scaleAbsolute(550, 100) + .setFixedPosition(1, 10, 50); + document.add(image); + + // 4.5. add a paragraph + Text title = new Text("This is a demo").setFontSize(16); + Text author = new Text("Baeldung tutorials."); + Paragraph p = new Paragraph().setFontSize(8) + .add(title) + .add(" from ") + .add(author); + document.add(p); + + // 4.6. add a table + Table table = new Table(UnitValue.createPercentArray(2)); + table.addHeaderCell("#"); + table.addHeaderCell("company"); + table.addCell("name"); + table.addCell("baeldung"); + document.add(table); + + // close the document + // this automatically closes the pdfDocument, which then closes automatically the pdfReader and pdfWriter + document.close(); + } + +} diff --git a/pdf-2/src/main/java/com/baeldung/pdfedition/PdfTextReplacement.java b/text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfedition/PdfTextReplacement.java similarity index 97% rename from pdf-2/src/main/java/com/baeldung/pdfedition/PdfTextReplacement.java rename to text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfedition/PdfTextReplacement.java index e81adff1ec..a1ca449134 100644 --- a/pdf-2/src/main/java/com/baeldung/pdfedition/PdfTextReplacement.java +++ b/text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfedition/PdfTextReplacement.java @@ -1,45 +1,45 @@ -package com.baeldung.pdfedition; - -import java.io.IOException; - -import com.itextpdf.kernel.colors.ColorConstants; -import com.itextpdf.kernel.pdf.PdfDocument; -import com.itextpdf.kernel.pdf.PdfPage; -import com.itextpdf.kernel.pdf.PdfReader; -import com.itextpdf.kernel.pdf.PdfWriter; -import com.itextpdf.kernel.pdf.canvas.PdfCanvas; -import com.itextpdf.kernel.pdf.canvas.parser.listener.IPdfTextLocation; -import com.itextpdf.layout.Canvas; -import com.itextpdf.layout.element.Paragraph; -import com.itextpdf.pdfcleanup.PdfCleaner; -import com.itextpdf.pdfcleanup.autosweep.CompositeCleanupStrategy; -import com.itextpdf.pdfcleanup.autosweep.RegexBasedCleanupStrategy; - -public class PdfTextReplacement { - - private static final String SOURCE = "src/main/resources/baeldung-modified.pdf"; - private static final String DESTINATION = "src/main/resources/baeldung-fixed.pdf"; - - public static void main(String[] args) throws IOException { - PdfReader reader = new PdfReader(SOURCE); - PdfWriter writer = new PdfWriter(DESTINATION); - PdfDocument pdfDocument = new PdfDocument(reader, writer); - replaceTextContentFromDocument(pdfDocument); - pdfDocument.close(); - } - - private static void replaceTextContentFromDocument(PdfDocument pdfDocument) throws IOException { - CompositeCleanupStrategy strategy = new CompositeCleanupStrategy(); - strategy.add(new RegexBasedCleanupStrategy("Baeldung tutorials").setRedactionColor(ColorConstants.WHITE)); - PdfCleaner.autoSweepCleanUp(pdfDocument, strategy); - - for (IPdfTextLocation location : strategy.getResultantLocations()) { - PdfPage page = pdfDocument.getPage(location.getPageNumber() + 1); - PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), page.getDocument()); - Canvas canvas = new Canvas(pdfCanvas, location.getRectangle()); - canvas.add(new Paragraph("HIDDEN").setFontSize(8) - .setMarginTop(0f)); - } - } - -} +package com.baeldung.pdfedition; + +import java.io.IOException; + +import com.itextpdf.kernel.colors.ColorConstants; +import com.itextpdf.kernel.pdf.PdfDocument; +import com.itextpdf.kernel.pdf.PdfPage; +import com.itextpdf.kernel.pdf.PdfReader; +import com.itextpdf.kernel.pdf.PdfWriter; +import com.itextpdf.kernel.pdf.canvas.PdfCanvas; +import com.itextpdf.kernel.pdf.canvas.parser.listener.IPdfTextLocation; +import com.itextpdf.layout.Canvas; +import com.itextpdf.layout.element.Paragraph; +import com.itextpdf.pdfcleanup.PdfCleaner; +import com.itextpdf.pdfcleanup.autosweep.CompositeCleanupStrategy; +import com.itextpdf.pdfcleanup.autosweep.RegexBasedCleanupStrategy; + +public class PdfTextReplacement { + + private static final String SOURCE = "src/main/resources/baeldung-modified.pdf"; + private static final String DESTINATION = "src/main/resources/baeldung-fixed.pdf"; + + public static void main(String[] args) throws IOException { + PdfReader reader = new PdfReader(SOURCE); + PdfWriter writer = new PdfWriter(DESTINATION); + PdfDocument pdfDocument = new PdfDocument(reader, writer); + replaceTextContentFromDocument(pdfDocument); + pdfDocument.close(); + } + + private static void replaceTextContentFromDocument(PdfDocument pdfDocument) throws IOException { + CompositeCleanupStrategy strategy = new CompositeCleanupStrategy(); + strategy.add(new RegexBasedCleanupStrategy("Baeldung tutorials").setRedactionColor(ColorConstants.WHITE)); + PdfCleaner.autoSweepCleanUp(pdfDocument, strategy); + + for (IPdfTextLocation location : strategy.getResultantLocations()) { + PdfPage page = pdfDocument.getPage(location.getPageNumber() + 1); + PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamAfter(), page.getResources(), page.getDocument()); + Canvas canvas = new Canvas(pdfCanvas, location.getRectangle()); + canvas.add(new Paragraph("HIDDEN").setFontSize(8) + .setMarginTop(0f)); + } + } + +} diff --git a/pdf-2/src/main/java/com/baeldung/pdfinfo/PdfInfoIText.java b/text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfinfo/PdfInfoIText.java similarity index 100% rename from pdf-2/src/main/java/com/baeldung/pdfinfo/PdfInfoIText.java rename to text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfinfo/PdfInfoIText.java diff --git a/pdf-2/src/main/java/com/baeldung/pdfinfo/PdfInfoPdfBox.java b/text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfinfo/PdfInfoPdfBox.java similarity index 100% rename from pdf-2/src/main/java/com/baeldung/pdfinfo/PdfInfoPdfBox.java rename to text-processing-libraries-modules/pdf-2/src/main/java/com/baeldung/pdfinfo/PdfInfoPdfBox.java diff --git a/pdf-2/src/main/resources/baeldung-cleaned.pdf b/text-processing-libraries-modules/pdf-2/src/main/resources/baeldung-cleaned.pdf similarity index 100% rename from pdf-2/src/main/resources/baeldung-cleaned.pdf rename to text-processing-libraries-modules/pdf-2/src/main/resources/baeldung-cleaned.pdf diff --git a/pdf-2/src/main/resources/baeldung-fixed.pdf b/text-processing-libraries-modules/pdf-2/src/main/resources/baeldung-fixed.pdf similarity index 100% rename from pdf-2/src/main/resources/baeldung-fixed.pdf rename to text-processing-libraries-modules/pdf-2/src/main/resources/baeldung-fixed.pdf diff --git a/pdf-2/src/main/resources/baeldung-modified.pdf b/text-processing-libraries-modules/pdf-2/src/main/resources/baeldung-modified.pdf similarity index 100% rename from pdf-2/src/main/resources/baeldung-modified.pdf rename to text-processing-libraries-modules/pdf-2/src/main/resources/baeldung-modified.pdf diff --git a/pdf-2/src/main/resources/baeldung.pdf b/text-processing-libraries-modules/pdf-2/src/main/resources/baeldung.pdf similarity index 100% rename from pdf-2/src/main/resources/baeldung.pdf rename to text-processing-libraries-modules/pdf-2/src/main/resources/baeldung.pdf diff --git a/pdf-2/src/main/resources/baeldung.png b/text-processing-libraries-modules/pdf-2/src/main/resources/baeldung.png similarity index 100% rename from pdf-2/src/main/resources/baeldung.png rename to text-processing-libraries-modules/pdf-2/src/main/resources/baeldung.png diff --git a/text-processing-libraries-modules/pdf-2/src/main/resources/excelsample.xlsx b/text-processing-libraries-modules/pdf-2/src/main/resources/excelsample.xlsx new file mode 100644 index 0000000000..771d312ae0 Binary files /dev/null and b/text-processing-libraries-modules/pdf-2/src/main/resources/excelsample.xlsx differ diff --git a/text-processing-libraries-modules/pdf-2/src/main/resources/pdfsample.pdf b/text-processing-libraries-modules/pdf-2/src/main/resources/pdfsample.pdf new file mode 100644 index 0000000000..6a47504513 --- /dev/null +++ b/text-processing-libraries-modules/pdf-2/src/main/resources/pdfsample.pdf @@ -0,0 +1,43 @@ +%PDF-1.4 +%âãÏÓ +3 0 obj +<>stream +xœ•WËRÛ0Ýû+î’.Puõ´–@Ÿ”R žÎtéi ¤Íc0d:ü}%K&a¢«daœãsïÑ‘tdªÓ¦’jn ™VXæ, îÞBÀšÛêèG?íz¸˜=>ÁU{×¾kþTÇéqÚyÞðç høe¸çpŒj¨ÿ±©®«‡Š3'œBàL9.ü@ý]b}säŠú®º-<ŽŠ³ÃBi&bHåX}CiÅT††.àÜûñÙ³5üË w’ üÐF4?ŒÍKѼ¼É–$îägW&Iš$h’Dq 'GÈìJ¢Ð(‰B£$ +’H®ojGȯú]Iš$h’D IÅõMµ-¹D I&Iš$Q\ßÔï‚$M’4I"Ð$‰âú¦øb`fySh’D I&I;èuH_Ÿ þ‹`-ãaK;h1zUˆ^3\×5„+:órõ9st¹b!i9Ü…dݪ…F±ÚV,Fü×ùŠ"T”`•|{ųõãÓjÑõcÅ—Z¶fJêŠl]^¬5“õa#lVOí<_N9ôq~X¹«v6¥ÄEŒ• * Xà!ãĬ)òu‹©^3Oû3¤lÈ_ºïÉrú íšp@8Æu‰¯ «ó\ͳ%ê/Ò'ã4EeŸ +Ìè“(ùT`ŸwËå3|Y}*ðýêv´OÒ–¸—´Q–$É=FÌ 9£dÑ(ºïÅzö?)›ÛV‰›mÀ÷úD·.ø¤ER{|¢™Ñ'Uô‰fë–¼*/(í^;åQf⛥DéýaOH¦K{° ¢°ÇPÏìùW–ÅßoÂÛk=˜ƒmÒÁ¢BçÕªáfÎ=ÿŠ‹þ‘]“é^ÑdbxÉdšý½]®»9Lœ¶7gNÞkºŒÙrjÁ`$²yƒÁ>W7û›²Át¯h°)þó˳ÏîÛ~>ëà†íœç‘o“ß÷};Ý7´\©‘Li*hêöTüˆ +endstream +endobj +5 0 obj +<>>>/Contents 3 0 R/Parent 4 0 R>> +endobj +1 0 obj +<> +endobj +2 0 obj +<> +endobj +4 0 obj +<> +endobj +6 0 obj +<> +endobj +7 0 obj +<> +endobj +xref +0 8 +0000000000 65535 f +0000000954 00000 n +0000001047 00000 n +0000000015 00000 n +0000001135 00000 n +0000000833 00000 n +0000001186 00000 n +0000001231 00000 n +trailer +<<6a28b1036b62f3808f3bfb62a88a5239>]>> +%iText-5.5.13.3 +startxref +1391 +%%EOF diff --git a/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoITextUnitTest.java b/text-processing-libraries-modules/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoITextUnitTest.java similarity index 100% rename from pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoITextUnitTest.java rename to text-processing-libraries-modules/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoITextUnitTest.java diff --git a/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoPdfBoxUnitTest.java b/text-processing-libraries-modules/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoPdfBoxUnitTest.java similarity index 100% rename from pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoPdfBoxUnitTest.java rename to text-processing-libraries-modules/pdf-2/src/test/java/com/baeldung/pdfinfo/PdfInfoPdfBoxUnitTest.java diff --git a/pdf-2/src/test/resources/input.pdf b/text-processing-libraries-modules/pdf-2/src/test/resources/input.pdf similarity index 100% rename from pdf-2/src/test/resources/input.pdf rename to text-processing-libraries-modules/pdf-2/src/test/resources/input.pdf diff --git a/pdf/.gitignore b/text-processing-libraries-modules/pdf/.gitignore similarity index 100% rename from pdf/.gitignore rename to text-processing-libraries-modules/pdf/.gitignore diff --git a/pdf/README.md b/text-processing-libraries-modules/pdf/README.md similarity index 100% rename from pdf/README.md rename to text-processing-libraries-modules/pdf/README.md diff --git a/pdf/input.docx b/text-processing-libraries-modules/pdf/input.docx similarity index 100% rename from pdf/input.docx rename to text-processing-libraries-modules/pdf/input.docx diff --git a/pdf/output.pdf b/text-processing-libraries-modules/pdf/output.pdf similarity index 100% rename from pdf/output.pdf rename to text-processing-libraries-modules/pdf/output.pdf diff --git a/pdf/pom.xml b/text-processing-libraries-modules/pdf/pom.xml similarity index 98% rename from pdf/pom.xml rename to text-processing-libraries-modules/pdf/pom.xml index 041f356b9a..b5de19f815 100644 --- a/pdf/pom.xml +++ b/text-processing-libraries-modules/pdf/pom.xml @@ -9,7 +9,7 @@ com.baeldung - parent-modules + text-processing-libraries-modules 1.0.0-SNAPSHOT diff --git a/pdf/sample.pdf b/text-processing-libraries-modules/pdf/sample.pdf similarity index 100% rename from pdf/sample.pdf rename to text-processing-libraries-modules/pdf/sample.pdf diff --git a/pdf/src/main/java/com/baeldung/pdf/DocxToPDFExample.java b/text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/DocxToPDFExample.java similarity index 100% rename from pdf/src/main/java/com/baeldung/pdf/DocxToPDFExample.java rename to text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/DocxToPDFExample.java diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java b/text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java similarity index 100% rename from pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java rename to text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/PDF2HTMLExample.java diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java b/text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java similarity index 100% rename from pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java rename to text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/PDF2ImageExample.java diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java b/text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java similarity index 100% rename from pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java rename to text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/PDF2TextExample.java diff --git a/pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java b/text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java similarity index 100% rename from pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java rename to text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/PDF2WordExample.java diff --git a/pdf/src/main/java/com/baeldung/pdf/PDFSampleMain.java b/text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/PDFSampleMain.java similarity index 100% rename from pdf/src/main/java/com/baeldung/pdf/PDFSampleMain.java rename to text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/PDFSampleMain.java diff --git a/pdf/src/main/java/com/baeldung/pdf/openpdf/CustomElementFactoryImpl.java b/text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/openpdf/CustomElementFactoryImpl.java similarity index 100% rename from pdf/src/main/java/com/baeldung/pdf/openpdf/CustomElementFactoryImpl.java rename to text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/openpdf/CustomElementFactoryImpl.java diff --git a/pdf/src/main/java/com/baeldung/pdf/openpdf/Html2PdfUsingFlyingSaucer.java b/text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/openpdf/Html2PdfUsingFlyingSaucer.java similarity index 100% rename from pdf/src/main/java/com/baeldung/pdf/openpdf/Html2PdfUsingFlyingSaucer.java rename to text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/openpdf/Html2PdfUsingFlyingSaucer.java diff --git a/pdf/src/main/java/com/baeldung/pdf/openpdf/Html2PdfUsingOpenHtml.java b/text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/openpdf/Html2PdfUsingOpenHtml.java similarity index 100% rename from pdf/src/main/java/com/baeldung/pdf/openpdf/Html2PdfUsingOpenHtml.java rename to text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdf/openpdf/Html2PdfUsingOpenHtml.java diff --git a/pdf/src/main/java/com/baeldung/pdfthymeleaf/PDFThymeleafExample.java b/text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdfthymeleaf/PDFThymeleafExample.java similarity index 100% rename from pdf/src/main/java/com/baeldung/pdfthymeleaf/PDFThymeleafExample.java rename to text-processing-libraries-modules/pdf/src/main/java/com/baeldung/pdfthymeleaf/PDFThymeleafExample.java diff --git a/pdf/src/main/resources/Java_logo.png b/text-processing-libraries-modules/pdf/src/main/resources/Java_logo.png similarity index 100% rename from pdf/src/main/resources/Java_logo.png rename to text-processing-libraries-modules/pdf/src/main/resources/Java_logo.png diff --git a/pdf/src/main/resources/html.html b/text-processing-libraries-modules/pdf/src/main/resources/html.html similarity index 100% rename from pdf/src/main/resources/html.html rename to text-processing-libraries-modules/pdf/src/main/resources/html.html diff --git a/pdf/src/main/resources/html2pdf.pdf b/text-processing-libraries-modules/pdf/src/main/resources/html2pdf.pdf similarity index 100% rename from pdf/src/main/resources/html2pdf.pdf rename to text-processing-libraries-modules/pdf/src/main/resources/html2pdf.pdf diff --git a/pdf/src/main/resources/htmlforopenpdf.html b/text-processing-libraries-modules/pdf/src/main/resources/htmlforopenpdf.html similarity index 100% rename from pdf/src/main/resources/htmlforopenpdf.html rename to text-processing-libraries-modules/pdf/src/main/resources/htmlforopenpdf.html diff --git a/text-processing-libraries-modules/pdf/src/main/resources/logback.xml b/text-processing-libraries-modules/pdf/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/text-processing-libraries-modules/pdf/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/pdf/src/main/resources/pdf.pdf b/text-processing-libraries-modules/pdf/src/main/resources/pdf.pdf similarity index 100% rename from pdf/src/main/resources/pdf.pdf rename to text-processing-libraries-modules/pdf/src/main/resources/pdf.pdf diff --git a/pdf/src/main/resources/style.css b/text-processing-libraries-modules/pdf/src/main/resources/style.css similarity index 100% rename from pdf/src/main/resources/style.css rename to text-processing-libraries-modules/pdf/src/main/resources/style.css diff --git a/pdf/src/main/resources/thymeleaf_template.html b/text-processing-libraries-modules/pdf/src/main/resources/thymeleaf_template.html similarity index 100% rename from pdf/src/main/resources/thymeleaf_template.html rename to text-processing-libraries-modules/pdf/src/main/resources/thymeleaf_template.html diff --git a/pdf/src/main/resources/txt.txt b/text-processing-libraries-modules/pdf/src/main/resources/txt.txt similarity index 100% rename from pdf/src/main/resources/txt.txt rename to text-processing-libraries-modules/pdf/src/main/resources/txt.txt diff --git a/pdf/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java b/text-processing-libraries-modules/pdf/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java similarity index 100% rename from pdf/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java rename to text-processing-libraries-modules/pdf/src/test/java/com/baeldung/pdf/base64/EncodeDecodeUnitTest.java diff --git a/pdf/src/test/java/com/baeldung/pdfreadertest/ReadPdfFileUnitTest.java b/text-processing-libraries-modules/pdf/src/test/java/com/baeldung/pdfreadertest/ReadPdfFileUnitTest.java similarity index 100% rename from pdf/src/test/java/com/baeldung/pdfreadertest/ReadPdfFileUnitTest.java rename to text-processing-libraries-modules/pdf/src/test/java/com/baeldung/pdfreadertest/ReadPdfFileUnitTest.java diff --git a/pdf/src/test/java/com/baeldung/pdfthymeleaf/PDFThymeleafUnitTest.java b/text-processing-libraries-modules/pdf/src/test/java/com/baeldung/pdfthymeleaf/PDFThymeleafUnitTest.java similarity index 100% rename from pdf/src/test/java/com/baeldung/pdfthymeleaf/PDFThymeleafUnitTest.java rename to text-processing-libraries-modules/pdf/src/test/java/com/baeldung/pdfthymeleaf/PDFThymeleafUnitTest.java diff --git a/pdf/src/test/resources/input.pdf b/text-processing-libraries-modules/pdf/src/test/resources/input.pdf similarity index 100% rename from pdf/src/test/resources/input.pdf rename to text-processing-libraries-modules/pdf/src/test/resources/input.pdf diff --git a/pdf/src/test/resources/output.pdf b/text-processing-libraries-modules/pdf/src/test/resources/output.pdf similarity index 100% rename from pdf/src/test/resources/output.pdf rename to text-processing-libraries-modules/pdf/src/test/resources/output.pdf diff --git a/text-processing-libraries-modules/pom.xml b/text-processing-libraries-modules/pom.xml new file mode 100644 index 0000000000..a7bb3675eb --- /dev/null +++ b/text-processing-libraries-modules/pom.xml @@ -0,0 +1,24 @@ + + + 4.0.0 + text-processing-libraries-modules + text-processing-libraries-modules + pom + + + parent-modules + com.baeldung + 1.0.0-SNAPSHOT + + + + antlr + apache-tika + asciidoctor + pdf + pdf-2 + + + \ No newline at end of file diff --git a/timefold-solver/README.md b/timefold-solver/README.md new file mode 100644 index 0000000000..67fdd81bc1 --- /dev/null +++ b/timefold-solver/README.md @@ -0,0 +1,8 @@ +## Timefold Solver + +This module contains articles about (Timefold Solver)[https://timefold.ai]. + +### Relevant articles + +- [A Guide to Timefold Solver for Employee Scheduling](https://www.baeldung.com/java-timefold-solver-guide) + diff --git a/timefold-solver/pom.xml b/timefold-solver/pom.xml new file mode 100644 index 0000000000..a16afb9e54 --- /dev/null +++ b/timefold-solver/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + timefold-solver + timefold-solver + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + + ai.timefold.solver + timefold-solver-bom + ${version.ai.timefold.solver} + pom + import + + + + + + ai.timefold.solver + timefold-solver-core + + + ai.timefold.solver + timefold-solver-test + test + + + + + 17 + 17 + 1.4.0 + + + diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java new file mode 100644 index 0000000000..ef4752a8c6 --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Employee.java @@ -0,0 +1,28 @@ +package com.baeldung.timefoldsolver; + +import java.util.Set; + +public class Employee { + + private String name; + private Set skills; + + public Employee(String name, Set skills) { + this.name = name; + this.skills = skills; + } + + @Override + public String toString() { + return name; + } + + public String getName() { + return name; + } + + public Set getSkills() { + return skills; + } + +} diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java new file mode 100644 index 0000000000..2ef2f2a1b9 --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/Shift.java @@ -0,0 +1,54 @@ +package com.baeldung.timefoldsolver; + +import java.time.LocalDateTime; + +import ai.timefold.solver.core.api.domain.entity.PlanningEntity; +import ai.timefold.solver.core.api.domain.variable.PlanningVariable; + +@PlanningEntity +public class Shift { + + private LocalDateTime start; + private LocalDateTime end; + private String requiredSkill; + + @PlanningVariable + private Employee employee; + + // A no-arg constructor is required for @PlanningEntity annotated classes + public Shift() { + } + + public Shift(LocalDateTime start, LocalDateTime end, String requiredSkill) { + this(start, end, requiredSkill, null); + } + + public Shift(LocalDateTime start, LocalDateTime end, String requiredSkill, Employee employee) { + this.start = start; + this.end = end; + this.requiredSkill = requiredSkill; + this.employee = employee; + } + + @Override + public String toString() { + return start + " - " + end; + } + + public LocalDateTime getStart() { + return start; + } + + public LocalDateTime getEnd() { + return end; + } + + public String getRequiredSkill() { + return requiredSkill; + } + + public Employee getEmployee() { + return employee; + } + +} diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java new file mode 100644 index 0000000000..794c31e5b7 --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftSchedule.java @@ -0,0 +1,43 @@ +package com.baeldung.timefoldsolver; + +import java.util.List; + +import ai.timefold.solver.core.api.domain.solution.PlanningEntityCollectionProperty; +import ai.timefold.solver.core.api.domain.solution.PlanningScore; +import ai.timefold.solver.core.api.domain.solution.PlanningSolution; +import ai.timefold.solver.core.api.domain.valuerange.ValueRangeProvider; +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; + +@PlanningSolution +public class ShiftSchedule { + + @ValueRangeProvider + private List employees; + @PlanningEntityCollectionProperty + private List shifts; + + @PlanningScore + private HardSoftScore score; + + // A no-arg constructor is required for @PlanningSolution annotated classes + public ShiftSchedule() { + } + + public ShiftSchedule(List employees, List shifts) { + this.employees = employees; + this.shifts = shifts; + } + + public List getEmployees() { + return employees; + } + + public List getShifts() { + return shifts; + } + + public HardSoftScore getScore() { + return score; + } + +} diff --git a/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java new file mode 100644 index 0000000000..bd308dacbf --- /dev/null +++ b/timefold-solver/src/main/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProvider.java @@ -0,0 +1,35 @@ +package com.baeldung.timefoldsolver; + +import static ai.timefold.solver.core.api.score.stream.Joiners.equal; + +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; +import ai.timefold.solver.core.api.score.stream.Constraint; +import ai.timefold.solver.core.api.score.stream.ConstraintFactory; +import ai.timefold.solver.core.api.score.stream.ConstraintProvider; + +public class ShiftScheduleConstraintProvider implements ConstraintProvider { + + @Override + public Constraint[] defineConstraints(ConstraintFactory constraintFactory) { + return new Constraint[] { atMostOneShiftPerDay(constraintFactory), requiredSkill(constraintFactory) }; + } + + public Constraint atMostOneShiftPerDay(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Shift.class) + .join(Shift.class, equal(shift -> shift.getStart() + .toLocalDate()), equal(Shift::getEmployee)) + .filter((shift1, shift2) -> shift1 != shift2) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("At most one shift per day"); + } + + public Constraint requiredSkill(ConstraintFactory constraintFactory) { + return constraintFactory.forEach(Shift.class) + .filter(shift -> !shift.getEmployee() + .getSkills() + .contains(shift.getRequiredSkill())) + .penalize(HardSoftScore.ONE_HARD) + .asConstraint("Required skill"); + } + +} diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java new file mode 100644 index 0000000000..c8ec5b53c4 --- /dev/null +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleConstraintProviderUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.timefoldsolver; + +import java.time.LocalDate; +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import ai.timefold.solver.test.api.score.stream.ConstraintVerifier; + +class ShiftScheduleConstraintProviderUnitTest { + + private static final LocalDate MONDAY = LocalDate.of(2030, 4, 1); + private static final LocalDate TUESDAY = LocalDate.of(2030, 4, 2); + + ConstraintVerifier constraintVerifier = ConstraintVerifier.build(new ShiftScheduleConstraintProvider(), + ShiftSchedule.class, Shift.class); + + @Test + void givenTwoShiftsOnOneDay_whenApplyingAtMostOneShiftPerDayConstraint_thenPenalize() { + Employee ann = new Employee("Ann", null); + constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) + .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(MONDAY.atTime(14, 0), MONDAY.atTime(22, 0), null, ann)) + // Penalizes by 2 because both {shiftA, shiftB} and {shiftB, shiftA} match. + // To avoid that, use forEachUniquePair(Shift) instead of forEach(Shift).join(Shift) in ShiftScheduleConstraintProvider.atMostOneShiftPerDay(). + .penalizesBy(2); + } + + @Test + void givenTwoShiftsOnDifferentDays_whenApplyingAtMostOneShiftPerDayConstraint_thenDoNotPenalize() { + Employee ann = new Employee("Ann", null); + constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::atMostOneShiftPerDay) + .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), null, ann), new Shift(TUESDAY.atTime(14, 0), TUESDAY.atTime(22, 0), null, ann)) + .penalizesBy(0); + } + + @Test + void givenEmployeeLacksRequiredSkill_whenApplyingRequiredSkillConstraint_thenPenalize() { + Employee ann = new Employee("Ann", Set.of("Waiter")); + constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::requiredSkill) + .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Cook", ann)) + .penalizesBy(1); + } + + @Test + void givenEmployeeHasRequiredSkill_whenApplyingRequiredSkillConstraint_thenDoNotPenalize() { + Employee ann = new Employee("Ann", Set.of("Waiter")); + constraintVerifier.verifyThat(ShiftScheduleConstraintProvider::requiredSkill) + .given(ann, new Shift(MONDAY.atTime(6, 0), MONDAY.atTime(14, 0), "Waiter", ann)) + .penalizesBy(0); + } + +} diff --git a/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java new file mode 100644 index 0000000000..873ce1a853 --- /dev/null +++ b/timefold-solver/src/test/java/com/baeldung/timefoldsolver/ShiftScheduleSolverUnitTest.java @@ -0,0 +1,65 @@ +package com.baeldung.timefoldsolver; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import java.time.Duration; +import java.time.LocalDate; +import java.util.List; +import java.util.Set; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ai.timefold.solver.core.api.score.buildin.hardsoft.HardSoftScore; +import ai.timefold.solver.core.api.solver.Solver; +import ai.timefold.solver.core.api.solver.SolverFactory; +import ai.timefold.solver.core.config.solver.SolverConfig; +import ai.timefold.solver.core.config.solver.termination.TerminationConfig; + +public class ShiftScheduleSolverUnitTest { + + private static final Logger logger = LoggerFactory.getLogger(ShiftScheduleSolverUnitTest.class); + + @Test + public void given3Employees5Shifts_whenSolve_thenScoreIsOptimalAndAllShiftsAssigned() { + SolverFactory solverFactory = SolverFactory.create(new SolverConfig().withSolutionClass(ShiftSchedule.class) + .withEntityClasses(Shift.class) + .withConstraintProviderClass(ShiftScheduleConstraintProvider.class) + // For this dataset, we know the optimal score in advance (which is normally not the case). + // So we can use .withBestScoreLimit() instead of .withTerminationSpentLimit(). + .withTerminationConfig(new TerminationConfig().withBestScoreLimit("0hard/0soft"))); + Solver solver = solverFactory.buildSolver(); + + ShiftSchedule problem = loadProblem(); + ShiftSchedule solution = solver.solve(problem); + assertThat(solution.getScore()).isEqualTo(HardSoftScore.ZERO); + assertThat(solution.getShifts().size()).isNotZero(); + for (Shift shift : solution.getShifts()) { + assertThat(shift.getEmployee()).isNotNull(); + } + printSolution(solution); + } + + private ShiftSchedule loadProblem() { + LocalDate monday = LocalDate.of(2030, 4, 1); + LocalDate tuesday = LocalDate.of(2030, 4, 2); + return new ShiftSchedule( + List.of(new Employee("Ann", Set.of("Bartender")), new Employee("Beth", Set.of("Waiter", "Bartender")), new Employee("Carl", Set.of("Waiter"))), + List.of(new Shift(monday.atTime(6, 0), monday.atTime(14, 0), "Waiter"), new Shift(monday.atTime(9, 0), monday.atTime(17, 0), "Bartender"), + new Shift(monday.atTime(14, 0), monday.atTime(22, 0), "Bartender"), new Shift(tuesday.atTime(6, 0), tuesday.atTime(14, 0), "Waiter"), + new Shift(tuesday.atTime(14, 0), tuesday.atTime(22, 0), "Bartender"))); + } + + private void printSolution(ShiftSchedule solution) { + logger.info("Shift assignments"); + for (Shift shift : solution.getShifts()) { + logger.info(" " + shift.getStart() + .toLocalDate() + " " + shift.getStart() + .toLocalTime() + " - " + shift.getEnd() + .toLocalTime() + ": " + shift.getEmployee() + .getName()); + } + } + +} diff --git a/vavr-modules/java-vavr-stream/pom.xml b/vavr-modules/java-vavr-stream/pom.xml index cda9d1f734..e369fa7cf3 100644 --- a/vavr-modules/java-vavr-stream/pom.xml +++ b/vavr-modules/java-vavr-stream/pom.xml @@ -19,12 +19,8 @@ io.vavr vavr - ${io.vavr.version} + ${vavr.version} - - 0.9.2 - - \ No newline at end of file diff --git a/vavr-modules/pom.xml b/vavr-modules/pom.xml index 416c689511..e9a3b121aa 100644 --- a/vavr-modules/pom.xml +++ b/vavr-modules/pom.xml @@ -30,4 +30,8 @@ + + 0.9.2 + + \ No newline at end of file diff --git a/vavr-modules/vavr-2/pom.xml b/vavr-modules/vavr-2/pom.xml index 0063daa518..54f3cb4d71 100644 --- a/vavr-modules/vavr-2/pom.xml +++ b/vavr-modules/vavr-2/pom.xml @@ -21,8 +21,4 @@ - - 0.9.1 - - \ No newline at end of file diff --git a/vertx-modules/pom.xml b/vertx-modules/pom.xml index 7d9614ad61..00f0bc46f5 100644 --- a/vertx-modules/pom.xml +++ b/vertx-modules/pom.xml @@ -30,4 +30,8 @@ + + 3.9.15 + + \ No newline at end of file diff --git a/vertx-modules/vertx-and-rxjava/pom.xml b/vertx-modules/vertx-and-rxjava/pom.xml index 16eaf8ebaa..b68117ddeb 100644 --- a/vertx-modules/vertx-and-rxjava/pom.xml +++ b/vertx-modules/vertx-and-rxjava/pom.xml @@ -40,8 +40,4 @@ - - 3.9.15 - - \ No newline at end of file diff --git a/vertx-modules/vertx/pom.xml b/vertx-modules/vertx/pom.xml index 75df2fae69..d34deca9d8 100644 --- a/vertx-modules/vertx/pom.xml +++ b/vertx-modules/vertx/pom.xml @@ -65,7 +65,6 @@ - 3.9.15 3.2.1 diff --git a/video-tutorials/pom.xml b/video-tutorials/pom.xml index 52c4f2af2a..e1a2a22b30 100644 --- a/video-tutorials/pom.xml +++ b/video-tutorials/pom.xml @@ -10,9 +10,8 @@ com.baeldung - parent-java - 0.0.1-SNAPSHOT - ../parent-java + parent-modules + 1.0.0-SNAPSHOT diff --git a/web-modules/apache-tapestry/pom.xml b/web-modules/apache-tapestry/pom.xml index 562cdff00c..bfc7c22415 100644 --- a/web-modules/apache-tapestry/pom.xml +++ b/web-modules/apache-tapestry/pom.xml @@ -78,17 +78,13 @@ org.apache.maven.plugins maven-compiler-plugin - ${compiler.plugin.version} - ${source.version} - ${target.version} true org.apache.maven.plugins maven-surefire-plugin - ${compiler.surefire.version} Qa @@ -118,7 +114,6 @@ org.apache.maven.plugins maven-war-plugin - 3.3.1 @@ -140,9 +135,6 @@ 6.1.16 3.0.0-M5 - 3.8.1 - 11 - 11 5.8.2 2.5 6.8.21 diff --git a/web-modules/blade/pom.xml b/web-modules/blade/pom.xml index 2748c05663..fb0ca13dbe 100644 --- a/web-modules/blade/pom.xml +++ b/web-modules/blade/pom.xml @@ -62,7 +62,6 @@ org.apache.maven.plugins maven-failsafe-plugin - ${maven-failsafe-plugin.version} true diff --git a/web-modules/jakarta-ee/pom.xml b/web-modules/jakarta-ee/pom.xml index 066bc14766..d90e848323 100644 --- a/web-modules/jakarta-ee/pom.xml +++ b/web-modules/jakarta-ee/pom.xml @@ -2,7 +2,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 jakarta-ee 1.0-SNAPSHOT jakarta-ee @@ -51,7 +50,7 @@ org.glassfish.maven.plugin maven-glassfish-plugin - 2.1 + ${maven-glassfish-plugin.version} ${local.glassfish.home} admin @@ -76,11 +75,6 @@ org.apache.maven.plugins maven-compiler-plugin - 3.8.0 - - 11 - 11 - org.apache.maven.plugins @@ -104,6 +98,7 @@ ${local.glassfish.home}\\domains\\${local.glassfish.domain}\\config\\domain-passwords + 2.1 \ No newline at end of file diff --git a/web-modules/java-takes/README.md b/web-modules/java-takes/README.md new file mode 100644 index 0000000000..0db4361d6f --- /dev/null +++ b/web-modules/java-takes/README.md @@ -0,0 +1,7 @@ +## Java takes + +This module contains articles about Takes. + +### Relevant Articles: +- [Introduction to Takes](https://www.baeldung.com/java-takes) + diff --git a/web-modules/java-takes/pom.xml b/web-modules/java-takes/pom.xml new file mode 100644 index 0000000000..e28f75b536 --- /dev/null +++ b/web-modules/java-takes/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + com.baeldung.spring-boot-modules + java-takes + + + com.baeldung + web-modules + 1.0.0-SNAPSHOT + + + + + + + org.takes + takes + ${takes.version} + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + + + + reload + + + + src/main/resources + true + + + src/main/webapp + true + + + + + org.codehaus.mojo + exec-maven-plugin + + + start-server + pre-integration-test + + java + + + + + com.baeldung.com.baeldung.takes.TakesApp + false + + --port=${port} + + + + + + + + + + 1.19 + 4.4.13 + 4.5.12 + + + \ No newline at end of file diff --git a/libraries-3/src/main/java/com/baeldung/takes/TakesApp.java b/web-modules/java-takes/src/main/java/com/baeldung/takes/TakesApp.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/takes/TakesApp.java rename to web-modules/java-takes/src/main/java/com/baeldung/takes/TakesApp.java diff --git a/libraries-3/src/main/java/com/baeldung/takes/TakesContact.java b/web-modules/java-takes/src/main/java/com/baeldung/takes/TakesContact.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/takes/TakesContact.java rename to web-modules/java-takes/src/main/java/com/baeldung/takes/TakesContact.java diff --git a/libraries-3/src/main/java/com/baeldung/takes/TakesHelloWorld.java b/web-modules/java-takes/src/main/java/com/baeldung/takes/TakesHelloWorld.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/takes/TakesHelloWorld.java rename to web-modules/java-takes/src/main/java/com/baeldung/takes/TakesHelloWorld.java diff --git a/libraries-3/src/main/java/com/baeldung/takes/TakesIndex.java b/web-modules/java-takes/src/main/java/com/baeldung/takes/TakesIndex.java similarity index 100% rename from libraries-3/src/main/java/com/baeldung/takes/TakesIndex.java rename to web-modules/java-takes/src/main/java/com/baeldung/takes/TakesIndex.java diff --git a/web-modules/java-takes/src/main/resources/logback.xml b/web-modules/java-takes/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/web-modules/java-takes/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/libraries-3/src/main/webapp/templates/index.vm b/web-modules/java-takes/src/main/webapp/templates/index.vm similarity index 100% rename from libraries-3/src/main/webapp/templates/index.vm rename to web-modules/java-takes/src/main/webapp/templates/index.vm diff --git a/libraries-3/src/test/java/com/baeldung/takes/TakesAppIntegrationTest.java b/web-modules/java-takes/src/test/java/com/baeldung/takes/TakesAppIntegrationTest.java similarity index 100% rename from libraries-3/src/test/java/com/baeldung/takes/TakesAppIntegrationTest.java rename to web-modules/java-takes/src/test/java/com/baeldung/takes/TakesAppIntegrationTest.java diff --git a/libraries-3/src/test/java/com/baeldung/takes/TakesContactUnitTest.java b/web-modules/java-takes/src/test/java/com/baeldung/takes/TakesContactUnitTest.java similarity index 100% rename from libraries-3/src/test/java/com/baeldung/takes/TakesContactUnitTest.java rename to web-modules/java-takes/src/test/java/com/baeldung/takes/TakesContactUnitTest.java diff --git a/web-modules/javax-servlets-2/pom.xml b/web-modules/javax-servlets-2/pom.xml index 9ba12352fd..a6bfc6b473 100644 --- a/web-modules/javax-servlets-2/pom.xml +++ b/web-modules/javax-servlets-2/pom.xml @@ -68,6 +68,17 @@ + + org.mockito + mockito-core + ${mockito.version} + test + + + com.github.ua-parser + uap-java + ${uap.version} + @@ -101,6 +112,8 @@ 2.22.2 10.0.4 1.10.0 + 5.6.0 + 1.5.4 \ No newline at end of file diff --git a/web-modules/javax-servlets-2/src/main/java/com/baeldung/servlets/AccountServlet.java b/web-modules/javax-servlets-2/src/main/java/com/baeldung/servlets/AccountServlet.java new file mode 100644 index 0000000000..3533bf500b --- /dev/null +++ b/web-modules/javax-servlets-2/src/main/java/com/baeldung/servlets/AccountServlet.java @@ -0,0 +1,26 @@ +package com.baeldung.servlets; + +import java.io.IOException; +import java.util.Map; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.*; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.baeldung.servlets.clientinfo.AccountLogic; + +@WebServlet(name = "AccountServlet", urlPatterns = "/account") +public class AccountServlet extends HttpServlet { + public static final Logger log = LoggerFactory.getLogger(AccountServlet.class); + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { + AccountLogic accountLogic = new AccountLogic(); + Map clientInfo = accountLogic.getClientInfo(request); + log.info("Request client info: {}, " + clientInfo); + + response.setStatus(HttpServletResponse.SC_OK); + } +} diff --git a/web-modules/javax-servlets-2/src/main/java/com/baeldung/servlets/clientinfo/AccountLogic.java b/web-modules/javax-servlets-2/src/main/java/com/baeldung/servlets/clientinfo/AccountLogic.java new file mode 100644 index 0000000000..00f3a5ca39 --- /dev/null +++ b/web-modules/javax-servlets-2/src/main/java/com/baeldung/servlets/clientinfo/AccountLogic.java @@ -0,0 +1,32 @@ +package com.baeldung.servlets.clientinfo; + +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import ua_parser.Client; +import ua_parser.Parser; + +public class AccountLogic { + public Map getClientInfo(HttpServletRequest request) { + String remoteAddr = request.getRemoteAddr(); + String remoteHost = request.getRemoteHost(); + String remoteUser = request.getRemoteUser(); + String contentType = request.getHeader("content-type"); + String userAgent = request.getHeader("user-agent"); + + Parser uaParser = new Parser(); + Client client = uaParser.parse(userAgent); + + Map clientInfo = new HashMap<>(); + clientInfo.put("os_family", client.os.family); + clientInfo.put("device_family", client.device.family); + clientInfo.put("userAgent_family", client.userAgent.family); + clientInfo.put("remote_address", remoteAddr); + clientInfo.put("remote_host", remoteHost); + clientInfo.put("remote_user", remoteUser); + clientInfo.put("content_type", contentType); + return clientInfo; + } +} diff --git a/web-modules/javax-servlets-2/src/test/java/com/baeldung/servlets/clientinfo/ClientInformationUnitTest.java b/web-modules/javax-servlets-2/src/test/java/com/baeldung/servlets/clientinfo/ClientInformationUnitTest.java new file mode 100644 index 0000000000..4ff5256f37 --- /dev/null +++ b/web-modules/javax-servlets-2/src/test/java/com/baeldung/servlets/clientinfo/ClientInformationUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.servlets.clientinfo; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.mockito.Mockito.when; + +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; + +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +public class ClientInformationUnitTest { + + @Test + void givenMockHttpServletRequestWithHeaders_whenGetClientInfo_thenReturnsUserAGentInfo() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + when(request.getHeader("user-agent")).thenReturn("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36, acceptLanguage:en-US,en;q=0.9"); + when(request.getHeader("content-type")).thenReturn("application/json"); + when(request.getRemoteAddr()).thenReturn("198.167.0.1"); + when(request.getRemoteHost()).thenReturn("baeldung.com"); + when(request.getRemoteUser()).thenReturn("baeldung"); + + AccountLogic accountLogic = new AccountLogic(); + Map clientInfo = accountLogic.getClientInfo(request); + assertThat(clientInfo.get("os_family")).isEqualTo("Mac OS X"); + assertThat(clientInfo.get("device_family")).isEqualTo("Mac"); + assertThat(clientInfo.get("userAgent_family")).isEqualTo("Chrome"); + assertThat(clientInfo.get("content_type")).isEqualTo("application/json"); + assertThat(clientInfo.get("remote_user")).isEqualTo("baeldung"); + assertThat(clientInfo.get("remote_address")).isEqualTo("198.167.0.1"); + assertThat(clientInfo.get("remote_host")).isEqualTo("baeldung.com"); + } +} \ No newline at end of file diff --git a/jersey/README.md b/web-modules/jersey/README.md similarity index 100% rename from jersey/README.md rename to web-modules/jersey/README.md diff --git a/jersey/pom.xml b/web-modules/jersey/pom.xml similarity index 98% rename from jersey/pom.xml rename to web-modules/jersey/pom.xml index d279406e9a..779403e8c1 100644 --- a/jersey/pom.xml +++ b/web-modules/jersey/pom.xml @@ -9,7 +9,7 @@ com.baeldung - parent-modules + web-modules 1.0.0-SNAPSHOT diff --git a/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java diff --git a/jersey/src/main/java/com/baeldung/jersey/client/JerseyClientHeaders.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/client/JerseyClientHeaders.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/client/JerseyClientHeaders.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/client/JerseyClientHeaders.java diff --git a/jersey/src/main/java/com/baeldung/jersey/client/filter/AddHeaderOnRequestFilter.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/client/filter/AddHeaderOnRequestFilter.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/client/filter/AddHeaderOnRequestFilter.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/client/filter/AddHeaderOnRequestFilter.java diff --git a/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java diff --git a/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java diff --git a/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java diff --git a/jersey/src/main/java/com/baeldung/jersey/client/listdemo/JerseyListDemo.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/client/listdemo/JerseyListDemo.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/client/listdemo/JerseyListDemo.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/client/listdemo/JerseyListDemo.java diff --git a/jersey/src/main/java/com/baeldung/jersey/client/listdemo/ListDemoApp.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/client/listdemo/ListDemoApp.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/client/listdemo/ListDemoApp.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/client/listdemo/ListDemoApp.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/ExceptionHandlingConfig.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/ExceptionHandlingConfig.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/exceptionhandling/ExceptionHandlingConfig.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/ExceptionHandlingConfig.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Stock.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Stock.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Stock.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Stock.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Wallet.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Wallet.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Wallet.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/data/Wallet.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Db.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Db.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Db.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Db.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Identifiable.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Identifiable.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Identifiable.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/repo/Identifiable.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/StocksResource.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/StocksResource.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/StocksResource.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/StocksResource.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/WalletsResource.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/WalletsResource.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/WalletsResource.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/WalletsResource.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/IllegalArgumentExceptionMapper.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/IllegalArgumentExceptionMapper.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/IllegalArgumentExceptionMapper.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/IllegalArgumentExceptionMapper.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/InvalidTradeException.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/InvalidTradeException.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/InvalidTradeException.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/InvalidTradeException.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/RestErrorResponse.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/RestErrorResponse.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/RestErrorResponse.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/RestErrorResponse.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/ServerExceptionMapper.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/ServerExceptionMapper.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/ServerExceptionMapper.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/ServerExceptionMapper.java diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/service/Repository.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/service/Repository.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/exceptionhandling/service/Repository.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/service/Repository.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/EchoHeaders.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/EchoHeaders.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/EchoHeaders.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/EchoHeaders.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/Greetings.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/ItemParam.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/ItemParam.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/ItemParam.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/ItemParam.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/Items.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/Items.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/Items.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/Items.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/Responder.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/Responder.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/Responder.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/Responder.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/ViewApplicationConfig.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/config/ViewApplicationConfig.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/config/ViewApplicationConfig.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/config/ViewApplicationConfig.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/constraints/SerialNumber.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/constraints/SerialNumber.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/constraints/SerialNumber.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/constraints/SerialNumber.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/form/FormExampleResource.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/form/FormExampleResource.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/form/FormExampleResource.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/form/FormExampleResource.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/model/Person.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/model/Person.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/model/Person.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/model/Person.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/providers/FruitExceptionMapper.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/providers/FruitExceptionMapper.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/providers/FruitExceptionMapper.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/providers/FruitExceptionMapper.java diff --git a/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java diff --git a/jersey/src/main/java/com/baeldung/jersey/service/SimpleStorageService.java b/web-modules/jersey/src/main/java/com/baeldung/jersey/service/SimpleStorageService.java similarity index 100% rename from jersey/src/main/java/com/baeldung/jersey/service/SimpleStorageService.java rename to web-modules/jersey/src/main/java/com/baeldung/jersey/service/SimpleStorageService.java diff --git a/jersey/src/main/resources/formexamples/example1.html b/web-modules/jersey/src/main/resources/formexamples/example1.html similarity index 100% rename from jersey/src/main/resources/formexamples/example1.html rename to web-modules/jersey/src/main/resources/formexamples/example1.html diff --git a/jersey/src/main/resources/formexamples/example2.html b/web-modules/jersey/src/main/resources/formexamples/example2.html similarity index 100% rename from jersey/src/main/resources/formexamples/example2.html rename to web-modules/jersey/src/main/resources/formexamples/example2.html diff --git a/web-modules/jersey/src/main/resources/logback.xml b/web-modules/jersey/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/web-modules/jersey/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/jersey/src/main/resources/templates/freemarker/all.ftl b/web-modules/jersey/src/main/resources/templates/freemarker/all.ftl similarity index 100% rename from jersey/src/main/resources/templates/freemarker/all.ftl rename to web-modules/jersey/src/main/resources/templates/freemarker/all.ftl diff --git a/jersey/src/main/resources/templates/freemarker/error.ftl b/web-modules/jersey/src/main/resources/templates/freemarker/error.ftl similarity index 100% rename from jersey/src/main/resources/templates/freemarker/error.ftl rename to web-modules/jersey/src/main/resources/templates/freemarker/error.ftl diff --git a/jersey/src/main/resources/templates/freemarker/index.ftl b/web-modules/jersey/src/main/resources/templates/freemarker/index.ftl similarity index 100% rename from jersey/src/main/resources/templates/freemarker/index.ftl rename to web-modules/jersey/src/main/resources/templates/freemarker/index.ftl diff --git a/jersey/src/main/resources/templates/freemarker/named.ftl b/web-modules/jersey/src/main/resources/templates/freemarker/named.ftl similarity index 100% rename from jersey/src/main/resources/templates/freemarker/named.ftl rename to web-modules/jersey/src/main/resources/templates/freemarker/named.ftl diff --git a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java b/web-modules/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java similarity index 100% rename from jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java rename to web-modules/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java diff --git a/jersey/src/test/java/com/baeldung/jersey/client/listdemo/JerseyListDemoUnitTest.java b/web-modules/jersey/src/test/java/com/baeldung/jersey/client/listdemo/JerseyListDemoUnitTest.java similarity index 100% rename from jersey/src/test/java/com/baeldung/jersey/client/listdemo/JerseyListDemoUnitTest.java rename to web-modules/jersey/src/test/java/com/baeldung/jersey/client/listdemo/JerseyListDemoUnitTest.java diff --git a/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 similarity index 97% rename from jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java rename to web-modules/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java index eff5d5ae6e..92f2e77670 100644 --- a/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 @@ -1,105 +1,105 @@ -package com.baeldung.jersey.exceptionhandling.rest; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.startsWith; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.HashMap; - -import org.glassfish.jersey.server.ResourceConfig; -import org.glassfish.jersey.test.JerseyTest; -import org.glassfish.jersey.test.TestProperties; -import org.junit.jupiter.api.Test; - -import com.baeldung.jersey.exceptionhandling.data.Stock; -import com.baeldung.jersey.exceptionhandling.data.Wallet; -import com.baeldung.jersey.exceptionhandling.rest.exceptions.IllegalArgumentExceptionMapper; -import com.baeldung.jersey.exceptionhandling.rest.exceptions.RestErrorResponse; -import com.baeldung.jersey.exceptionhandling.rest.exceptions.ServerExceptionMapper; - -import jakarta.ws.rs.client.Entity; -import jakarta.ws.rs.client.Invocation; -import jakarta.ws.rs.core.Application; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Response; - -public class StocksResourceIntegrationTest extends JerseyTest { - private static final Entity EMPTY_BODY = Entity.json(""); - private static final Stock STOCK = new Stock("BAEL", 51.57); - private static final String MY_WALLET = "MY-WALLET"; - private static final Wallet WALLET = new Wallet(MY_WALLET); - private static final int INSUFFICIENT_AMOUNT = (int) (Wallet.MIN_CHARGE - 1); - - @Override - protected Application configure() { - final ResourceConfig resourceConfig = new ResourceConfig(); - resourceConfig.register(StocksResource.class); - resourceConfig.register(WalletsResource.class); - resourceConfig.register(IllegalArgumentExceptionMapper.class); - resourceConfig.register(ServerExceptionMapper.class); - resourceConfig.packages("com.baeldung.jersey.exceptionhandling.rest"); - return resourceConfig; - } - - private Invocation.Builder stocks(String path) { - return target("/stocks" + path).request(); - } - - private Invocation.Builder wallets(String path, Object... args) { - return target("/wallets" + String.format(path, args)).request(); - } - - private Entity entity(Object object) { - return Entity.entity(object, MediaType.APPLICATION_JSON_TYPE); - } - - @Test - public void whenMethodNotAllowed_thenCustomMessage() { - Response response = stocks("").get(); - - assertEquals(Response.Status.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus()); - - String content = response.readEntity(String.class); - assertThat(content, containsString(ServerExceptionMapper.HTTP_405_MESSAGE)); - } - - @Test - public void whenTickerNotExists_thenRestErrorResponse() { - Response response = stocks("/TEST").get(); - - assertEquals(Response.Status.EXPECTATION_FAILED.getStatusCode(), response.getStatus()); - - RestErrorResponse content = response.readEntity(RestErrorResponse.class); - assertThat(content.getMessage(), startsWith(IllegalArgumentExceptionMapper.DEFAULT_MESSAGE)); - } - - @Test - public void givenAmountLessThanMinimum_whenAddingToWallet_thenInvalidTradeException() { - wallets("").post(entity(WALLET)); - Response response = wallets("/%s/%d", MY_WALLET, INSUFFICIENT_AMOUNT).put(EMPTY_BODY); - - assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus()); - - String content = response.readEntity(String.class); - assertThat(content, containsString(Wallet.MIN_CHARGE_MSG)); - } - - @Test - public void givenInsifficientFunds_whenBuyingStock_thenWebApplicationException() { - stocks("").post(entity(STOCK)); - wallets("").post(entity(WALLET)); - - Response response = wallets("/%s/buy/%s", MY_WALLET, STOCK.getId()).post(EMPTY_BODY); - assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus()); - - RestErrorResponse content = response.readEntity(RestErrorResponse.class); - assertNotNull(content.getSubject()); - - HashMap subject = (HashMap) content.getSubject(); - assertEquals(subject.get("id"), WALLET.getId()); - assertTrue(WALLET.getBalance() < Wallet.MIN_CHARGE); - } -} +package com.baeldung.jersey.exceptionhandling.rest; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.startsWith; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.HashMap; + +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; +import org.junit.jupiter.api.Test; + +import com.baeldung.jersey.exceptionhandling.data.Stock; +import com.baeldung.jersey.exceptionhandling.data.Wallet; +import com.baeldung.jersey.exceptionhandling.rest.exceptions.IllegalArgumentExceptionMapper; +import com.baeldung.jersey.exceptionhandling.rest.exceptions.RestErrorResponse; +import com.baeldung.jersey.exceptionhandling.rest.exceptions.ServerExceptionMapper; + +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.Invocation; +import jakarta.ws.rs.core.Application; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +public class StocksResourceIntegrationTest extends JerseyTest { + private static final Entity EMPTY_BODY = Entity.json(""); + private static final Stock STOCK = new Stock("BAEL", 51.57); + private static final String MY_WALLET = "MY-WALLET"; + private static final Wallet WALLET = new Wallet(MY_WALLET); + private static final int INSUFFICIENT_AMOUNT = (int) (Wallet.MIN_CHARGE - 1); + + @Override + protected Application configure() { + final ResourceConfig resourceConfig = new ResourceConfig(); + resourceConfig.register(StocksResource.class); + resourceConfig.register(WalletsResource.class); + resourceConfig.register(IllegalArgumentExceptionMapper.class); + resourceConfig.register(ServerExceptionMapper.class); + resourceConfig.packages("com.baeldung.jersey.exceptionhandling.rest"); + return resourceConfig; + } + + private Invocation.Builder stocks(String path) { + return target("/stocks" + path).request(); + } + + private Invocation.Builder wallets(String path, Object... args) { + return target("/wallets" + String.format(path, args)).request(); + } + + private Entity entity(Object object) { + return Entity.entity(object, MediaType.APPLICATION_JSON_TYPE); + } + + @Test + public void whenMethodNotAllowed_thenCustomMessage() { + Response response = stocks("").get(); + + assertEquals(Response.Status.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus()); + + String content = response.readEntity(String.class); + assertThat(content, containsString(ServerExceptionMapper.HTTP_405_MESSAGE)); + } + + @Test + public void whenTickerNotExists_thenRestErrorResponse() { + Response response = stocks("/TEST").get(); + + assertEquals(Response.Status.EXPECTATION_FAILED.getStatusCode(), response.getStatus()); + + RestErrorResponse content = response.readEntity(RestErrorResponse.class); + assertThat(content.getMessage(), startsWith(IllegalArgumentExceptionMapper.DEFAULT_MESSAGE)); + } + + @Test + public void givenAmountLessThanMinimum_whenAddingToWallet_thenInvalidTradeException() { + wallets("").post(entity(WALLET)); + Response response = wallets("/%s/%d", MY_WALLET, INSUFFICIENT_AMOUNT).put(EMPTY_BODY); + + assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus()); + + String content = response.readEntity(String.class); + assertThat(content, containsString(Wallet.MIN_CHARGE_MSG)); + } + + @Test + public void givenInsifficientFunds_whenBuyingStock_thenWebApplicationException() { + stocks("").post(entity(STOCK)); + wallets("").post(entity(WALLET)); + + Response response = wallets("/%s/buy/%s", MY_WALLET, STOCK.getId()).post(EMPTY_BODY); + assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus()); + + RestErrorResponse content = response.readEntity(RestErrorResponse.class); + assertNotNull(content.getSubject()); + + HashMap subject = (HashMap) content.getSubject(); + assertEquals(subject.get("id"), WALLET.getId()); + assertTrue(WALLET.getBalance() < Wallet.MIN_CHARGE); + } +} diff --git a/jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersIntegrationTest.java b/web-modules/jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersIntegrationTest.java similarity index 100% rename from jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersIntegrationTest.java rename to web-modules/jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersIntegrationTest.java diff --git a/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java b/web-modules/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java similarity index 97% rename from jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java rename to web-modules/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java index 97934369e2..5f23209c16 100644 --- a/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java +++ b/web-modules/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java @@ -1,32 +1,32 @@ -package com.baeldung.jersey.server; - -import static org.junit.Assert.assertEquals; - -import org.glassfish.jersey.server.ResourceConfig; -import org.glassfish.jersey.test.JerseyTest; -import org.junit.Test; - -import jakarta.ws.rs.core.Application; -import jakarta.ws.rs.core.HttpHeaders; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Response; - -public class GreetingsResourceIntegrationTest extends JerseyTest { - - @Override - protected Application configure() { - return new ResourceConfig(Greetings.class); - } - - @Test - public void givenGetHiGreeting_whenCorrectRequest_thenResponseIsOkAndContainsHi() { - Response response = target("/greetings/hi").request() - .get(); - - assertEquals("Http Response should be 200: ", Response.Status.OK.getStatusCode(), response.getStatus()); - assertEquals("Http Content-Type should be: ", MediaType.TEXT_HTML, response.getHeaderString(HttpHeaders.CONTENT_TYPE)); - - String content = response.readEntity(String.class); - assertEquals("Content of ressponse is: ", "hi", content); - } -} +package com.baeldung.jersey.server; + +import static org.junit.Assert.assertEquals; + +import org.glassfish.jersey.server.ResourceConfig; +import org.glassfish.jersey.test.JerseyTest; +import org.junit.Test; + +import jakarta.ws.rs.core.Application; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + +public class GreetingsResourceIntegrationTest extends JerseyTest { + + @Override + protected Application configure() { + return new ResourceConfig(Greetings.class); + } + + @Test + public void givenGetHiGreeting_whenCorrectRequest_thenResponseIsOkAndContainsHi() { + Response response = target("/greetings/hi").request() + .get(); + + assertEquals("Http Response should be 200: ", Response.Status.OK.getStatusCode(), response.getStatus()); + assertEquals("Http Content-Type should be: ", MediaType.TEXT_HTML, response.getHeaderString(HttpHeaders.CONTENT_TYPE)); + + String content = response.readEntity(String.class); + assertEquals("Content of ressponse is: ", "hi", content); + } +} diff --git a/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java b/web-modules/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java similarity index 100% rename from jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java rename to web-modules/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java diff --git a/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java b/web-modules/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java similarity index 100% rename from jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java rename to web-modules/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java diff --git a/jsf/.gitignore b/web-modules/jsf/.gitignore similarity index 100% rename from jsf/.gitignore rename to web-modules/jsf/.gitignore diff --git a/jsf/README.md b/web-modules/jsf/README.md similarity index 100% rename from jsf/README.md rename to web-modules/jsf/README.md diff --git a/jsf/pom.xml b/web-modules/jsf/pom.xml similarity index 98% rename from jsf/pom.xml rename to web-modules/jsf/pom.xml index 09dea98f65..2a1c6ad353 100644 --- a/jsf/pom.xml +++ b/web-modules/jsf/pom.xml @@ -9,12 +9,11 @@ com.baeldung - parent-modules + web-modules 1.0.0-SNAPSHOT - javax.annotation javax.annotation-api diff --git a/jsf/src/main/java/com/baeldung/springintegration/config/MainWebAppInitializer.java b/web-modules/jsf/src/main/java/com/baeldung/springintegration/config/MainWebAppInitializer.java similarity index 100% rename from jsf/src/main/java/com/baeldung/springintegration/config/MainWebAppInitializer.java rename to web-modules/jsf/src/main/java/com/baeldung/springintegration/config/MainWebAppInitializer.java diff --git a/jsf/src/main/java/com/baeldung/springintegration/config/SpringCoreConfig.java b/web-modules/jsf/src/main/java/com/baeldung/springintegration/config/SpringCoreConfig.java similarity index 100% rename from jsf/src/main/java/com/baeldung/springintegration/config/SpringCoreConfig.java rename to web-modules/jsf/src/main/java/com/baeldung/springintegration/config/SpringCoreConfig.java diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java b/web-modules/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java similarity index 100% rename from jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java rename to web-modules/jsf/src/main/java/com/baeldung/springintegration/controllers/ELSampleBean.java diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/HelloPFBean.java b/web-modules/jsf/src/main/java/com/baeldung/springintegration/controllers/HelloPFBean.java similarity index 100% rename from jsf/src/main/java/com/baeldung/springintegration/controllers/HelloPFBean.java rename to web-modules/jsf/src/main/java/com/baeldung/springintegration/controllers/HelloPFBean.java diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/HelloPFMBean.java b/web-modules/jsf/src/main/java/com/baeldung/springintegration/controllers/HelloPFMBean.java similarity index 100% rename from jsf/src/main/java/com/baeldung/springintegration/controllers/HelloPFMBean.java rename to web-modules/jsf/src/main/java/com/baeldung/springintegration/controllers/HelloPFMBean.java diff --git a/jsf/src/main/java/com/baeldung/springintegration/controllers/RegistrationBean.java b/web-modules/jsf/src/main/java/com/baeldung/springintegration/controllers/RegistrationBean.java similarity index 100% rename from jsf/src/main/java/com/baeldung/springintegration/controllers/RegistrationBean.java rename to web-modules/jsf/src/main/java/com/baeldung/springintegration/controllers/RegistrationBean.java diff --git a/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAO.java b/web-modules/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAO.java similarity index 100% rename from jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAO.java rename to web-modules/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAO.java diff --git a/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java b/web-modules/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java similarity index 100% rename from jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java rename to web-modules/jsf/src/main/java/com/baeldung/springintegration/dao/UserManagementDAOImpl.java diff --git a/jsf/src/main/resources/logback.xml b/web-modules/jsf/src/main/resources/logback.xml similarity index 100% rename from jsf/src/main/resources/logback.xml rename to web-modules/jsf/src/main/resources/logback.xml diff --git a/jsf/src/main/resources/messages.properties b/web-modules/jsf/src/main/resources/messages.properties similarity index 100% rename from jsf/src/main/resources/messages.properties rename to web-modules/jsf/src/main/resources/messages.properties diff --git a/jsf/src/main/webapp/META-INF/context.xml b/web-modules/jsf/src/main/webapp/META-INF/context.xml similarity index 100% rename from jsf/src/main/webapp/META-INF/context.xml rename to web-modules/jsf/src/main/webapp/META-INF/context.xml diff --git a/jsf/src/main/webapp/WEB-INF/faces-config.xml b/web-modules/jsf/src/main/webapp/WEB-INF/faces-config.xml similarity index 100% rename from jsf/src/main/webapp/WEB-INF/faces-config.xml rename to web-modules/jsf/src/main/webapp/WEB-INF/faces-config.xml diff --git a/jsf/src/main/webapp/el3_intro.xhtml b/web-modules/jsf/src/main/webapp/el3_intro.xhtml similarity index 100% rename from jsf/src/main/webapp/el3_intro.xhtml rename to web-modules/jsf/src/main/webapp/el3_intro.xhtml diff --git a/jsf/src/main/webapp/el_intro.xhtml b/web-modules/jsf/src/main/webapp/el_intro.xhtml similarity index 97% rename from jsf/src/main/webapp/el_intro.xhtml rename to web-modules/jsf/src/main/webapp/el_intro.xhtml index 446647497f..b3e573fb37 100644 --- a/jsf/src/main/webapp/el_intro.xhtml +++ b/web-modules/jsf/src/main/webapp/el_intro.xhtml @@ -1,52 +1,52 @@ - - - - - Baeldung | The EL Intro - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - - - - - -
KeyValue
#{header.key}#{header.value}
- -
-
- - + + + + + Baeldung | The EL Intro + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + + + + + +
KeyValue
#{header.key}#{header.value}
+ +
+
+ + diff --git a/jsf/src/main/webapp/index.xhtml b/web-modules/jsf/src/main/webapp/index.xhtml similarity index 100% rename from jsf/src/main/webapp/index.xhtml rename to web-modules/jsf/src/main/webapp/index.xhtml diff --git a/jsf/src/main/webapp/pf_intro.xhtml b/web-modules/jsf/src/main/webapp/pf_intro.xhtml similarity index 100% rename from jsf/src/main/webapp/pf_intro.xhtml rename to web-modules/jsf/src/main/webapp/pf_intro.xhtml diff --git a/jsf/src/main/webapp/pfm_intro.xhtml b/web-modules/jsf/src/main/webapp/pfm_intro.xhtml similarity index 100% rename from jsf/src/main/webapp/pfm_intro.xhtml rename to web-modules/jsf/src/main/webapp/pfm_intro.xhtml diff --git a/web-modules/pom.xml b/web-modules/pom.xml index 57810f90de..6119316a62 100644 --- a/web-modules/pom.xml +++ b/web-modules/pom.xml @@ -22,10 +22,13 @@ jakarta-ee + java-takes javax-servlets javax-servlets-2 jee-7 + jersey jooby + jsf linkrest @@ -33,10 +36,12 @@ ratpack resteasy restx + rome spark-java struts-2 vraptor wicket + diff --git a/web-modules/rome/README.md b/web-modules/rome/README.md new file mode 100644 index 0000000000..e5cbbbb373 --- /dev/null +++ b/web-modules/rome/README.md @@ -0,0 +1,8 @@ +## RSS ROME + +This module contains articles about Rss with Rome. + +### Relevant Articles + +- [Quick Guide to RSS with Rome](https://www.baeldung.com/rome-rss) + diff --git a/web-modules/rome/pom.xml b/web-modules/rome/pom.xml new file mode 100644 index 0000000000..cfcdf4721c --- /dev/null +++ b/web-modules/rome/pom.xml @@ -0,0 +1,31 @@ + + + 4.0.0 + rome + 0.1-SNAPSHOT + rome + + + com.baeldung + web-modules + 1.0.0-SNAPSHOT + + + + + + + rome + rome + ${rome.version} + + + + + + 1.0 + + + \ No newline at end of file diff --git a/libraries-4/src/main/java/com/baeldung/rome/RSSRomeExample.java b/web-modules/rome/src/main/java/com/baeldung/rome/RSSRomeExample.java similarity index 85% rename from libraries-4/src/main/java/com/baeldung/rome/RSSRomeExample.java rename to web-modules/rome/src/main/java/com/baeldung/rome/RSSRomeExample.java index 66a9e0ebce..b5e4569270 100644 --- a/libraries-4/src/main/java/com/baeldung/rome/RSSRomeExample.java +++ b/web-modules/rome/src/main/java/com/baeldung/rome/RSSRomeExample.java @@ -1,11 +1,5 @@ package com.baeldung.rome; -import com.sun.syndication.feed.synd.*; -import com.sun.syndication.io.FeedException; -import com.sun.syndication.io.SyndFeedInput; -import com.sun.syndication.io.SyndFeedOutput; -import com.sun.syndication.io.XmlReader; - import java.io.FileWriter; import java.io.IOException; import java.io.Writer; @@ -14,6 +8,19 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import com.sun.syndication.feed.synd.SyndCategory; +import com.sun.syndication.feed.synd.SyndCategoryImpl; +import com.sun.syndication.feed.synd.SyndContent; +import com.sun.syndication.feed.synd.SyndContentImpl; +import com.sun.syndication.feed.synd.SyndEntry; +import com.sun.syndication.feed.synd.SyndEntryImpl; +import com.sun.syndication.feed.synd.SyndFeed; +import com.sun.syndication.feed.synd.SyndFeedImpl; +import com.sun.syndication.io.FeedException; +import com.sun.syndication.io.SyndFeedInput; +import com.sun.syndication.io.SyndFeedOutput; +import com.sun.syndication.io.XmlReader; + public class RSSRomeExample { public static void main(String[] args) throws IOException, FeedException { diff --git a/web-modules/rome/src/main/resources/logback.xml b/web-modules/rome/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/web-modules/rome/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/xml-2/README.md b/xml-2/README.md index a6762f2840..1075f34e1f 100644 --- a/xml-2/README.md +++ b/xml-2/README.md @@ -10,3 +10,5 @@ This module contains articles about eXtensible Markup Language (XML) - [Convert an XML Object to a String in Java](https://www.baeldung.com/java-convert-xml-object-string) - [Convert String Containing XML to org.w3c.dom.Document](https://www.baeldung.com/java-convert-string-xml-dom) - [How to Parse XML to HashMap in Java](https://www.baeldung.com/java-xml-read-into-hashmap) +- [Convert an XML File to CSV File](https://www.baeldung.com/java-convert-xml-csv) +- - More articles: [[prev -->]](../xml) \ No newline at end of file diff --git a/xml-2/pom.xml b/xml-2/pom.xml index ccb84e1687..e1c7859daa 100644 --- a/xml-2/pom.xml +++ b/xml-2/pom.xml @@ -59,12 +59,12 @@ org.apache.xmlbeans xmlbeans - 5.0.2 + ${xmlbeans.version} org.apache.logging.log4j log4j-core - 2.12.4 + ${log4j-core.version}
@@ -78,8 +78,8 @@ + org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} org.apache.maven.plugins @@ -94,6 +94,8 @@ 1.89 1.4.18 2.3.3 + 5.0.2 + 2.12.4 diff --git a/xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java b/xml-2/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java similarity index 100% rename from xml/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java rename to xml-2/src/main/java/com/baeldung/xml/xml2csv/Xml2CsvExample.java diff --git a/xml/src/main/resources/xml2csv/data.xml b/xml-2/src/main/resources/xml2csv/data.xml similarity index 100% rename from xml/src/main/resources/xml2csv/data.xml rename to xml-2/src/main/resources/xml2csv/data.xml diff --git a/xml/src/main/resources/xml2csv/style.xsl b/xml-2/src/main/resources/xml2csv/style.xsl similarity index 100% rename from xml/src/main/resources/xml2csv/style.xsl rename to xml-2/src/main/resources/xml2csv/style.xsl diff --git a/xml-2/src/test/java/com/baeldung/xml/json2xml/JsonToXmlUnitTest.java b/xml-2/src/test/java/com/baeldung/xml/json2xml/JsonToXmlUnitTest.java index 6c8486f14b..275a734b28 100644 --- a/xml-2/src/test/java/com/baeldung/xml/json2xml/JsonToXmlUnitTest.java +++ b/xml-2/src/test/java/com/baeldung/xml/json2xml/JsonToXmlUnitTest.java @@ -41,15 +41,15 @@ public class JsonToXmlUnitTest { xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true); xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_1_1, true); String xmlString = xmlMapper.writer().withRootName("root").withDefaultPrettyPrinter().writeValueAsString(jsonNode); - Assertions.assertEquals("\n" + - "\n" + - " John\n" + - " 20\n" + - "
\n" + - " Wall Street\n" + - " New York\n" + - "
\n" + - "
\n", xmlString); + Assertions.assertEquals("" + System.lineSeparator() + + "" + System.lineSeparator() + + " John" + System.lineSeparator() + + " 20" + System.lineSeparator() + + "
" + System.lineSeparator() + + " Wall Street" + System.lineSeparator() + + " New York" + System.lineSeparator() + + "
" + System.lineSeparator() + + "
" + System.lineSeparator(), xmlString); } @Test diff --git a/xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java b/xml-2/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java similarity index 100% rename from xml/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java rename to xml-2/src/test/java/com/baeldung/xml/xml2csv/Xml2CsvExampleUnitTest.java diff --git a/xml/README.md b/xml/README.md index 16942c6836..be12640252 100644 --- a/xml/README.md +++ b/xml/README.md @@ -13,3 +13,4 @@ This module contains articles about eXtensible Markup Language (XML) - [Parsing an XML File Using StAX](https://www.baeldung.com/java-stax) - [Parsing an XML File Using SAX Parser](https://www.baeldung.com/java-sax-parser) - [Remove HTML Tags Using Java](https://www.baeldung.com/java-remove-html-tags) +- More articles: [[next -->]](../xml-2)