From ef44b839eab33833e9dd61221f2cc53814f58827 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 10 Feb 2024 18:53:37 -0500 Subject: [PATCH 01/59] BAEL-7374 - First Cut --- .../KafaConsumeLastNMessagesLiveTest.java | 2 - spring-kafka-3/pom.xml | 5 + .../kafka/start/stop/consumer/Constants.java | 8 ++ .../stop/consumer/KafkaConsumerConfig.java | 42 +++++++ .../consumer/KafkaListenerControlService.java | 29 +++++ .../StartStopConsumerApplication.java | 12 ++ .../kafka/start/stop/consumer/UserEvent.java | 28 +++++ .../stop/consumer/UserEventListener.java | 21 ++++ .../start/stop/consumer/UserEventStore.java | 23 ++++ .../StartStopConsumerTest.java | 109 ++++++++++++++++++ 10 files changed, 277 insertions(+), 2 deletions(-) create mode 100644 spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java create mode 100644 spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaConsumerConfig.java create mode 100644 spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaListenerControlService.java create mode 100644 spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java create mode 100644 spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java create mode 100644 spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java create mode 100644 spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventStore.java create mode 100644 spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerTest.java diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessagesLiveTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessagesLiveTest.java index b92f65ca5a..f631c1a85e 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessagesLiveTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessagesLiveTest.java @@ -17,13 +17,11 @@ import org.testcontainers.containers.KafkaContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; - import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutionException; - import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/spring-kafka-3/pom.xml b/spring-kafka-3/pom.xml index 894eab2576..c5db336e84 100644 --- a/spring-kafka-3/pom.xml +++ b/spring-kafka-3/pom.xml @@ -50,6 +50,11 @@ ${awaitility.version} test + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java new file mode 100644 index 0000000000..71e453fa43 --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java @@ -0,0 +1,8 @@ +package com.baeldung.spring.kafka.start.stop.consumer; + +public class Constants { + public static final String MULTI_PARTITION_TOPIC = "multi_partition_topic"; + public static final int MULTIPLE_PARTITIONS = 5; + public static final short REPLICATION_FACTOR = 1; + public static final String LISTENER_ID = "listener-id-1"; +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaConsumerConfig.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaConsumerConfig.java new file mode 100644 index 0000000000..21f6270bca --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaConsumerConfig.java @@ -0,0 +1,42 @@ +package com.baeldung.spring.kafka.start.stop.consumer; + +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.annotation.EnableKafka; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.support.serializer.JsonDeserializer; + +import java.util.HashMap; +import java.util.Map; + +@EnableKafka +@Configuration +public class KafkaConsumerConfig { + + @Value("${spring.kafka.bootstrap-servers}") + private String bootstrapServers; + + @Bean + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory() { + ConcurrentKafkaListenerContainerFactory factory = + new ConcurrentKafkaListenerContainerFactory<>(); + factory.setConsumerFactory(consumerFactory()); + return factory; + } + + @Bean + public DefaultKafkaConsumerFactory consumerFactory() { + Map props = new HashMap<>(); + props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); + props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); + props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + props.put(JsonDeserializer.TRUSTED_PACKAGES, "com.baeldung.spring.kafka.start.stop.consumer"); + return new DefaultKafkaConsumerFactory<>(props, new StringDeserializer(), + new JsonDeserializer<>(UserEvent.class)); + } +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaListenerControlService.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaListenerControlService.java new file mode 100644 index 0000000000..259c461b4a --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaListenerControlService.java @@ -0,0 +1,29 @@ +package com.baeldung.spring.kafka.start.stop.consumer; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.config.KafkaListenerEndpointRegistry; +import org.springframework.kafka.listener.MessageListenerContainer; +import org.springframework.stereotype.Service; + +@Service +public class KafkaListenerControlService { + + @Autowired + private KafkaListenerEndpointRegistry registry; + + // Method to start a listener + public void startListener(String listenerId) { + MessageListenerContainer listenerContainer = registry.getListenerContainer(listenerId); + if (listenerContainer != null && !listenerContainer.isRunning()) { + listenerContainer.start(); + } + } + + // Method to stop a listener + public void stopListener(String listenerId) { + MessageListenerContainer listenerContainer = registry.getListenerContainer(listenerId); + if (listenerContainer != null && listenerContainer.isRunning()) { + listenerContainer.stop(); + } + } +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java new file mode 100644 index 0000000000..c4461b9388 --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.kafka.start.stop.consumer; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class StartStopConsumerApplication { + + public static void main(String[] args) { + SpringApplication.run(com.baeldung.spring.kafka.deserialization.exception.Application.class, args); + } + +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java new file mode 100644 index 0000000000..1c7a7d35c8 --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java @@ -0,0 +1,28 @@ +package com.baeldung.spring.kafka.start.stop.consumer; + +public class UserEvent { + private String userEventId; + private long eventNanoTime; + + public UserEvent(){} + + public UserEvent(String userEventId) { + this.userEventId = userEventId; + } + + public String getUserEventId() { + return userEventId; + } + + public void setUserEventId(String userEventId) { + this.userEventId = userEventId; + } + + public long getEventNanoTime() { + return eventNanoTime; + } + + public void setEventNanoTime(long eventNanoTime) { + this.eventNanoTime = eventNanoTime; + } +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java new file mode 100644 index 0000000000..d35828211e --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.kafka.start.stop.consumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.kafka.annotation.KafkaListener; +import org.springframework.stereotype.Component; + +@Component +public class UserEventListener { + private static final Logger logger = LoggerFactory.getLogger(UserEventListener.class); + + @Autowired + UserEventStore userEventStore; + + @KafkaListener(id = Constants.LISTENER_ID, topics = Constants.MULTI_PARTITION_TOPIC, groupId = "test-group", + containerFactory = "kafkaListenerContainerFactory", autoStartup = "false") + public void userEventListener(UserEvent userEvent) { + logger.info("Received UserEvent: " + userEvent.getUserEventId() + ", Time: " + userEvent.getEventNanoTime()); + userEventStore.addUserEvent(userEvent); + } +} diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventStore.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventStore.java new file mode 100644 index 0000000000..e0ccab20bb --- /dev/null +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventStore.java @@ -0,0 +1,23 @@ +package com.baeldung.spring.kafka.start.stop.consumer; + +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; + +@Component +public class UserEventStore { + private final List userEvents = new ArrayList<>(); + + public void addUserEvent(UserEvent userEvent){ + userEvents.add(userEvent); + } + + public List getUserEvents(){ + return userEvents; + } + + public void clearUserEvents(){ + this.userEvents.clear(); + } +} diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerTest.java new file mode 100644 index 0000000000..7dad372737 --- /dev/null +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerTest.java @@ -0,0 +1,109 @@ +package com.baeldung.spring.kafka.startstopconsumer; + +import com.baeldung.spring.kafka.start.stop.consumer.*; +import org.apache.kafka.clients.admin.Admin; +import org.apache.kafka.clients.admin.AdminClientConfig; +import org.apache.kafka.clients.admin.NewTopic; +import org.apache.kafka.clients.producer.KafkaProducer; +import org.apache.kafka.clients.producer.ProducerConfig; +import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.clients.producer.RecordMetadata; +import org.apache.kafka.common.serialization.LongSerializer; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.kafka.support.serializer.JsonSerializer; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.containers.KafkaContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.shaded.com.google.common.collect.ImmutableList; +import org.testcontainers.utility.DockerImageName; +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; + + +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +@Testcontainers +@SpringBootTest(classes = StartStopConsumerApplication.class) +public class StartStopConsumerTest { + + private static KafkaProducer producer; + + private static final Logger logger = LoggerFactory.getLogger(StartStopConsumerTest.class); + + @Container + private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); + + @Autowired + KafkaListenerControlService kafkaListenerControlService; + + @Autowired + UserEventStore userEventStore; + + @DynamicPropertySource + static void setProps(DynamicPropertyRegistry registry) { + registry.add("spring.kafka.bootstrap-servers", KAFKA_CONTAINER::getBootstrapServers); + } + + @BeforeAll + static void setup() throws ExecutionException, InterruptedException { + KAFKA_CONTAINER.addExposedPort(9092); + + Properties adminProperties = new Properties(); + adminProperties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + + Properties producerProperties = new Properties(); + producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); + producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); + producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class.getName()); + Admin admin = Admin.create(adminProperties); + producer = new KafkaProducer<>(producerProperties); + admin.createTopics(ImmutableList.of(new NewTopic(Constants.MULTI_PARTITION_TOPIC, Constants.MULTIPLE_PARTITIONS, Constants.REPLICATION_FACTOR))) + .all() + .get(); + } + + @AfterAll + static void destroy() { + KAFKA_CONTAINER.stop(); + } + + @Test + void processMessages_whenListenerIsRestarted_thenCorrectNumberOfMessagesAreConsumed() throws ExecutionException, InterruptedException { + kafkaListenerControlService.startListener(Constants.LISTENER_ID); + + //Verification that listener has started. + UserEvent startUserEventTest = new UserEvent(UUID.randomUUID().toString()); + startUserEventTest.setEventNanoTime(System.nanoTime()); + producer.send(new ProducerRecord<>(Constants.MULTI_PARTITION_TOPIC, startUserEventTest)); + await().untilAsserted(() -> assertEquals(1, this.userEventStore.getUserEvents().size())); + this.userEventStore.clearUserEvents(); + + for (long count = 1; count <= 10; count++) { + UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); + userEvent.setEventNanoTime(System.nanoTime()); + Future future = producer.send(new ProducerRecord<>(Constants.MULTI_PARTITION_TOPIC, userEvent)); + RecordMetadata metadata = future.get(); + if (count == 4) { + await().untilAsserted(() -> assertEquals(4, this.userEventStore.getUserEvents().size())); + this.kafkaListenerControlService.stopListener(Constants.LISTENER_ID); + this.userEventStore.clearUserEvents(); + } + logger.info("User Event ID: " + userEvent.getUserEventId() + ", Partition : " + metadata.partition()); + } + assertEquals(0, this.userEventStore.getUserEvents().size()); + kafkaListenerControlService.startListener(Constants.LISTENER_ID); + await().untilAsserted(() -> assertEquals(6, this.userEventStore.getUserEvents().size())); + kafkaListenerControlService.stopListener(Constants.LISTENER_ID); + } +} \ No newline at end of file From 2e750893590fd89a6478267cc574421ff5405a48 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 10 Feb 2024 19:06:16 -0500 Subject: [PATCH 02/59] BAEL-7374 - PR Build Failure --- ...tStopConsumerTest.java => StartStopConsumerUnitTest.java} | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) rename spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/{StartStopConsumerTest.java => StartStopConsumerUnitTest.java} (97%) diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java similarity index 97% rename from spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerTest.java rename to spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java index 7dad372737..fb557ec2b9 100644 --- a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerTest.java +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java @@ -31,15 +31,14 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; @Testcontainers @SpringBootTest(classes = StartStopConsumerApplication.class) -public class StartStopConsumerTest { +public class StartStopConsumerUnitTest { private static KafkaProducer producer; - private static final Logger logger = LoggerFactory.getLogger(StartStopConsumerTest.class); + private static final Logger logger = LoggerFactory.getLogger(StartStopConsumerUnitTest.class); @Container private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); From 45315f4f48ffef2ad323082cc07f3721cc1d5109 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 10 Feb 2024 19:23:25 -0500 Subject: [PATCH 03/59] BAEL-7374 - Removed reduntant jackson package --- spring-kafka-3/pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/spring-kafka-3/pom.xml b/spring-kafka-3/pom.xml index c5db336e84..894eab2576 100644 --- a/spring-kafka-3/pom.xml +++ b/spring-kafka-3/pom.xml @@ -50,11 +50,6 @@ ${awaitility.version} test - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - From 3b5e91b0dd38bce9708a6cebf272af2d9d205db4 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 10 Feb 2024 19:34:06 -0500 Subject: [PATCH 04/59] BAEL-7374 - Code clean Up --- .../StartStopConsumerUnitTest.java | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java index fb557ec2b9..20a78f0251 100644 --- a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java @@ -1,16 +1,15 @@ package com.baeldung.spring.kafka.startstopconsumer; import com.baeldung.spring.kafka.start.stop.consumer.*; -import org.apache.kafka.clients.admin.Admin; -import org.apache.kafka.clients.admin.AdminClientConfig; -import org.apache.kafka.clients.admin.NewTopic; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.serialization.LongSerializer; +import org.awaitility.Awaitility; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,8 +21,10 @@ import org.springframework.test.context.DynamicPropertySource; import org.testcontainers.containers.KafkaContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import org.testcontainers.shaded.com.google.common.collect.ImmutableList; import org.testcontainers.utility.DockerImageName; + +import static java.time.Duration.ofMillis; +import static java.time.Duration.ofSeconds; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -55,21 +56,14 @@ public class StartStopConsumerUnitTest { } @BeforeAll - static void setup() throws ExecutionException, InterruptedException { - KAFKA_CONTAINER.addExposedPort(9092); - - Properties adminProperties = new Properties(); - adminProperties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); - + static void beforeAll() { Properties producerProperties = new Properties(); producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers()); producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, LongSerializer.class.getName()); producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class.getName()); - Admin admin = Admin.create(adminProperties); producer = new KafkaProducer<>(producerProperties); - admin.createTopics(ImmutableList.of(new NewTopic(Constants.MULTI_PARTITION_TOPIC, Constants.MULTIPLE_PARTITIONS, Constants.REPLICATION_FACTOR))) - .all() - .get(); + Awaitility.setDefaultTimeout(ofSeconds(5)); + Awaitility.setDefaultPollInterval(ofMillis(50)); } @AfterAll @@ -77,6 +71,11 @@ public class StartStopConsumerUnitTest { KAFKA_CONTAINER.stop(); } + @BeforeEach + void beforeEach() { + this.userEventStore.clearUserEvents(); + } + @Test void processMessages_whenListenerIsRestarted_thenCorrectNumberOfMessagesAreConsumed() throws ExecutionException, InterruptedException { kafkaListenerControlService.startListener(Constants.LISTENER_ID); From 21c3d8fdcc3dbdd3403c470eac7b4bfb650983cb Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 10 Feb 2024 21:01:53 -0500 Subject: [PATCH 05/59] BAEL-7374 - Removed unit test --- .../kafka/startstopconsumer/StartStopConsumerUnitTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java index 20a78f0251..500962311e 100644 --- a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java @@ -76,7 +76,7 @@ public class StartStopConsumerUnitTest { this.userEventStore.clearUserEvents(); } - @Test + /*@Test void processMessages_whenListenerIsRestarted_thenCorrectNumberOfMessagesAreConsumed() throws ExecutionException, InterruptedException { kafkaListenerControlService.startListener(Constants.LISTENER_ID); @@ -103,5 +103,5 @@ public class StartStopConsumerUnitTest { kafkaListenerControlService.startListener(Constants.LISTENER_ID); await().untilAsserted(() -> assertEquals(6, this.userEventStore.getUserEvents().size())); kafkaListenerControlService.stopListener(Constants.LISTENER_ID); - } + }*/ } \ No newline at end of file From 48a149956ec33e20b622fdb48a459635ef158aa4 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 10 Feb 2024 21:17:49 -0500 Subject: [PATCH 06/59] BAEL-7374 - Added Back Unit test --- .../kafka/startstopconsumer/StartStopConsumerUnitTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java index 500962311e..20a78f0251 100644 --- a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java @@ -76,7 +76,7 @@ public class StartStopConsumerUnitTest { this.userEventStore.clearUserEvents(); } - /*@Test + @Test void processMessages_whenListenerIsRestarted_thenCorrectNumberOfMessagesAreConsumed() throws ExecutionException, InterruptedException { kafkaListenerControlService.startListener(Constants.LISTENER_ID); @@ -103,5 +103,5 @@ public class StartStopConsumerUnitTest { kafkaListenerControlService.startListener(Constants.LISTENER_ID); await().untilAsserted(() -> assertEquals(6, this.userEventStore.getUserEvents().size())); kafkaListenerControlService.stopListener(Constants.LISTENER_ID); - }*/ + } } \ No newline at end of file From 8b560721b621e25906f164e730fc66cd33d50fc5 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 10 Feb 2024 21:29:51 -0500 Subject: [PATCH 07/59] BAEL-7374 - Application class --- .../kafka/start/stop/consumer/StartStopConsumerApplication.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java index c4461b9388..9a2860bf1e 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java @@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; public class StartStopConsumerApplication { public static void main(String[] args) { - SpringApplication.run(com.baeldung.spring.kafka.deserialization.exception.Application.class, args); + SpringApplication.run(StartStopConsumerApplication.class, args); } } From 7a51fa8e80b9b8d516368418ff8211f54d01c95c Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 11 Feb 2024 11:11:35 -0500 Subject: [PATCH 08/59] BAEL-7374 - Build Failure Fix --- .../kafka/startstopconsumer/StartStopConsumerUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java index 20a78f0251..559be3264e 100644 --- a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java @@ -42,7 +42,7 @@ public class StartStopConsumerUnitTest { private static final Logger logger = LoggerFactory.getLogger(StartStopConsumerUnitTest.class); @Container - private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); + private static KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); @Autowired KafkaListenerControlService kafkaListenerControlService; From 3b4d456e3ae294c69dd3f229eb4a7ae708e8f85c Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sun, 11 Feb 2024 11:19:20 -0500 Subject: [PATCH 09/59] BAEL-7374 - Incoorect File modification --- .../com/baeldung/kafka/KafaConsumeLastNMessagesLiveTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessagesLiveTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessagesLiveTest.java index f631c1a85e..b92f65ca5a 100644 --- a/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessagesLiveTest.java +++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/KafaConsumeLastNMessagesLiveTest.java @@ -17,11 +17,13 @@ import org.testcontainers.containers.KafkaContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; + import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutionException; + import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; From 36f3e32ff67e2a759b7859ab2c92f848966b6602 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Tue, 13 Feb 2024 09:15:00 -0500 Subject: [PATCH 10/59] BAEL-7374 - Renamed to live test --- ...pConsumerUnitTest.java => StartStopConsumerLiveTest.java} | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) rename spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/{StartStopConsumerUnitTest.java => StartStopConsumerLiveTest.java} (96%) diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java similarity index 96% rename from spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java rename to spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java index 559be3264e..298aee513c 100644 --- a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerUnitTest.java +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java @@ -33,13 +33,14 @@ import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; +// This live test needs a Docker Daemon running so that a kafka container can be created @Testcontainers @SpringBootTest(classes = StartStopConsumerApplication.class) -public class StartStopConsumerUnitTest { +public class StartStopConsumerLiveTest { private static KafkaProducer producer; - private static final Logger logger = LoggerFactory.getLogger(StartStopConsumerUnitTest.class); + private static final Logger logger = LoggerFactory.getLogger(StartStopConsumerLiveTest.class); @Container private static KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest")); From ec88f944279bd1db3024c1b1a61df17320da6868 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 17 Feb 2024 09:15:50 -0500 Subject: [PATCH 11/59] BAEL-7374 - Incorporated Review comments for PR --- .../kafka/start/stop/consumer/Constants.java | 4 ++-- .../consumer/KafkaListenerControlService.java | 2 -- .../consumer/StartStopConsumerApplication.java | 1 + .../kafka/start/stop/consumer/UserEvent.java | 15 +++++---------- .../start/stop/consumer/UserEventListener.java | 4 +++- .../kafka/start/stop/consumer/UserEventStore.java | 7 ++++--- .../StartStopConsumerLiveTest.java | 2 -- 7 files changed, 15 insertions(+), 20 deletions(-) diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java index 71e453fa43..bc17c368d9 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java @@ -1,8 +1,8 @@ package com.baeldung.spring.kafka.start.stop.consumer; public class Constants { + public static final String MULTI_PARTITION_TOPIC = "multi_partition_topic"; - public static final int MULTIPLE_PARTITIONS = 5; - public static final short REPLICATION_FACTOR = 1; + public static final String LISTENER_ID = "listener-id-1"; } diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaListenerControlService.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaListenerControlService.java index 259c461b4a..64f7158a49 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaListenerControlService.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaListenerControlService.java @@ -11,7 +11,6 @@ public class KafkaListenerControlService { @Autowired private KafkaListenerEndpointRegistry registry; - // Method to start a listener public void startListener(String listenerId) { MessageListenerContainer listenerContainer = registry.getListenerContainer(listenerId); if (listenerContainer != null && !listenerContainer.isRunning()) { @@ -19,7 +18,6 @@ public class KafkaListenerControlService { } } - // Method to stop a listener public void stopListener(String listenerId) { MessageListenerContainer listenerContainer = registry.getListenerContainer(listenerId); if (listenerContainer != null && listenerContainer.isRunning()) { diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java index 9a2860bf1e..51893ea64a 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java @@ -1,4 +1,5 @@ package com.baeldung.spring.kafka.start.stop.consumer; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java index 1c7a7d35c8..fe95a8c4ad 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java @@ -1,10 +1,12 @@ package com.baeldung.spring.kafka.start.stop.consumer; public class UserEvent { - private String userEventId; - private long eventNanoTime; - public UserEvent(){} + private String userEventId; + + + public UserEvent() { + } public UserEvent(String userEventId) { this.userEventId = userEventId; @@ -18,11 +20,4 @@ public class UserEvent { this.userEventId = userEventId; } - public long getEventNanoTime() { - return eventNanoTime; - } - - public void setEventNanoTime(long eventNanoTime) { - this.eventNanoTime = eventNanoTime; - } } diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java index d35828211e..66fb861cdd 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java @@ -1,4 +1,5 @@ package com.baeldung.spring.kafka.start.stop.consumer; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -7,6 +8,7 @@ import org.springframework.stereotype.Component; @Component public class UserEventListener { + private static final Logger logger = LoggerFactory.getLogger(UserEventListener.class); @Autowired @@ -15,7 +17,7 @@ public class UserEventListener { @KafkaListener(id = Constants.LISTENER_ID, topics = Constants.MULTI_PARTITION_TOPIC, groupId = "test-group", containerFactory = "kafkaListenerContainerFactory", autoStartup = "false") public void userEventListener(UserEvent userEvent) { - logger.info("Received UserEvent: " + userEvent.getUserEventId() + ", Time: " + userEvent.getEventNanoTime()); + logger.info("Received UserEvent: " + userEvent.getUserEventId()); userEventStore.addUserEvent(userEvent); } } diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventStore.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventStore.java index e0ccab20bb..071b39c7a3 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventStore.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventStore.java @@ -7,17 +7,18 @@ import java.util.List; @Component public class UserEventStore { + private final List userEvents = new ArrayList<>(); - public void addUserEvent(UserEvent userEvent){ + public void addUserEvent(UserEvent userEvent) { userEvents.add(userEvent); } - public List getUserEvents(){ + public List getUserEvents() { return userEvents; } - public void clearUserEvents(){ + public void clearUserEvents() { this.userEvents.clear(); } } diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java index 298aee513c..6405f75f91 100644 --- a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java @@ -83,14 +83,12 @@ public class StartStopConsumerLiveTest { //Verification that listener has started. UserEvent startUserEventTest = new UserEvent(UUID.randomUUID().toString()); - startUserEventTest.setEventNanoTime(System.nanoTime()); producer.send(new ProducerRecord<>(Constants.MULTI_PARTITION_TOPIC, startUserEventTest)); await().untilAsserted(() -> assertEquals(1, this.userEventStore.getUserEvents().size())); this.userEventStore.clearUserEvents(); for (long count = 1; count <= 10; count++) { UserEvent userEvent = new UserEvent(UUID.randomUUID().toString()); - userEvent.setEventNanoTime(System.nanoTime()); Future future = producer.send(new ProducerRecord<>(Constants.MULTI_PARTITION_TOPIC, userEvent)); RecordMetadata metadata = future.get(); if (count == 4) { From 3ba11fcdba073e41d4a0129a6237c0909702bc63 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 17 Feb 2024 12:45:01 -0500 Subject: [PATCH 12/59] BAEL-7374 - Event Listener method rename --- .../spring/kafka/start/stop/consumer/UserEventListener.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java index 66fb861cdd..f6235a05f5 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java @@ -16,7 +16,7 @@ public class UserEventListener { @KafkaListener(id = Constants.LISTENER_ID, topics = Constants.MULTI_PARTITION_TOPIC, groupId = "test-group", containerFactory = "kafkaListenerContainerFactory", autoStartup = "false") - public void userEventListener(UserEvent userEvent) { + public void processUserEvent(UserEvent userEvent) { logger.info("Received UserEvent: " + userEvent.getUserEventId()); userEventStore.addUserEvent(userEvent); } From a40222a45adebf61b52927bfe5b006f7fba72a90 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Mon, 26 Feb 2024 07:08:41 -0500 Subject: [PATCH 13/59] BAEL-7374 - Code formatting issue --- .../spring/kafka/start/stop/consumer/UserEventListener.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java index f6235a05f5..d6338d7f3a 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java @@ -15,7 +15,7 @@ public class UserEventListener { UserEventStore userEventStore; @KafkaListener(id = Constants.LISTENER_ID, topics = Constants.MULTI_PARTITION_TOPIC, groupId = "test-group", - containerFactory = "kafkaListenerContainerFactory", autoStartup = "false") + containerFactory = "kafkaListenerContainerFactory", autoStartup = "false") public void processUserEvent(UserEvent userEvent) { logger.info("Received UserEvent: " + userEvent.getUserEventId()); userEventStore.addUserEvent(userEvent); From 43a168a5253467b01ab700d14e1a10072ca7b996 Mon Sep 17 00:00:00 2001 From: saikat Date: Wed, 28 Feb 2024 14:52:16 +0530 Subject: [PATCH 14/59] Add two level of caching --- .../caching/multicache/CacheConfig.java | 90 +++++++++++++++++++ .../baeldung/caching/multicache/Customer.java | 21 +++++ .../multicache/CustomerCacheInterceptor.java | 30 +++++++ .../multicache/CustomerController.java | 22 +++++ .../multicache/CustomerRepository.java | 44 +++++++++ .../caching/multicache/CustomerService.java | 25 ++++++ .../MultipleCachingApplication.java | 12 +++ .../src/main/resources/application.properties | 5 +- 8 files changed, 247 insertions(+), 2 deletions(-) create mode 100644 spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java create mode 100644 spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/Customer.java create mode 100644 spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerCacheInterceptor.java create mode 100644 spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerController.java create mode 100644 spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerRepository.java create mode 100644 spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerService.java create mode 100644 spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/MultipleCachingApplication.java diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java new file mode 100644 index 0000000000..29419f4c12 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java @@ -0,0 +1,90 @@ +package com.baeldung.caching.multicache; + +import com.github.benmanes.caffeine.cache.Caffeine; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.AnnotationCacheOperationSource; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.cache.caffeine.CaffeineCache; +import org.springframework.cache.interceptor.CacheInterceptor; +import org.springframework.cache.interceptor.CacheOperationSource; +import org.springframework.cache.support.SimpleCacheManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.connection.RedisStandaloneConfiguration; +import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; +import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; + +import java.time.Duration; +import java.util.Arrays; + +@Configuration +@EnableCaching +public class CacheConfig { + + @Value("${spring.redis.host}") + private String redisHost; + + @Value("${spring.redis.port}") + private int redisPort; + + @Bean + public CaffeineCache caffeineCacheConfig() { + return new CaffeineCache("customerCache", Caffeine.newBuilder() + .expireAfterWrite(Duration.ofMinutes(1)) + .initialCapacity(1) + .maximumSize(2000) + .build()); + } + + @Bean + @Primary + public CacheManager caffeineCacheManager() { + SimpleCacheManager manager = new SimpleCacheManager(); + manager.setCaches(Arrays.asList( + caffeineCacheConfig())); + return manager; + } + + @Bean + public CacheManager redisCacheManager() { + return RedisCacheManager.RedisCacheManagerBuilder + .fromConnectionFactory(redisConnectionFactory()) + .withCacheConfiguration("customerCache", cacheConfiguration()) + .build(); + } + + @Bean + public RedisConnectionFactory redisConnectionFactory() { + RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); + redisStandaloneConfiguration.setHostName(redisHost); + redisStandaloneConfiguration.setPort(redisPort); + return new LettuceConnectionFactory(redisStandaloneConfiguration); + } + + @Bean + public RedisCacheConfiguration cacheConfiguration() { + return RedisCacheConfiguration.defaultCacheConfig() + .entryTtl(Duration.ofMinutes(60)) + .disableCachingNullValues() + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); + } + + @Bean + public CacheInterceptor cacheInterceptor() { + CacheInterceptor interceptor = new CustomerCacheInterceptor(caffeineCacheManager()); + interceptor.setCacheOperationSources(cacheOperationSource()); + return interceptor; + } + + @Bean + public CacheOperationSource cacheOperationSource() { + return new AnnotationCacheOperationSource(); + } + +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/Customer.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/Customer.java new file mode 100644 index 0000000000..4632799a1c --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/Customer.java @@ -0,0 +1,21 @@ +package com.baeldung.caching.multicache; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.io.Serializable; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@Setter +public class Customer implements Serializable { + + private String id; + + private String name; + + private String email; +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerCacheInterceptor.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerCacheInterceptor.java new file mode 100644 index 0000000000..2ca1d2b2de --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerCacheInterceptor.java @@ -0,0 +1,30 @@ +package com.baeldung.caching.multicache; + +import org.springframework.cache.Cache; +import org.springframework.cache.CacheManager; +import org.springframework.cache.interceptor.CacheInterceptor; +import org.springframework.data.redis.cache.RedisCache; + +public class CustomerCacheInterceptor extends CacheInterceptor { + + private final CacheManager caffeineCacheManager; + + public CustomerCacheInterceptor(CacheManager caffeineCacheManager) { + this.caffeineCacheManager = caffeineCacheManager; + } + + @Override + protected Cache.ValueWrapper doGet(Cache cache, Object key) { + Cache.ValueWrapper existingCacheValue = super.doGet(cache, key); + + if (cache.getClass() == RedisCache.class) { + Cache caffeineCache = caffeineCacheManager.getCache(cache.getName()); + if (existingCacheValue != null && caffeineCache != null && caffeineCache.get(key) == null) { + caffeineCache.putIfAbsent(key, existingCacheValue.get()); + } + } + + return existingCacheValue; + } +} + diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerController.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerController.java new file mode 100644 index 0000000000..d053754be8 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerController.java @@ -0,0 +1,22 @@ +package com.baeldung.caching.multicache; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class CustomerController { + + private final CustomerService customerService; + + @Autowired + public CustomerController(CustomerService customerService) { + this.customerService = customerService; + } + + @GetMapping("/customer/{id}") + public Customer getCustomer(@PathVariable String id) { + return customerService.getCustomer(id); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerRepository.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerRepository.java new file mode 100644 index 0000000000..da08e299e5 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerRepository.java @@ -0,0 +1,44 @@ +package com.baeldung.caching.multicache; + +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.util.HashMap; +import java.util.Map; + +@Service +public class CustomerRepository { + + private final Map customerMap = new HashMap<>(); + + public Customer getCustomerById(String id) { + return customerMap.get(id); + } + + @PostConstruct + private void setupCustomerRepo() { + Customer product1 = getCustomer("100001", "name1", "name1@mail.com"); + customerMap.put("100001", product1); + + Customer product2 = getCustomer("100002", "name2", "name2@mail.com"); + customerMap.put("100002", product2); + + Customer product3 = getCustomer("100003", "name3", "name3@mail.com"); + customerMap.put("100003", product3); + + Customer product4 = getCustomer("100004", "name4", "name4@mail.com"); + customerMap.put("100004", product4); + + Customer product5 = getCustomer("100005", "name5", "name5@mail.com"); + customerMap.put("100005", product5); + } + + private static Customer getCustomer(String id, String name, String email) { + Customer customer = new Customer(); + customer.setId(id); + customer.setName(name); + customer.setEmail(email); + + return customer; + } +} diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerService.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerService.java new file mode 100644 index 0000000000..db24254d83 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerService.java @@ -0,0 +1,25 @@ +package com.baeldung.caching.multicache; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.cache.annotation.Caching; +import org.springframework.stereotype.Service; + +@Service +public class CustomerService { + + private final CustomerRepository customerRepository; + + @Autowired + public CustomerService(CustomerRepository customerRepository) { + this.customerRepository = customerRepository; + } + + @Caching(cacheable = { + @Cacheable(cacheNames = "customerCache", cacheManager = "caffeineCacheManager"), + @Cacheable(cacheNames = "customerCache", cacheManager = "redisCacheManager") + }) + public Customer getCustomer(String id) { + return customerRepository.getCustomerById(id); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/MultipleCachingApplication.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/MultipleCachingApplication.java new file mode 100644 index 0000000000..862a2993a0 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/MultipleCachingApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.caching.multicache; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MultipleCachingApplication { + + public static void main(String[] args) { + SpringApplication.run(MultipleCachingApplication.class, args); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/resources/application.properties b/spring-boot-modules/spring-caching-2/src/main/resources/application.properties index 38f3537d01..97e4f97fcb 100644 --- a/spring-boot-modules/spring-caching-2/src/main/resources/application.properties +++ b/spring-boot-modules/spring-caching-2/src/main/resources/application.properties @@ -9,5 +9,6 @@ spring.jpa.hibernate.ddl-auto=update #setting cache TTL caching.spring.hotelListTTL=43200 # Connection details -#spring.redis.host=localhost -#spring.redis.port=6379 +spring.redis.host=localhost +spring.redis.port=6379 +spring.main.allow-bean-definition-overriding=true From 33ed7196ba17326ebaf589c4842d8eadc3ad5a7a Mon Sep 17 00:00:00 2001 From: saikat Date: Thu, 29 Feb 2024 11:12:18 +0530 Subject: [PATCH 15/59] refactor code and add integration tests --- .../caching/multicache/CacheConfig.java | 43 ++---- .../multicache/CustomerCacheInterceptor.java | 5 +- .../src/main/resources/application.properties | 4 +- ...CustomerServiceCachingIntegrationTest.java | 128 ++++++++++++++++++ .../ItemServiceCachingIntegrationTest.java | 7 +- 5 files changed, 149 insertions(+), 38 deletions(-) create mode 100644 spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java index 29419f4c12..22b223066a 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java @@ -1,7 +1,7 @@ package com.baeldung.caching.multicache; import com.github.benmanes.caffeine.cache.Caffeine; -import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.AnnotationCacheOperationSource; import org.springframework.cache.annotation.EnableCaching; @@ -15,8 +15,6 @@ import org.springframework.context.annotation.Primary; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; -import org.springframework.data.redis.connection.RedisStandaloneConfiguration; -import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; @@ -27,21 +25,6 @@ import java.util.Arrays; @EnableCaching public class CacheConfig { - @Value("${spring.redis.host}") - private String redisHost; - - @Value("${spring.redis.port}") - private int redisPort; - - @Bean - public CaffeineCache caffeineCacheConfig() { - return new CaffeineCache("customerCache", Caffeine.newBuilder() - .expireAfterWrite(Duration.ofMinutes(1)) - .initialCapacity(1) - .maximumSize(2000) - .build()); - } - @Bean @Primary public CacheManager caffeineCacheManager() { @@ -52,25 +35,26 @@ public class CacheConfig { } @Bean - public CacheManager redisCacheManager() { + public CaffeineCache caffeineCacheConfig() { + return new CaffeineCache("customerCache", Caffeine.newBuilder() + .expireAfterWrite(Duration.ofSeconds(3)) + .initialCapacity(1) + .maximumSize(2000) + .build()); + } + + @Bean + public CacheManager redisCacheManager(RedisConnectionFactory connectionFactory) { return RedisCacheManager.RedisCacheManagerBuilder - .fromConnectionFactory(redisConnectionFactory()) + .fromConnectionFactory(connectionFactory) .withCacheConfiguration("customerCache", cacheConfiguration()) .build(); } - @Bean - public RedisConnectionFactory redisConnectionFactory() { - RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); - redisStandaloneConfiguration.setHostName(redisHost); - redisStandaloneConfiguration.setPort(redisPort); - return new LettuceConnectionFactory(redisStandaloneConfiguration); - } - @Bean public RedisCacheConfiguration cacheConfiguration() { return RedisCacheConfiguration.defaultCacheConfig() - .entryTtl(Duration.ofMinutes(60)) + .entryTtl(Duration.ofMinutes(5)) .disableCachingNullValues() .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); } @@ -86,5 +70,4 @@ public class CacheConfig { public CacheOperationSource cacheOperationSource() { return new AnnotationCacheOperationSource(); } - } \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerCacheInterceptor.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerCacheInterceptor.java index 2ca1d2b2de..4c9a981489 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerCacheInterceptor.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerCacheInterceptor.java @@ -17,9 +17,9 @@ public class CustomerCacheInterceptor extends CacheInterceptor { protected Cache.ValueWrapper doGet(Cache cache, Object key) { Cache.ValueWrapper existingCacheValue = super.doGet(cache, key); - if (cache.getClass() == RedisCache.class) { + if (existingCacheValue != null && cache.getClass() == RedisCache.class) { Cache caffeineCache = caffeineCacheManager.getCache(cache.getName()); - if (existingCacheValue != null && caffeineCache != null && caffeineCache.get(key) == null) { + if (caffeineCache != null) { caffeineCache.putIfAbsent(key, existingCacheValue.get()); } } @@ -27,4 +27,3 @@ public class CustomerCacheInterceptor extends CacheInterceptor { return existingCacheValue; } } - diff --git a/spring-boot-modules/spring-caching-2/src/main/resources/application.properties b/spring-boot-modules/spring-caching-2/src/main/resources/application.properties index 97e4f97fcb..49bd715e43 100644 --- a/spring-boot-modules/spring-caching-2/src/main/resources/application.properties +++ b/spring-boot-modules/spring-caching-2/src/main/resources/application.properties @@ -9,6 +9,6 @@ spring.jpa.hibernate.ddl-auto=update #setting cache TTL caching.spring.hotelListTTL=43200 # Connection details -spring.redis.host=localhost -spring.redis.port=6379 +#spring.redis.host=localhost +#spring.redis.port=6379 spring.main.allow-bean-definition-overriding=true diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java new file mode 100644 index 0000000000..919c32fc66 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java @@ -0,0 +1,128 @@ +package com.baeldung.caching.multicache; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration; +import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import redis.embedded.RedisServer; + +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@Import({ CacheConfig.class,CustomerService.class }) +@ExtendWith(SpringExtension.class) +@ImportAutoConfiguration(classes = { CacheAutoConfiguration.class, RedisAutoConfiguration.class }) +@EnableCaching +class CustomerServiceCachingIntegrationTest { + + @MockBean + private CustomerRepository customerRepository; + + @Autowired + private CustomerService customerService; + + @Autowired + private CacheManager redisCacheManager; + + @Autowired + private CacheManager caffeineCacheManager; + + @Test + void givenCustomerIsPresentInDb_whenFindCustomerById_thenCustomerReturnedFromDb_And_Cached() { + Customer customer = new Customer("100", "test", "test@mail.com"); + given(customerRepository.getCustomerById("100")) + .willReturn(customer); + + Customer customerCacheMiss = customerService.getCustomer("100"); + + assertThat(customerCacheMiss).isEqualTo(customer); + verify(customerRepository, times(1)).getCustomerById("100"); + assertThat(customerFromRedisCache("100")).isEqualTo(customer); + assertThat(customerFromCaffeineCache("100")).isEqualTo(customer); + } + + @Test + void givenCustomerIsPresentInDb_whenFindCustomerById_CalledTwice_thenCustomerReturnedFromDb_And_Cached() { + Customer customer = new Customer("101", "test", "test@mail.com"); + given(customerRepository.getCustomerById("101")) + .willReturn(customer); + + Customer customerCacheMiss = customerService.getCustomer("101"); + Customer customerCacheHit = customerService.getCustomer("101"); + + assertThat(customerCacheMiss).isEqualTo(customer); + assertThat(customerCacheHit).isEqualTo(customer); + + verify(customerRepository, times(1)).getCustomerById("101"); + assertThat(customerFromRedisCache("101")).isEqualTo(customer); + assertThat(customerFromCaffeineCache("101")).isEqualTo(customer); + } + + @Test + void givenCustomerIsPresentInDb_whenFindCustomerById_CalledThrice_thenCustomerReturnedFromDBFirst_ThenFromCache() throws InterruptedException { + Customer customer = new Customer("102", "test", "test@mail.com"); + given(customerRepository.getCustomerById("102")) + .willReturn(customer); + + Customer customerCacheMiss = customerService.getCustomer("102"); + Customer customerCacheHit = customerService.getCustomer("102"); + + TimeUnit.SECONDS.sleep(4); + + assertThat(customerFromCaffeineCache("102")).isEqualTo(null); + Customer customerCacheHitAgain = customerService.getCustomer("102"); + + verify(customerRepository, times(1)).getCustomerById("102"); + assertThat(customerCacheMiss).isEqualTo(customer); + assertThat(customerCacheHit).isEqualTo(customer); + assertThat(customerCacheHitAgain).isEqualTo(customer); + assertThat(customerFromRedisCache("102")).isEqualTo(customer); + assertThat(customerFromCaffeineCache("102")).isEqualTo(customer); + } + + private Object customerFromRedisCache(String key) { + return redisCacheManager.getCache("customerCache").get(key) != null ? + redisCacheManager.getCache("customerCache").get(key).get() : null; + } + + private Object customerFromCaffeineCache(String key) { + return caffeineCacheManager.getCache("customerCache").get(key) != null ? + caffeineCacheManager.getCache("customerCache").get(key).get() : null; + } + + @TestConfiguration + static class EmbeddedRedisConfiguration { + + private final RedisServer redisServer; + + public EmbeddedRedisConfiguration() throws IOException { + this.redisServer = new RedisServer(); + } + + @PostConstruct + public void startRedis() throws IOException { + redisServer.start(); + } + + @PreDestroy + public void stopRedis() throws IOException { + this.redisServer.stop(); + } + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java index 291e729fb9..b070528bf6 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java @@ -16,6 +16,7 @@ import redis.embedded.RedisServer; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; +import java.io.IOException; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @@ -66,17 +67,17 @@ class ItemServiceCachingIntegrationTest { private final RedisServer redisServer; - public EmbeddedRedisConfiguration() { + public EmbeddedRedisConfiguration() throws IOException { this.redisServer = new RedisServer(); } @PostConstruct - public void startRedis() { + public void startRedis() throws IOException { redisServer.start(); } @PreDestroy - public void stopRedis() { + public void stopRedis() throws IOException { this.redisServer.stop(); } } From 87826df61a1c78d83ae80aa1c5ad248e030d24eb Mon Sep 17 00:00:00 2001 From: saikat Date: Thu, 29 Feb 2024 11:17:29 +0530 Subject: [PATCH 16/59] update embeddbed redis dependencies to run test in Mac OS as well --- spring-boot-modules/spring-caching-2/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot-modules/spring-caching-2/pom.xml b/spring-boot-modules/spring-caching-2/pom.xml index 4675b5162e..3934a8b22e 100644 --- a/spring-boot-modules/spring-caching-2/pom.xml +++ b/spring-boot-modules/spring-caching-2/pom.xml @@ -51,7 +51,7 @@ ${caffeine.version} - it.ozimov + com.github.codemonstur embedded-redis ${embedded.redis.version} @@ -65,7 +65,7 @@ - 0.7.3 + 1.4.0 3.1.8 From 878509406f99ad0edc20b8fea308d073a03c2ce7 Mon Sep 17 00:00:00 2001 From: saikat Date: Thu, 29 Feb 2024 11:23:54 +0530 Subject: [PATCH 17/59] test updated --- .../ItemServiceCachingIntegrationTest.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java index b070528bf6..7865add769 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java @@ -1,5 +1,14 @@ package com.baeldung.caching.redis; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.io.IOException; +import java.util.Optional; + +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; @@ -12,22 +21,17 @@ import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; + import redis.embedded.RedisServer; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; -import java.io.IOException; -import java.util.Optional; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; @Import({ CacheConfig.class, ItemService.class }) @ExtendWith(SpringExtension.class) @ImportAutoConfiguration(classes = { CacheAutoConfiguration.class, RedisAutoConfiguration.class }) @EnableCaching +@Disabled("This will be fixed.") class ItemServiceCachingIntegrationTest { private static final String AN_ID = "id-1"; From ff0db905bc6d1ef034740d1b890a868719f9d48b Mon Sep 17 00:00:00 2001 From: saikat Date: Thu, 29 Feb 2024 11:29:42 +0530 Subject: [PATCH 18/59] reverted dependencies to check --- spring-boot-modules/spring-caching-2/pom.xml | 8 +++---- ...CustomerServiceCachingIntegrationTest.java | 7 +++--- .../ItemServiceCachingIntegrationTest.java | 23 ++++++++----------- 3 files changed, 16 insertions(+), 22 deletions(-) diff --git a/spring-boot-modules/spring-caching-2/pom.xml b/spring-boot-modules/spring-caching-2/pom.xml index 3934a8b22e..7a4744802a 100644 --- a/spring-boot-modules/spring-caching-2/pom.xml +++ b/spring-boot-modules/spring-caching-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-caching-2 0.1-SNAPSHOT @@ -51,7 +51,7 @@ ${caffeine.version} - com.github.codemonstur + it.ozimov embedded-redis ${embedded.redis.version} @@ -65,7 +65,7 @@ - 1.4.0 + 0.7.3 3.1.8 diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java index 919c32fc66..17faef871c 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java @@ -17,7 +17,6 @@ import redis.embedded.RedisServer; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; -import java.io.IOException; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; @@ -111,17 +110,17 @@ class CustomerServiceCachingIntegrationTest { private final RedisServer redisServer; - public EmbeddedRedisConfiguration() throws IOException { + public EmbeddedRedisConfiguration() { this.redisServer = new RedisServer(); } @PostConstruct - public void startRedis() throws IOException { + public void startRedis() { redisServer.start(); } @PreDestroy - public void stopRedis() throws IOException { + public void stopRedis() { this.redisServer.stop(); } } diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java index 7865add769..291e729fb9 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java @@ -1,14 +1,5 @@ package com.baeldung.caching.redis; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import java.io.IOException; -import java.util.Optional; - -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; @@ -21,17 +12,21 @@ import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; - import redis.embedded.RedisServer; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; @Import({ CacheConfig.class, ItemService.class }) @ExtendWith(SpringExtension.class) @ImportAutoConfiguration(classes = { CacheAutoConfiguration.class, RedisAutoConfiguration.class }) @EnableCaching -@Disabled("This will be fixed.") class ItemServiceCachingIntegrationTest { private static final String AN_ID = "id-1"; @@ -71,17 +66,17 @@ class ItemServiceCachingIntegrationTest { private final RedisServer redisServer; - public EmbeddedRedisConfiguration() throws IOException { + public EmbeddedRedisConfiguration() { this.redisServer = new RedisServer(); } @PostConstruct - public void startRedis() throws IOException { + public void startRedis() { redisServer.start(); } @PreDestroy - public void stopRedis() throws IOException { + public void stopRedis() { this.redisServer.stop(); } } From 0a2d6823de5aa656a5bded7f86f1e30b1f21753f Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Thu, 29 Feb 2024 23:02:56 -0500 Subject: [PATCH 19/59] BAEL-7374 - Review comments. --- .../baeldung/spring/kafka/start/stop/consumer/Constants.java | 2 -- .../start/stop/consumer/StartStopConsumerApplication.java | 2 -- .../baeldung/spring/kafka/start/stop/consumer/UserEvent.java | 3 --- 3 files changed, 7 deletions(-) diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java index bc17c368d9..9de3e117be 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java @@ -1,8 +1,6 @@ package com.baeldung.spring.kafka.start.stop.consumer; public class Constants { - public static final String MULTI_PARTITION_TOPIC = "multi_partition_topic"; - public static final String LISTENER_ID = "listener-id-1"; } diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java index 51893ea64a..c24517543b 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java @@ -5,9 +5,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class StartStopConsumerApplication { - public static void main(String[] args) { SpringApplication.run(StartStopConsumerApplication.class, args); } - } diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java index fe95a8c4ad..bfa8c72c39 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java @@ -1,10 +1,8 @@ package com.baeldung.spring.kafka.start.stop.consumer; public class UserEvent { - private String userEventId; - public UserEvent() { } @@ -19,5 +17,4 @@ public class UserEvent { public void setUserEventId(String userEventId) { this.userEventId = userEventId; } - } From 5b7a864ef29a1f5b2bdd115fafe1e4bb8f295d19 Mon Sep 17 00:00:00 2001 From: saikat Date: Fri, 1 Mar 2024 13:08:58 +0530 Subject: [PATCH 20/59] refactor code for customer repository and update embedded redis repository --- spring-boot-modules/spring-caching-2/pom.xml | 8 +-- .../caching/multicache/CacheConfig.java | 3 +- .../multicache/CustomerController.java | 22 ------ .../multicache/CustomerRepository.java | 41 +---------- .../caching/multicache/CustomerService.java | 3 +- ...CustomerServiceCachingIntegrationTest.java | 71 +++++++++---------- .../ItemServiceCachingIntegrationTest.java | 7 +- 7 files changed, 48 insertions(+), 107 deletions(-) delete mode 100644 spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerController.java diff --git a/spring-boot-modules/spring-caching-2/pom.xml b/spring-boot-modules/spring-caching-2/pom.xml index 7a4744802a..3934a8b22e 100644 --- a/spring-boot-modules/spring-caching-2/pom.xml +++ b/spring-boot-modules/spring-caching-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-caching-2 0.1-SNAPSHOT @@ -51,7 +51,7 @@ ${caffeine.version} - it.ozimov + com.github.codemonstur embedded-redis ${embedded.redis.version} @@ -65,7 +65,7 @@ - 0.7.3 + 1.4.0 3.1.8 diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java index 22b223066a..a911bdf161 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java @@ -1,7 +1,6 @@ package com.baeldung.caching.multicache; import com.github.benmanes.caffeine.cache.Caffeine; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.AnnotationCacheOperationSource; import org.springframework.cache.annotation.EnableCaching; @@ -37,7 +36,7 @@ public class CacheConfig { @Bean public CaffeineCache caffeineCacheConfig() { return new CaffeineCache("customerCache", Caffeine.newBuilder() - .expireAfterWrite(Duration.ofSeconds(3)) + .expireAfterWrite(Duration.ofSeconds(1)) .initialCapacity(1) .maximumSize(2000) .build()); diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerController.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerController.java deleted file mode 100644 index d053754be8..0000000000 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerController.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.baeldung.caching.multicache; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class CustomerController { - - private final CustomerService customerService; - - @Autowired - public CustomerController(CustomerService customerService) { - this.customerService = customerService; - } - - @GetMapping("/customer/{id}") - public Customer getCustomer(@PathVariable String id) { - return customerService.getCustomer(id); - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerRepository.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerRepository.java index da08e299e5..3281e35c76 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerRepository.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerRepository.java @@ -1,44 +1,7 @@ package com.baeldung.caching.multicache; -import org.springframework.stereotype.Service; +import org.springframework.data.repository.CrudRepository; -import javax.annotation.PostConstruct; -import java.util.HashMap; -import java.util.Map; -@Service -public class CustomerRepository { - - private final Map customerMap = new HashMap<>(); - - public Customer getCustomerById(String id) { - return customerMap.get(id); - } - - @PostConstruct - private void setupCustomerRepo() { - Customer product1 = getCustomer("100001", "name1", "name1@mail.com"); - customerMap.put("100001", product1); - - Customer product2 = getCustomer("100002", "name2", "name2@mail.com"); - customerMap.put("100002", product2); - - Customer product3 = getCustomer("100003", "name3", "name3@mail.com"); - customerMap.put("100003", product3); - - Customer product4 = getCustomer("100004", "name4", "name4@mail.com"); - customerMap.put("100004", product4); - - Customer product5 = getCustomer("100005", "name5", "name5@mail.com"); - customerMap.put("100005", product5); - } - - private static Customer getCustomer(String id, String name, String email) { - Customer customer = new Customer(); - customer.setId(id); - customer.setName(name); - customer.setEmail(email); - - return customer; - } +public interface CustomerRepository extends CrudRepository { } diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerService.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerService.java index db24254d83..14a7f293c8 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerService.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerService.java @@ -20,6 +20,7 @@ public class CustomerService { @Cacheable(cacheNames = "customerCache", cacheManager = "redisCacheManager") }) public Customer getCustomer(String id) { - return customerRepository.getCustomerById(id); + return customerRepository.findById(id) + .orElseThrow(RuntimeException::new); } } \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java index 17faef871c..df53eb2833 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java @@ -17,6 +17,8 @@ import redis.embedded.RedisServer; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; +import java.io.IOException; +import java.util.Optional; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; @@ -43,56 +45,53 @@ class CustomerServiceCachingIntegrationTest { private CacheManager caffeineCacheManager; @Test - void givenCustomerIsPresentInDb_whenFindCustomerById_thenCustomerReturnedFromDb_And_Cached() { - Customer customer = new Customer("100", "test", "test@mail.com"); - given(customerRepository.getCustomerById("100")) - .willReturn(customer); + void givenCustomerIsPresentInDB_whenGetCustomerById_thenCustomerReturnedFromDBAndCached() { + String CUSTOMER_ID = "100"; + Customer customer = new Customer(CUSTOMER_ID, "test", "test@mail.com"); - Customer customerCacheMiss = customerService.getCustomer("100"); + given(customerRepository.findById(CUSTOMER_ID)) + .willReturn(Optional.of(customer)); + + Customer customerCacheMiss = customerService.getCustomer(CUSTOMER_ID); assertThat(customerCacheMiss).isEqualTo(customer); - verify(customerRepository, times(1)).getCustomerById("100"); - assertThat(customerFromRedisCache("100")).isEqualTo(customer); - assertThat(customerFromCaffeineCache("100")).isEqualTo(customer); + verify(customerRepository, times(1)).findById(CUSTOMER_ID); + assertThat(customerFromRedisCache(CUSTOMER_ID)).isEqualTo(customer); + assertThat(customerFromCaffeineCache(CUSTOMER_ID)).isEqualTo(customer); } @Test - void givenCustomerIsPresentInDb_whenFindCustomerById_CalledTwice_thenCustomerReturnedFromDb_And_Cached() { - Customer customer = new Customer("101", "test", "test@mail.com"); - given(customerRepository.getCustomerById("101")) - .willReturn(customer); + void givenCustomerIsPresentInDB_whenGetCustomerByIdIsCalledTwice_thenCustomerReturnedFromDBAndCached() { + String CUSTOMER_ID = "101"; + Customer customer = new Customer(CUSTOMER_ID, "test", "test@mail.com"); + given(customerRepository.findById(CUSTOMER_ID)).willReturn(Optional.of(customer)); - Customer customerCacheMiss = customerService.getCustomer("101"); - Customer customerCacheHit = customerService.getCustomer("101"); + Customer customerCacheMiss = customerService.getCustomer(CUSTOMER_ID); + Customer customerCacheHit = customerService.getCustomer(CUSTOMER_ID); assertThat(customerCacheMiss).isEqualTo(customer); assertThat(customerCacheHit).isEqualTo(customer); - - verify(customerRepository, times(1)).getCustomerById("101"); - assertThat(customerFromRedisCache("101")).isEqualTo(customer); - assertThat(customerFromCaffeineCache("101")).isEqualTo(customer); + verify(customerRepository, times(1)).findById(CUSTOMER_ID); + assertThat(customerFromRedisCache(CUSTOMER_ID)).isEqualTo(customer); + assertThat(customerFromCaffeineCache(CUSTOMER_ID)).isEqualTo(customer); } @Test - void givenCustomerIsPresentInDb_whenFindCustomerById_CalledThrice_thenCustomerReturnedFromDBFirst_ThenFromCache() throws InterruptedException { - Customer customer = new Customer("102", "test", "test@mail.com"); - given(customerRepository.getCustomerById("102")) - .willReturn(customer); + void givenCustomerIsPresentInDB_whenGetCustomerByIdIsCalledThrice_thenCustomerReturnedFromDBAndCached() throws InterruptedException { + String CUSTOMER_ID = "102"; + Customer customer = new Customer(CUSTOMER_ID, "test", "test@mail.com"); + given(customerRepository.findById(CUSTOMER_ID)) + .willReturn(Optional.of(customer)); - Customer customerCacheMiss = customerService.getCustomer("102"); - Customer customerCacheHit = customerService.getCustomer("102"); + Customer customerCacheMiss = customerService.getCustomer(CUSTOMER_ID); + TimeUnit.SECONDS.sleep(2); + Customer customerCacheHit = customerService.getCustomer(CUSTOMER_ID); - TimeUnit.SECONDS.sleep(4); - - assertThat(customerFromCaffeineCache("102")).isEqualTo(null); - Customer customerCacheHitAgain = customerService.getCustomer("102"); - - verify(customerRepository, times(1)).getCustomerById("102"); + verify(customerRepository, times(1)).findById(CUSTOMER_ID); assertThat(customerCacheMiss).isEqualTo(customer); assertThat(customerCacheHit).isEqualTo(customer); - assertThat(customerCacheHitAgain).isEqualTo(customer); - assertThat(customerFromRedisCache("102")).isEqualTo(customer); - assertThat(customerFromCaffeineCache("102")).isEqualTo(customer); + assertThat(customerFromRedisCache(CUSTOMER_ID)).isEqualTo(customer); + assertThat(customerFromCaffeineCache(CUSTOMER_ID)).isEqualTo(customer); } private Object customerFromRedisCache(String key) { @@ -110,17 +109,17 @@ class CustomerServiceCachingIntegrationTest { private final RedisServer redisServer; - public EmbeddedRedisConfiguration() { + public EmbeddedRedisConfiguration() throws IOException { this.redisServer = new RedisServer(); } @PostConstruct - public void startRedis() { + public void startRedis() throws IOException { redisServer.start(); } @PreDestroy - public void stopRedis() { + public void stopRedis() throws IOException { this.redisServer.stop(); } } diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java index 291e729fb9..b070528bf6 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java @@ -16,6 +16,7 @@ import redis.embedded.RedisServer; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; +import java.io.IOException; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; @@ -66,17 +67,17 @@ class ItemServiceCachingIntegrationTest { private final RedisServer redisServer; - public EmbeddedRedisConfiguration() { + public EmbeddedRedisConfiguration() throws IOException { this.redisServer = new RedisServer(); } @PostConstruct - public void startRedis() { + public void startRedis() throws IOException { redisServer.start(); } @PreDestroy - public void stopRedis() { + public void stopRedis() throws IOException { this.redisServer.stop(); } } From 03f52e6329af6196b9272f56b39528ea06451d55 Mon Sep 17 00:00:00 2001 From: saikat Date: Fri, 1 Mar 2024 16:03:55 +0530 Subject: [PATCH 21/59] refactor code --- .../multicache/MultipleCachingApplication.java | 12 ------------ .../{multicache => twolevelcache}/CacheConfig.java | 5 ++--- .../{multicache => twolevelcache}/Customer.java | 2 +- .../CustomerCacheInterceptor.java | 2 +- .../CustomerRepository.java | 3 +-- .../CustomerService.java | 2 +- .../redis/ItemServiceCachingIntegrationTest.java | 10 +++++----- .../CustomerServiceCachingIntegrationTest.java | 12 ++++++------ 8 files changed, 17 insertions(+), 31 deletions(-) delete mode 100644 spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/MultipleCachingApplication.java rename spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/{multicache => twolevelcache}/CacheConfig.java (95%) rename spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/{multicache => twolevelcache}/Customer.java (87%) rename spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/{multicache => twolevelcache}/CustomerCacheInterceptor.java (95%) rename spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/{multicache => twolevelcache}/CustomerRepository.java (76%) rename spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/{multicache => twolevelcache}/CustomerService.java (94%) rename spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/{multicache => twolevelcache}/CustomerServiceCachingIntegrationTest.java (99%) diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/MultipleCachingApplication.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/MultipleCachingApplication.java deleted file mode 100644 index 862a2993a0..0000000000 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/MultipleCachingApplication.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.baeldung.caching.multicache; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class MultipleCachingApplication { - - public static void main(String[] args) { - SpringApplication.run(MultipleCachingApplication.class, args); - } -} \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java similarity index 95% rename from spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java index a911bdf161..2072f5806a 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CacheConfig.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.caching.multicache; +package com.baeldung.caching.twolevelcache; import com.github.benmanes.caffeine.cache.Caffeine; import org.springframework.cache.CacheManager; @@ -28,8 +28,7 @@ public class CacheConfig { @Primary public CacheManager caffeineCacheManager() { SimpleCacheManager manager = new SimpleCacheManager(); - manager.setCaches(Arrays.asList( - caffeineCacheConfig())); + manager.setCaches(Arrays.asList(caffeineCacheConfig())); return manager; } diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/Customer.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java similarity index 87% rename from spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/Customer.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java index 4632799a1c..a2d1a14ea3 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/Customer.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java @@ -1,4 +1,4 @@ -package com.baeldung.caching.multicache; +package com.baeldung.caching.twolevelcache; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerCacheInterceptor.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerCacheInterceptor.java similarity index 95% rename from spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerCacheInterceptor.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerCacheInterceptor.java index 4c9a981489..f1a8dca0db 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerCacheInterceptor.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerCacheInterceptor.java @@ -1,4 +1,4 @@ -package com.baeldung.caching.multicache; +package com.baeldung.caching.twolevelcache; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerRepository.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerRepository.java similarity index 76% rename from spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerRepository.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerRepository.java index 3281e35c76..098112f152 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerRepository.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerRepository.java @@ -1,7 +1,6 @@ -package com.baeldung.caching.multicache; +package com.baeldung.caching.twolevelcache; import org.springframework.data.repository.CrudRepository; - public interface CustomerRepository extends CrudRepository { } diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerService.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java similarity index 94% rename from spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerService.java rename to spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java index 14a7f293c8..68e78c9fdb 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/multicache/CustomerService.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java @@ -1,4 +1,4 @@ -package com.baeldung.caching.multicache; +package com.baeldung.caching.twolevelcache; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java index b070528bf6..e25773305a 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java @@ -1,5 +1,10 @@ package com.baeldung.caching.redis; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; @@ -19,11 +24,6 @@ import javax.annotation.PreDestroy; import java.io.IOException; import java.util.Optional; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - @Import({ CacheConfig.class, ItemService.class }) @ExtendWith(SpringExtension.class) @ImportAutoConfiguration(classes = { CacheAutoConfiguration.class, RedisAutoConfiguration.class }) diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java similarity index 99% rename from spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java rename to spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java index df53eb2833..6aa3242c95 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/multicache/CustomerServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java @@ -1,4 +1,9 @@ -package com.baeldung.caching.multicache; +package com.baeldung.caching.twolevelcache; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -21,11 +26,6 @@ import java.io.IOException; import java.util.Optional; import java.util.concurrent.TimeUnit; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - @Import({ CacheConfig.class,CustomerService.class }) @ExtendWith(SpringExtension.class) @ImportAutoConfiguration(classes = { CacheAutoConfiguration.class, RedisAutoConfiguration.class }) From f959e7a273a56b90e7614b44a7cb1de9e4477f1d Mon Sep 17 00:00:00 2001 From: saikat Date: Sat, 2 Mar 2024 09:43:32 +0530 Subject: [PATCH 22/59] fixed int test issue with redis server --- .../com/baeldung/caching/twolevelcache/CacheConfig.java | 2 +- .../CustomerServiceCachingIntegrationTest.java | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java index 2072f5806a..67d857eb24 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java @@ -35,7 +35,7 @@ public class CacheConfig { @Bean public CaffeineCache caffeineCacheConfig() { return new CaffeineCache("customerCache", Caffeine.newBuilder() - .expireAfterWrite(Duration.ofSeconds(1)) + .expireAfterWrite(Duration.ofSeconds(3)) .initialCapacity(1) .maximumSize(2000) .build()); diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java index 6aa3242c95..b28c70da0c 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java @@ -16,6 +16,7 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Import; +import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import redis.embedded.RedisServer; @@ -30,6 +31,7 @@ import java.util.concurrent.TimeUnit; @ExtendWith(SpringExtension.class) @ImportAutoConfiguration(classes = { CacheAutoConfiguration.class, RedisAutoConfiguration.class }) @EnableCaching +@TestPropertySource(properties = {"spring.redis.port=7000"}) class CustomerServiceCachingIntegrationTest { @MockBean @@ -84,7 +86,8 @@ class CustomerServiceCachingIntegrationTest { .willReturn(Optional.of(customer)); Customer customerCacheMiss = customerService.getCustomer(CUSTOMER_ID); - TimeUnit.SECONDS.sleep(2); + TimeUnit.SECONDS.sleep(3); + assertThat(customerFromCaffeineCache(CUSTOMER_ID)).isEqualTo(null); Customer customerCacheHit = customerService.getCustomer(CUSTOMER_ID); verify(customerRepository, times(1)).findById(CUSTOMER_ID); @@ -110,7 +113,7 @@ class CustomerServiceCachingIntegrationTest { private final RedisServer redisServer; public EmbeddedRedisConfiguration() throws IOException { - this.redisServer = new RedisServer(); + this.redisServer = new RedisServer(7000); } @PostConstruct From 605568587ec6e11b43f5a05262928652b842c4e7 Mon Sep 17 00:00:00 2001 From: saikat Date: Sat, 2 Mar 2024 11:06:37 +0530 Subject: [PATCH 23/59] Add application file and update entity in model --- .../baeldung/caching/twolevelcache/Customer.java | 4 ++++ .../twolevelcache/TwoLevelCacheApplication.java | 14 ++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/TwoLevelCacheApplication.java diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java index a2d1a14ea3..b8a1b7d6b2 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java @@ -5,14 +5,18 @@ import lombok.Data; import lombok.NoArgsConstructor; import lombok.Setter; +import javax.persistence.Entity; +import javax.persistence.Id; import java.io.Serializable; @Data +@Entity @AllArgsConstructor @NoArgsConstructor @Setter public class Customer implements Serializable { + @Id private String id; private String name; diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/TwoLevelCacheApplication.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/TwoLevelCacheApplication.java new file mode 100644 index 0000000000..867f4c9f91 --- /dev/null +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/TwoLevelCacheApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.caching.twolevelcache; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; + +@SpringBootApplication +@EnableCaching +public class TwoLevelCacheApplication { + + public static void main(String[] args) { + SpringApplication.run(TwoLevelCacheApplication.class, args); + } +} \ No newline at end of file From d5490dd79450186299877f3748c1921ddf3e8872 Mon Sep 17 00:00:00 2001 From: saikat Date: Sat, 2 Mar 2024 14:01:28 +0530 Subject: [PATCH 24/59] rename method --- .../caching/redis/ItemServiceCachingIntegrationTest.java | 1 + .../twolevelcache/CustomerServiceCachingIntegrationTest.java | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java index 07d9f0316b..7134c4727c 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java @@ -5,6 +5,7 @@ import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java index b28c70da0c..0bc1a5c1fc 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java @@ -79,7 +79,7 @@ class CustomerServiceCachingIntegrationTest { } @Test - void givenCustomerIsPresentInDB_whenGetCustomerByIdIsCalledThrice_thenCustomerReturnedFromDBAndCached() throws InterruptedException { + void givenCustomerIsPresentInDB_whenGetCustomerByIdIsCalledTwice_AndFirstCacheExpires_thenCustomerReturnedFromDBAndCached() throws InterruptedException { String CUSTOMER_ID = "102"; Customer customer = new Customer(CUSTOMER_ID, "test", "test@mail.com"); given(customerRepository.findById(CUSTOMER_ID)) From b182b42c0747967fd31f26d7526472b82fbd2ee6 Mon Sep 17 00:00:00 2001 From: saikat Date: Sat, 2 Mar 2024 15:39:52 +0530 Subject: [PATCH 25/59] fix the imports with latest changes --- .../com/baeldung/caching/twolevelcache/Customer.java | 4 ++-- .../caching/redis/ItemServiceCachingIntegrationTest.java | 4 ++-- .../CustomerServiceCachingIntegrationTest.java | 9 +++------ 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java index b8a1b7d6b2..0b985d35f3 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/Customer.java @@ -1,12 +1,12 @@ package com.baeldung.caching.twolevelcache; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.Setter; -import javax.persistence.Entity; -import javax.persistence.Id; import java.io.Serializable; @Data diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java index 7134c4727c..01740ba780 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/redis/ItemServiceCachingIntegrationTest.java @@ -20,8 +20,8 @@ import org.springframework.context.annotation.Import; import org.springframework.test.context.junit.jupiter.SpringExtension; import redis.embedded.RedisServer; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import java.io.IOException; import java.util.Optional; diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java index 0bc1a5c1fc..93f61b5916 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java @@ -16,13 +16,11 @@ import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Import; -import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit.jupiter.SpringExtension; import redis.embedded.RedisServer; -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; - +import jakarta.annotation.PostConstruct; +import jakarta.annotation.PreDestroy; import java.io.IOException; import java.util.Optional; import java.util.concurrent.TimeUnit; @@ -31,7 +29,6 @@ import java.util.concurrent.TimeUnit; @ExtendWith(SpringExtension.class) @ImportAutoConfiguration(classes = { CacheAutoConfiguration.class, RedisAutoConfiguration.class }) @EnableCaching -@TestPropertySource(properties = {"spring.redis.port=7000"}) class CustomerServiceCachingIntegrationTest { @MockBean @@ -113,7 +110,7 @@ class CustomerServiceCachingIntegrationTest { private final RedisServer redisServer; public EmbeddedRedisConfiguration() throws IOException { - this.redisServer = new RedisServer(7000); + this.redisServer = new RedisServer(); } @PostConstruct From b2a0a75389267b7fca56e7e90f86d5550df3dfc8 Mon Sep 17 00:00:00 2001 From: saikat Date: Wed, 6 Mar 2024 13:09:58 +0530 Subject: [PATCH 26/59] reformatting from default and update test method names --- .../caching/twolevelcache/CacheConfig.java | 30 +++++++++---------- .../twolevelcache/CustomerService.java | 6 ++-- .../TwoLevelCacheApplication.java | 2 -- ...CustomerServiceCachingIntegrationTest.java | 22 +++++++------- 4 files changed, 28 insertions(+), 32 deletions(-) diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java index 67d857eb24..e8642e43ba 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java @@ -26,40 +26,40 @@ public class CacheConfig { @Bean @Primary - public CacheManager caffeineCacheManager() { + public CacheManager caffeineCacheManager(CaffeineCache caffeineCache) { SimpleCacheManager manager = new SimpleCacheManager(); - manager.setCaches(Arrays.asList(caffeineCacheConfig())); + manager.setCaches(Arrays.asList(caffeineCache)); return manager; } @Bean public CaffeineCache caffeineCacheConfig() { return new CaffeineCache("customerCache", Caffeine.newBuilder() - .expireAfterWrite(Duration.ofSeconds(3)) - .initialCapacity(1) - .maximumSize(2000) - .build()); + .expireAfterWrite(Duration.ofSeconds(3)) + .initialCapacity(1) + .maximumSize(2000) + .build()); } @Bean - public CacheManager redisCacheManager(RedisConnectionFactory connectionFactory) { + public CacheManager redisCacheManager(RedisConnectionFactory connectionFactory, RedisCacheConfiguration redisCacheConfiguration) { return RedisCacheManager.RedisCacheManagerBuilder - .fromConnectionFactory(connectionFactory) - .withCacheConfiguration("customerCache", cacheConfiguration()) - .build(); + .fromConnectionFactory(connectionFactory) + .withCacheConfiguration("customerCache", redisCacheConfiguration) + .build(); } @Bean public RedisCacheConfiguration cacheConfiguration() { return RedisCacheConfiguration.defaultCacheConfig() - .entryTtl(Duration.ofMinutes(5)) - .disableCachingNullValues() - .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); + .entryTtl(Duration.ofMinutes(5)) + .disableCachingNullValues() + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); } @Bean - public CacheInterceptor cacheInterceptor() { - CacheInterceptor interceptor = new CustomerCacheInterceptor(caffeineCacheManager()); + public CacheInterceptor cacheInterceptor(CacheManager caffeineCacheManager) { + CacheInterceptor interceptor = new CustomerCacheInterceptor(caffeineCacheManager); interceptor.setCacheOperationSources(cacheOperationSource()); return interceptor; } diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java index 68e78c9fdb..20bc91f7b2 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java @@ -16,11 +16,11 @@ public class CustomerService { } @Caching(cacheable = { - @Cacheable(cacheNames = "customerCache", cacheManager = "caffeineCacheManager"), - @Cacheable(cacheNames = "customerCache", cacheManager = "redisCacheManager") + @Cacheable(cacheNames = "customerCache", cacheManager = "caffeineCacheManager"), + @Cacheable(cacheNames = "customerCache", cacheManager = "redisCacheManager") }) public Customer getCustomer(String id) { return customerRepository.findById(id) - .orElseThrow(RuntimeException::new); + .orElseThrow(RuntimeException::new); } } \ No newline at end of file diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/TwoLevelCacheApplication.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/TwoLevelCacheApplication.java index 867f4c9f91..9bc2c65e6e 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/TwoLevelCacheApplication.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/TwoLevelCacheApplication.java @@ -2,10 +2,8 @@ package com.baeldung.caching.twolevelcache; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication -@EnableCaching public class TwoLevelCacheApplication { public static void main(String[] args) { diff --git a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java index 93f61b5916..3db53198fc 100644 --- a/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java +++ b/spring-boot-modules/spring-caching-2/src/test/java/com/baeldung/caching/twolevelcache/CustomerServiceCachingIntegrationTest.java @@ -44,23 +44,22 @@ class CustomerServiceCachingIntegrationTest { private CacheManager caffeineCacheManager; @Test - void givenCustomerIsPresentInDB_whenGetCustomerById_thenCustomerReturnedFromDBAndCached() { + void givenCustomerIsPresent_whenGetCustomerCalled_thenReturnCustomerAndCacheIt() { String CUSTOMER_ID = "100"; Customer customer = new Customer(CUSTOMER_ID, "test", "test@mail.com"); - given(customerRepository.findById(CUSTOMER_ID)) - .willReturn(Optional.of(customer)); + given(customerRepository.findById(CUSTOMER_ID)).willReturn(Optional.of(customer)); Customer customerCacheMiss = customerService.getCustomer(CUSTOMER_ID); assertThat(customerCacheMiss).isEqualTo(customer); verify(customerRepository, times(1)).findById(CUSTOMER_ID); - assertThat(customerFromRedisCache(CUSTOMER_ID)).isEqualTo(customer); assertThat(customerFromCaffeineCache(CUSTOMER_ID)).isEqualTo(customer); + assertThat(customerFromRedisCache(CUSTOMER_ID)).isEqualTo(customer); } @Test - void givenCustomerIsPresentInDB_whenGetCustomerByIdIsCalledTwice_thenCustomerReturnedFromDBAndCached() { + void givenCustomerIsPresent_whenGetCustomerCalledTwice_thenReturnCustomerAndCacheIt() { String CUSTOMER_ID = "101"; Customer customer = new Customer(CUSTOMER_ID, "test", "test@mail.com"); given(customerRepository.findById(CUSTOMER_ID)).willReturn(Optional.of(customer)); @@ -71,16 +70,15 @@ class CustomerServiceCachingIntegrationTest { assertThat(customerCacheMiss).isEqualTo(customer); assertThat(customerCacheHit).isEqualTo(customer); verify(customerRepository, times(1)).findById(CUSTOMER_ID); - assertThat(customerFromRedisCache(CUSTOMER_ID)).isEqualTo(customer); assertThat(customerFromCaffeineCache(CUSTOMER_ID)).isEqualTo(customer); + assertThat(customerFromRedisCache(CUSTOMER_ID)).isEqualTo(customer); } @Test - void givenCustomerIsPresentInDB_whenGetCustomerByIdIsCalledTwice_AndFirstCacheExpires_thenCustomerReturnedFromDBAndCached() throws InterruptedException { + void givenCustomerIsPresent_whenGetCustomerCalledTwiceAndFirstCacheExpired_thenReturnCustomerAndCacheIt() throws InterruptedException { String CUSTOMER_ID = "102"; Customer customer = new Customer(CUSTOMER_ID, "test", "test@mail.com"); - given(customerRepository.findById(CUSTOMER_ID)) - .willReturn(Optional.of(customer)); + given(customerRepository.findById(CUSTOMER_ID)).willReturn(Optional.of(customer)); Customer customerCacheMiss = customerService.getCustomer(CUSTOMER_ID); TimeUnit.SECONDS.sleep(3); @@ -90,18 +88,18 @@ class CustomerServiceCachingIntegrationTest { verify(customerRepository, times(1)).findById(CUSTOMER_ID); assertThat(customerCacheMiss).isEqualTo(customer); assertThat(customerCacheHit).isEqualTo(customer); - assertThat(customerFromRedisCache(CUSTOMER_ID)).isEqualTo(customer); assertThat(customerFromCaffeineCache(CUSTOMER_ID)).isEqualTo(customer); + assertThat(customerFromRedisCache(CUSTOMER_ID)).isEqualTo(customer); } private Object customerFromRedisCache(String key) { return redisCacheManager.getCache("customerCache").get(key) != null ? - redisCacheManager.getCache("customerCache").get(key).get() : null; + redisCacheManager.getCache("customerCache").get(key).get() : null; } private Object customerFromCaffeineCache(String key) { return caffeineCacheManager.getCache("customerCache").get(key) != null ? - caffeineCacheManager.getCache("customerCache").get(key).get() : null; + caffeineCacheManager.getCache("customerCache").get(key).get() : null; } @TestConfiguration From e7d85015e342d073fa46caaea0fb80d5bcba24a1 Mon Sep 17 00:00:00 2001 From: saikat Date: Wed, 6 Mar 2024 13:56:59 +0530 Subject: [PATCH 27/59] autwire via method param --- .../java/com/baeldung/caching/twolevelcache/CacheConfig.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java index e8642e43ba..b1bec0f4a1 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java @@ -58,9 +58,9 @@ public class CacheConfig { } @Bean - public CacheInterceptor cacheInterceptor(CacheManager caffeineCacheManager) { + public CacheInterceptor cacheInterceptor(CacheManager caffeineCacheManager, CacheOperationSource cacheOperationSource) { CacheInterceptor interceptor = new CustomerCacheInterceptor(caffeineCacheManager); - interceptor.setCacheOperationSources(cacheOperationSource()); + interceptor.setCacheOperationSources(cacheOperationSource); return interceptor; } From 126f7626191a56e1405a1a3a210122e6aebc62b9 Mon Sep 17 00:00:00 2001 From: saikat Date: Wed, 6 Mar 2024 15:25:04 +0530 Subject: [PATCH 28/59] reformated --- .../caching/twolevelcache/CacheConfig.java | 22 +++++++++---------- .../twolevelcache/CustomerService.java | 6 ++--- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java index b1bec0f4a1..576bcd97ab 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CacheConfig.java @@ -1,6 +1,7 @@ package com.baeldung.caching.twolevelcache; import com.github.benmanes.caffeine.cache.Caffeine; + import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.AnnotationCacheOperationSource; import org.springframework.cache.annotation.EnableCaching; @@ -35,26 +36,25 @@ public class CacheConfig { @Bean public CaffeineCache caffeineCacheConfig() { return new CaffeineCache("customerCache", Caffeine.newBuilder() - .expireAfterWrite(Duration.ofSeconds(3)) - .initialCapacity(1) - .maximumSize(2000) - .build()); + .expireAfterWrite(Duration.ofSeconds(3)) + .initialCapacity(1) + .maximumSize(2000) + .build()); } @Bean public CacheManager redisCacheManager(RedisConnectionFactory connectionFactory, RedisCacheConfiguration redisCacheConfiguration) { - return RedisCacheManager.RedisCacheManagerBuilder - .fromConnectionFactory(connectionFactory) - .withCacheConfiguration("customerCache", redisCacheConfiguration) - .build(); + return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(connectionFactory) + .withCacheConfiguration("customerCache", redisCacheConfiguration) + .build(); } @Bean public RedisCacheConfiguration cacheConfiguration() { return RedisCacheConfiguration.defaultCacheConfig() - .entryTtl(Duration.ofMinutes(5)) - .disableCachingNullValues() - .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); + .entryTtl(Duration.ofMinutes(5)) + .disableCachingNullValues() + .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); } @Bean diff --git a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java index 20bc91f7b2..088b66919c 100644 --- a/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java +++ b/spring-boot-modules/spring-caching-2/src/main/java/com/baeldung/caching/twolevelcache/CustomerService.java @@ -16,11 +16,11 @@ public class CustomerService { } @Caching(cacheable = { - @Cacheable(cacheNames = "customerCache", cacheManager = "caffeineCacheManager"), - @Cacheable(cacheNames = "customerCache", cacheManager = "redisCacheManager") + @Cacheable(cacheNames = "customerCache", cacheManager = "caffeineCacheManager"), + @Cacheable(cacheNames = "customerCache", cacheManager = "redisCacheManager") }) public Customer getCustomer(String id) { return customerRepository.findById(id) - .orElseThrow(RuntimeException::new); + .orElseThrow(RuntimeException::new); } } \ No newline at end of file From 38d0425b2fd1561f3c61f0b0140c5e401109471d Mon Sep 17 00:00:00 2001 From: "Kai.Yuan" Date: Sun, 10 Mar 2024 18:04:08 +0100 Subject: [PATCH 29/59] [calc-percentile] wip --- .../baeldung/percentile/CalculatePercentileUnitTest.java | 6 ++++++ core-java-modules/pom.xml | 1 + 2 files changed, 7 insertions(+) create mode 100644 core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java diff --git a/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java b/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java new file mode 100644 index 0000000000..b277ded6d8 --- /dev/null +++ b/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java @@ -0,0 +1,6 @@ +package com.baeldung.percentile; + +public class CalculatePercentileUnitTest { + + +} \ No newline at end of file diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 3d26d51a6a..cf15b823bb 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -144,6 +144,7 @@ core-java-lang-6 core-java-lang-math core-java-lang-math-2 + core-java-lang-math-4 core-java-lang-oop-constructors core-java-lang-oop-patterns core-java-lang-oop-generics From bd5512454dc4614b694970dcf162550c45695a42 Mon Sep 17 00:00:00 2001 From: "ICKostiantyn.Ivanov" Date: Mon, 11 Mar 2024 12:35:51 +0100 Subject: [PATCH 30/59] BAEL-6163 - Add code examples for the article "Querydsl vs. JPA Criteria" --- persistence-modules/querydsl/pom.xml | 47 ++- .../entities/GroupUser.java | 59 ++++ .../querydslvsjpacriteria/entities/Task.java | 43 +++ .../entities/UserGroup.java | 47 +++ .../UserGroupJpaSpecificationRepository.java | 25 ++ .../UserGroupQuerydslPredicateRepository.java | 27 ++ .../QuerydslVSJPACriteriaIntegrationTest.java | 270 ++++++++++++++++++ .../TimingExtension.java | 34 +++ 8 files changed, 546 insertions(+), 6 deletions(-) create mode 100644 persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/GroupUser.java create mode 100644 persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/Task.java create mode 100644 persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/UserGroup.java create mode 100644 persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupJpaSpecificationRepository.java create mode 100644 persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupQuerydslPredicateRepository.java create mode 100644 persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/QuerydslVSJPACriteriaIntegrationTest.java create mode 100644 persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/TimingExtension.java diff --git a/persistence-modules/querydsl/pom.xml b/persistence-modules/querydsl/pom.xml index 72cdb3a48a..c40b97d1b9 100644 --- a/persistence-modules/querydsl/pom.xml +++ b/persistence-modules/querydsl/pom.xml @@ -15,6 +15,18 @@ + + + org.springframework.boot + spring-boot-starter-data-jpa + ${spring-boot.version} + + + org.springframework.boot + spring-boot-starter-test + test + ${spring-boot.version} + com.querydsl @@ -36,6 +48,16 @@ ${hibernate-core.version} compile + + org.hibernate + hibernate-jpamodelgen + ${hibernate-core.version} + + + org.bsc.maven + maven-processor-plugin + 5.0 + commons-dbcp commons-dbcp @@ -103,24 +125,36 @@ ${maven-compiler-plugin.version} -proc:none + 17 + 17 - - com.mysema.maven - apt-maven-plugin - ${apt-maven-plugin.version} + org.bsc.maven + maven-processor-plugin + 5.0 + process process + generate-sources - target/generated-sources/java - com.querydsl.apt.jpa.JPAAnnotationProcessor + + org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor + com.querydsl.apt.jpa.JPAAnnotationProcessor + + + + org.hibernate + hibernate-jpamodelgen + ${hibernate-core.version} + + @@ -132,6 +166,7 @@ 1.4 1.1.3 6.4.2.Final + 3.2.3 \ No newline at end of file diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/GroupUser.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/GroupUser.java new file mode 100644 index 0000000000..32f35cbeb7 --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/GroupUser.java @@ -0,0 +1,59 @@ +package com.baeldung.querydslvsjpacriteria.entities; + +import java.util.HashSet; +import java.util.Set; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.OneToMany; + +@Entity +public class GroupUser { + + @Id + @GeneratedValue + private Long id; + + private String login; + + @ManyToMany(mappedBy = "groupUsers", cascade = CascadeType.PERSIST) + private Set userGroups = new HashSet<>(); + + @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "groupUser") + private Set tasks = new HashSet<>(0); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public Set getUserGroups() { + return userGroups; + } + + public void setUserGroups(Set userGroups) { + this.userGroups = userGroups; + } + + public Set getTasks() { + return tasks; + } + + public void setTasks(Set tasks) { + this.tasks = tasks; + } +} diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/Task.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/Task.java new file mode 100644 index 0000000000..ddb522711c --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/Task.java @@ -0,0 +1,43 @@ +package com.baeldung.querydslvsjpacriteria.entities; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToOne; + +@Entity +public class Task { + + @Id + @GeneratedValue + private Long id; + + private String description; + + @ManyToOne + private GroupUser groupUser; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public GroupUser getUser() { + return groupUser; + } + + public void setUser(GroupUser groupUser) { + this.groupUser = groupUser; + } +} diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/UserGroup.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/UserGroup.java new file mode 100644 index 0000000000..f6a8b52983 --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/entities/UserGroup.java @@ -0,0 +1,47 @@ +package com.baeldung.querydslvsjpacriteria.entities; + +import java.util.HashSet; +import java.util.Set; + +import jakarta.persistence.CascadeType; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.ManyToMany; + +@Entity +public class UserGroup { + + @Id + @GeneratedValue + private Long id; + + private String name; + + @ManyToMany(cascade = CascadeType.PERSIST) + private Set groupUsers = new HashSet<>(); + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Set getGroupUsers() { + return groupUsers; + } + + public void setGroupUsers(Set groupUsers) { + this.groupUsers = groupUsers; + } +} diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupJpaSpecificationRepository.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupJpaSpecificationRepository.java new file mode 100644 index 0000000000..72d14145af --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupJpaSpecificationRepository.java @@ -0,0 +1,25 @@ +package com.baeldung.querydslvsjpacriteria.repositories; + +import java.util.List; + +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; + +import com.baeldung.querydslvsjpacriteria.entities.UserGroup; +import com.baeldung.querydslvsjpacriteria.entities.UserGroup_; + +public interface UserGroupJpaSpecificationRepository extends JpaRepository, + JpaSpecificationExecutor { + + default List findAllWithNameInAnyList(List names1, List names2) { + return findAll(specNameInAnyList(names1, names2)); + } + + default Specification specNameInAnyList(List names1, List names2) { + return (root, q, cb) -> cb.or( + root.get(UserGroup_.name).in(names1), + root.get(UserGroup_.name).in(names2) + ); + } +} diff --git a/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupQuerydslPredicateRepository.java b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupQuerydslPredicateRepository.java new file mode 100644 index 0000000000..22d36e9cc8 --- /dev/null +++ b/persistence-modules/querydsl/src/main/java/com/baeldung/querydslvsjpacriteria/repositories/UserGroupQuerydslPredicateRepository.java @@ -0,0 +1,27 @@ +package com.baeldung.querydslvsjpacriteria.repositories; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.querydsl.QuerydslPredicateExecutor; + +import com.baeldung.querydslvsjpacriteria.entities.QUserGroup; +import com.baeldung.querydslvsjpacriteria.entities.UserGroup; +import com.querydsl.core.BooleanBuilder; +import com.querydsl.core.types.Predicate; + +public interface UserGroupQuerydslPredicateRepository extends JpaRepository, QuerydslPredicateExecutor { + + default List findAllWithNameInAnyList(List names1, List names2) { + return StreamSupport + .stream(findAll(predicateInAnyList(names1, names2)).spliterator(), false) + .collect(Collectors.toList()); + } + + default Predicate predicateInAnyList(List names1, List names2) { + return new BooleanBuilder().and(QUserGroup.userGroup.name.in(names1)) + .or(QUserGroup.userGroup.name.in(names2)); + } +} diff --git a/persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/QuerydslVSJPACriteriaIntegrationTest.java b/persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/QuerydslVSJPACriteriaIntegrationTest.java new file mode 100644 index 0000000000..7827430211 --- /dev/null +++ b/persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/QuerydslVSJPACriteriaIntegrationTest.java @@ -0,0 +1,270 @@ +package com.baeldung.querydslvsjpacriteria; + +import static com.baeldung.querydslvsjpacriteria.entities.GroupUser_.tasks; +import static com.baeldung.querydslvsjpacriteria.entities.QGroupUser.groupUser; +import static com.baeldung.querydslvsjpacriteria.entities.QTask.task; +import static com.baeldung.querydslvsjpacriteria.entities.QUserGroup.userGroup; +import static com.baeldung.querydslvsjpacriteria.entities.UserGroup_.GROUP_USERS; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.List; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import com.baeldung.querydslvsjpacriteria.entities.GroupUser; +import com.baeldung.querydslvsjpacriteria.entities.Task; +import com.baeldung.querydslvsjpacriteria.entities.UserGroup; +import com.baeldung.querydslvsjpacriteria.entities.UserGroup_; +import com.baeldung.querydslvsjpacriteria.repositories.UserGroupJpaSpecificationRepository; +import com.baeldung.querydslvsjpacriteria.repositories.UserGroupQuerydslPredicateRepository; +import com.querydsl.core.Tuple; +import com.querydsl.jpa.impl.JPAQueryFactory; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; +import jakarta.persistence.TypedQuery; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.CriteriaUpdate; +import jakarta.persistence.criteria.JoinType; +import jakarta.persistence.criteria.Root; + +@EnableJpaRepositories(basePackages = {"com.baeldung.querydslvsjpacriteria.repositories"}) +@ContextConfiguration("/test-context.xml") +@ExtendWith({SpringExtension.class, TimingExtension.class}) +class QuerydslVSJPACriteriaIntegrationTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(QuerydslVSJPACriteriaIntegrationTest.class); + + private static EntityManagerFactory emf; + + private EntityManager em; + + private JPAQueryFactory queryFactory; + + @Autowired + private UserGroupJpaSpecificationRepository userGroupJpaSpecificationRepository; + + @Autowired + private UserGroupQuerydslPredicateRepository userQuerydslPredicateRepository; + + @BeforeAll + static void populateDatabase() { + emf = Persistence.createEntityManagerFactory("com.baeldung.querydsl.intro"); + EntityManager em = emf.createEntityManager(); + em.getTransaction().begin(); + + Stream.of("Group 1", "Group 2", "Group 3") + .forEach(g -> { + UserGroup userGroup = new UserGroup(); + userGroup.setName(g); + em.persist(userGroup); + IntStream.range(0, 10) + .forEach(u -> { + GroupUser groupUser = new GroupUser(); + groupUser.setLogin("User" + u); + groupUser.getUserGroups().add(userGroup); + em.persist(groupUser); + userGroup.getGroupUsers().add(groupUser); + IntStream.range(0, 10000) + .forEach(t -> { + Task task = new Task(); + task.setDescription(groupUser.getLogin() + " task #" + t); + task.setUser(groupUser); + em.persist(task); + }); + }); + em.merge(userGroup); + }); + + em.getTransaction().commit(); + em.close(); + } + + @BeforeEach + void setUp() { + em = emf.createEntityManager(); + em.getTransaction().begin(); + queryFactory = new JPAQueryFactory(em); + + createUserGroup("Group 1"); + createUserGroup("Group 4"); + } + + @Test + void givenJpaCriteria_whenGetAllTheUserGroups_thenExpectedNumberOfItemsShouldBePresent() { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cr = cb.createQuery(UserGroup.class); + Root root = cr.from(UserGroup.class); + CriteriaQuery select = cr.select(root); + + TypedQuery query = em.createQuery(select); + List results = query.getResultList(); + assertEquals(3, results.size()); + } + + @Test + void givenQueryDSL_whenGetAllTheUserGroups_thenExpectedNumberOfItemsShouldBePresent() { + List results = queryFactory.selectFrom(userGroup).fetch(); + assertEquals(3, results.size()); + } + + @Test + void givenJpaCriteria_whenGetTheUserGroups_thenExpectedAggregatedDataShouldBePresent() { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery cr = cb.createQuery(Object[].class); + Root root = cr.from(UserGroup.class); + + CriteriaQuery select = cr + .multiselect(root.get(UserGroup_.name), cb.countDistinct(root.get(UserGroup_.id))) + .where(cb.or( + root.get(UserGroup_.name).in("Group 1", "Group 2"), + root.get(UserGroup_.name).in("Group 4", "Group 5") + )) + .orderBy(cb.desc(root.get(UserGroup_.name))) + .groupBy(root.get(UserGroup_.name)); + + TypedQuery query = em.createQuery(select); + List results = query.getResultList(); + assertEquals(2, results.size()); + assertEquals("Group 2", results.get(0)[0]); + assertEquals(1L, results.get(0)[1]); + assertEquals("Group 1", results.get(1)[0]); + assertEquals(1L, results.get(1)[1]); + } + + @Test + void givenQueryDSL_whenGetTheUserGroups_thenExpectedAggregatedDataShouldBePresent() { + List results = queryFactory + .select(userGroup.name, userGroup.id.countDistinct()) + .from(userGroup) + .where(userGroup.name.in("Group 1", "Group 2") + .or(userGroup.name.in("Group 4", "Group 5"))) + .orderBy(userGroup.name.desc()) + .groupBy(userGroup.name) + .fetch(); + + assertEquals(2, results.size()); + assertEquals("Group 2", results.get(0).get(userGroup.name)); + assertEquals(1L, results.get(0).get(userGroup.id.countDistinct())); + assertEquals("Group 1", results.get(1).get(userGroup.name)); + assertEquals(1L, results.get(1).get(userGroup.id.countDistinct())); + } + + @Test + void givenJpaCriteria_whenGetTheUserGroupsWithJoins_thenExpectedDataShouldBePresent() { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaQuery query = cb.createQuery(UserGroup.class); + + query.from(UserGroup.class) + .join(GROUP_USERS, JoinType.LEFT) + .join(tasks, JoinType.LEFT); + + List result = em.createQuery(query).getResultList(); + assertUserGroups(result); + } + + private void assertUserGroups(List userGroups) { + assertEquals(3, userGroups.size()); + for (UserGroup group : userGroups) { + assertEquals(10, group.getGroupUsers().size()); + for (GroupUser user : group.getGroupUsers()) { + assertEquals(10000, user.getTasks().size()); + } + } + } + + @Test + void givenQueryDSL_whenGetTheUserGroupsWithJoins_thenExpectedDataShouldBePresent() { + List result = queryFactory + .selectFrom(userGroup) + .leftJoin(userGroup.groupUsers, groupUser) + .leftJoin(groupUser.tasks, task) + .fetch(); + + assertUserGroups(result); + } + + @Test + void givenJpaCriteria_whenModifyTheUserGroup_thenNameShouldBeUpdated() { + CriteriaBuilder cb = em.getCriteriaBuilder(); + CriteriaUpdate criteriaUpdate = cb.createCriteriaUpdate(UserGroup.class); + Root root = criteriaUpdate.from(UserGroup.class); + criteriaUpdate.set(UserGroup_.name, "Group 1 Updated using Jpa Criteria"); + criteriaUpdate.where(cb.equal(root.get(UserGroup_.name), "Group 1")); + + em.createQuery(criteriaUpdate).executeUpdate(); + UserGroup foundGroup = em.find(UserGroup.class, 1L); + assertEquals("Group 1 Updated using Jpa Criteria", foundGroup.getName()); + renameEntityBack(foundGroup, "Group 1"); + } + + private void renameEntityBack(UserGroup foundGroup, String name) { + foundGroup.setName(name); + em.merge(foundGroup); + } + + @Test + void givenQueryDSL_whenModifyTheUserGroup_thenNameShouldBeUpdated() { + queryFactory.update(userGroup) + .set(userGroup.name, "Group 1 Updated Using QueryDSL") + .where(userGroup.name.eq("Group 1")) + .execute(); + + UserGroup foundGroup = em.find(UserGroup.class, 1L); + assertEquals("Group 1 Updated Using QueryDSL", foundGroup.getName()); + renameEntityBack(foundGroup, "Group 1"); + } + + @Test + void givenJpaSpecificationRepository_whenGetTheUserGroups_thenExpectedDataShouldBePresent() { + List results = userGroupJpaSpecificationRepository.findAllWithNameInAnyList( + List.of("Group 1", "Group 2"), List.of("Group 4", "Group 5")); + + assertEquals(2, results.size()); + assertEquals("Group 1", results.get(0).getName()); + assertEquals("Group 4", results.get(1).getName()); + } + + @Test + void givenQuerydslPredicateRepository_whenGetTheUserGroups_thenExpectedDataShouldBePresent() { + List results = userQuerydslPredicateRepository.findAllWithNameInAnyList( + List.of("Group 1", "Group 2"), List.of("Group 4", "Group 5")); + + assertEquals(2, results.size()); + assertEquals("Group 1", results.get(0).getName()); + assertEquals("Group 4", results.get(1).getName()); + } + + private void createUserGroup(String name) { + UserGroup entity = new UserGroup(); + entity.setName(name); + userGroupJpaSpecificationRepository.save(entity); + } + + @AfterEach + void tearDown() { + em.getTransaction().commit(); + em.close(); + userGroupJpaSpecificationRepository.deleteAll(); + } + + @AfterAll + static void afterClass() { + emf.close(); + } +} diff --git a/persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/TimingExtension.java b/persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/TimingExtension.java new file mode 100644 index 0000000000..1847dfb5be --- /dev/null +++ b/persistence-modules/querydsl/src/test/java/com/baeldung/querydslvsjpacriteria/TimingExtension.java @@ -0,0 +1,34 @@ +package com.baeldung.querydslvsjpacriteria; + +import java.lang.reflect.Method; + +import org.junit.jupiter.api.extension.AfterTestExecutionCallback; +import org.junit.jupiter.api.extension.BeforeTestExecutionCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.ExtensionContext.Namespace; +import org.junit.jupiter.api.extension.ExtensionContext.Store; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TimingExtension implements BeforeTestExecutionCallback, AfterTestExecutionCallback { + private static final Logger logger = LoggerFactory.getLogger(TimingExtension.class); + private static final String START_TIME = "start time"; + + @Override + public void beforeTestExecution(ExtensionContext context) { + getStore(context).put(START_TIME, System.currentTimeMillis()); + } + + @Override + public void afterTestExecution(ExtensionContext context) { + Method testMethod = context.getRequiredTestMethod(); + long startTime = getStore(context).remove(START_TIME, long.class); + long duration = System.currentTimeMillis() - startTime; + + logger.info(String.format("Method [%s] took %s ms.", testMethod.getName(), duration)); + } + + private Store getStore(ExtensionContext context) { + return context.getStore(Namespace.create(getClass(), context.getRequiredTestMethod())); + } +} From 2ef61a88842386be2d1df962b74e078b214f1c34 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Thu, 14 Mar 2024 14:35:48 -0400 Subject: [PATCH 31/59] Incorporated Review comments --- .../spring/kafka/start/stop/consumer/KafkaConsumerConfig.java | 4 ++-- .../stop/consumer}/StartStopConsumerLiveTest.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename spring-kafka-3/src/test/java/com/baeldung/spring/kafka/{startstopconsumer => start/stop/consumer}/StartStopConsumerLiveTest.java (98%) diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaConsumerConfig.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaConsumerConfig.java index 21f6270bca..f6b1d034a7 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaConsumerConfig.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaConsumerConfig.java @@ -23,7 +23,7 @@ public class KafkaConsumerConfig { @Bean public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory factory = - new ConcurrentKafkaListenerContainerFactory<>(); + new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory()); return factory; } @@ -37,6 +37,6 @@ public class KafkaConsumerConfig { props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); props.put(JsonDeserializer.TRUSTED_PACKAGES, "com.baeldung.spring.kafka.start.stop.consumer"); return new DefaultKafkaConsumerFactory<>(props, new StringDeserializer(), - new JsonDeserializer<>(UserEvent.class)); + new JsonDeserializer<>(UserEvent.class)); } } diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerLiveTest.java similarity index 98% rename from spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java rename to spring-kafka-3/src/test/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerLiveTest.java index 6405f75f91..5df40e6d4a 100644 --- a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerLiveTest.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.kafka.startstopconsumer; +package com.baeldung.spring.kafka.start.stop.consumer; import com.baeldung.spring.kafka.start.stop.consumer.*; import org.apache.kafka.clients.producer.KafkaProducer; From 4c484762583c1beb207e694b04f26139da78550d Mon Sep 17 00:00:00 2001 From: "Kai.Yuan" Date: Fri, 15 Mar 2024 14:45:38 +0100 Subject: [PATCH 32/59] [calc-percentile] calc percentile --- .../core-java-lang-math-4/README.md | 3 + .../core-java-lang-math-4/pom.xml | 15 ++++ .../CalculatePercentileUnitTest.java | 69 +++++++++++++++++++ 3 files changed, 87 insertions(+) create mode 100644 core-java-modules/core-java-lang-math-4/README.md create mode 100644 core-java-modules/core-java-lang-math-4/pom.xml diff --git a/core-java-modules/core-java-lang-math-4/README.md b/core-java-modules/core-java-lang-math-4/README.md new file mode 100644 index 0000000000..0c28f94821 --- /dev/null +++ b/core-java-modules/core-java-lang-math-4/README.md @@ -0,0 +1,3 @@ +========= + +### Relevant articles: diff --git a/core-java-modules/core-java-lang-math-4/pom.xml b/core-java-modules/core-java-lang-math-4/pom.xml new file mode 100644 index 0000000000..e818855d36 --- /dev/null +++ b/core-java-modules/core-java-lang-math-4/pom.xml @@ -0,0 +1,15 @@ + + + 4.0.0 + core-java-lang-math-4 + core-java-lang-math-4 + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + diff --git a/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java b/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java index b277ded6d8..84aac76b7e 100644 --- a/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java +++ b/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java @@ -1,6 +1,75 @@ package com.baeldung.percentile; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.LongStream; + +import org.junit.jupiter.api.Test; + public class CalculatePercentileUnitTest { + public static > T getPercentile(Collection input, double percentile) { + if (input == null || input.isEmpty()) { + throw new IllegalArgumentException("The input dataset cannot be null or empty."); + } + if (percentile < 0 || percentile > 100) { + throw new IllegalArgumentException("Percentile must be between 0 and 100(exclusive)"); + } + List sortedList = input.stream() + .sorted() + .collect(Collectors.toList()); + int rank = percentile == 0 ? 1 : (int) Math.ceil(percentile / 100.0 * input.size()); + return sortedList.get(rank - 1); + } + + @Test + void whenCallingGetPercentileWithAList_thenGetExpectedResult() { + assertThrows(IllegalArgumentException.class, () -> getPercentile(List.of(1, 2, 3), -1)); + assertThrows(IllegalArgumentException.class, () -> getPercentile(List.of(1, 2, 3), 101)); + + List list100 = IntStream.rangeClosed(1, 100) + .boxed() + .collect(Collectors.toList()); + Collections.shuffle(list100); + + assertEquals(10, getPercentile(list100, 10)); + assertEquals(25, getPercentile(list100, 25)); + assertEquals(50, getPercentile(list100, 50)); + assertEquals(76, getPercentile(list100, 75.3)); + + List list8 = IntStream.of(-1, 200, 30, 42, -5, 7, 8, 92) + .boxed() + .collect(Collectors.toList()); + + assertEquals(-5, getPercentile(list8, 10)); + assertEquals(-1, getPercentile(list8, 25)); + assertEquals(8, getPercentile(list8, 50)); + assertEquals(92, getPercentile(list8, 75.3)); + } + + @Test + void whenCallingGetPercentileWithAnArray_thenGetExpectedResult() { + + //prepare the input array + long[] theArray = LongStream.of(-1, 200, 30, 42, -5, 7, 8, 92) + .toArray(); + + //convert the long[] array to a List + List list8 = Arrays.stream(theArray) + .boxed() + .toList(); + + assertEquals(-5, getPercentile(list8, 10)); + assertEquals(-1, getPercentile(list8, 25)); + assertEquals(8, getPercentile(list8, 50)); + assertEquals(92, getPercentile(list8, 75.3)); + } } \ No newline at end of file From 2195e2c404160d0c59f5139910590cf52f0d931d Mon Sep 17 00:00:00 2001 From: "Kai.Yuan" Date: Fri, 15 Mar 2024 19:47:55 +0100 Subject: [PATCH 33/59] [calc-percentile] add 0 and 100 boundary test cases --- .../percentile/CalculatePercentileUnitTest.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java b/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java index 84aac76b7e..7b46b37e38 100644 --- a/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java +++ b/core-java-modules/core-java-lang-math-4/src/test/java/com/baeldung/percentile/CalculatePercentileUnitTest.java @@ -9,7 +9,6 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; -import java.util.stream.LongStream; import org.junit.jupiter.api.Test; @@ -40,36 +39,40 @@ public class CalculatePercentileUnitTest { .collect(Collectors.toList()); Collections.shuffle(list100); + assertEquals(1, getPercentile(list100, 0)); assertEquals(10, getPercentile(list100, 10)); assertEquals(25, getPercentile(list100, 25)); assertEquals(50, getPercentile(list100, 50)); assertEquals(76, getPercentile(list100, 75.3)); + assertEquals(100, getPercentile(list100, 100)); List list8 = IntStream.of(-1, 200, 30, 42, -5, 7, 8, 92) .boxed() .collect(Collectors.toList()); + assertEquals(-5, getPercentile(list8, 0)); assertEquals(-5, getPercentile(list8, 10)); assertEquals(-1, getPercentile(list8, 25)); assertEquals(8, getPercentile(list8, 50)); assertEquals(92, getPercentile(list8, 75.3)); + assertEquals(200, getPercentile(list8, 100)); } @Test void whenCallingGetPercentileWithAnArray_thenGetExpectedResult() { - //prepare the input array - long[] theArray = LongStream.of(-1, 200, 30, 42, -5, 7, 8, 92) - .toArray(); + long[] theArray = new long[] { -1, 200, 30, 42, -5, 7, 8, 92 }; //convert the long[] array to a List List list8 = Arrays.stream(theArray) .boxed() .toList(); + assertEquals(-5, getPercentile(list8, 0)); assertEquals(-5, getPercentile(list8, 10)); assertEquals(-1, getPercentile(list8, 25)); assertEquals(8, getPercentile(list8, 50)); assertEquals(92, getPercentile(list8, 75.3)); + assertEquals(200, getPercentile(list8, 100)); } } \ No newline at end of file From 9d0e847f15a9926c460d4152b7d1a67130f460a3 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 16 Mar 2024 18:08:45 +0530 Subject: [PATCH 34/59] JAVA-32180 Upgrade spring-kafka-3 to boot-3 (#16120) --- spring-kafka-3/pom.xml | 8 +++++--- .../deserialization/exception/KafkaErrorHandler.java | 3 ++- .../spring/kafka/viewheaders/KafkaMessageConsumer.java | 4 ++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/spring-kafka-3/pom.xml b/spring-kafka-3/pom.xml index 894eab2576..f94ce7748b 100644 --- a/spring-kafka-3/pom.xml +++ b/spring-kafka-3/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 4.0.0 @@ -22,6 +22,7 @@ org.springframework.kafka spring-kafka + ${spring-kafka.version} com.fasterxml.jackson.core @@ -54,8 +55,9 @@ 17 - 3.0.12 + 3.1.2 1.19.3 4.2.0 + org.springframework.boot.SpringApplication.Application diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/deserialization/exception/KafkaErrorHandler.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/deserialization/exception/KafkaErrorHandler.java index ea4211ab53..99d676e6c5 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/deserialization/exception/KafkaErrorHandler.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/deserialization/exception/KafkaErrorHandler.java @@ -13,8 +13,9 @@ class KafkaErrorHandler implements CommonErrorHandler { private static final Logger log = LoggerFactory.getLogger(KafkaErrorHandler.class); @Override - public void handleRecord(Exception exception, ConsumerRecord record, Consumer consumer, MessageListenerContainer container) { + public boolean handleOne(Exception exception, ConsumerRecord record, Consumer consumer, MessageListenerContainer container) { handle(exception, consumer); + return true; } @Override diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/viewheaders/KafkaMessageConsumer.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/viewheaders/KafkaMessageConsumer.java index 3bdc13d968..a9a414ac9f 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/viewheaders/KafkaMessageConsumer.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/viewheaders/KafkaMessageConsumer.java @@ -20,13 +20,13 @@ public class KafkaMessageConsumer { String topicName = (String) headers.get(KafkaHeaders.TOPIC); System.out.println("Topic: " + topicName); - int partitionID = (int) headers.get(KafkaHeaders.RECEIVED_PARTITION_ID); + int partitionID = (int) headers.get(KafkaHeaders.RECEIVED_PARTITION); System.out.println("Partition ID: " + partitionID); } @KafkaListener(topics = { "my-topic" }, groupId = "my-consumer-group") public void listen(@Payload String message, @Header(KafkaHeaders.RECEIVED_TOPIC) String topicName, - @Header(KafkaHeaders.RECEIVED_PARTITION_ID) int partition) { + @Header(KafkaHeaders.RECEIVED_PARTITION) int partition) { System.out.println("Topic: " + topicName); System.out.println("Partition ID: " + partition); } From 5102bc8766d7ba9e081fa59e4104663e6b3499d5 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Sat, 16 Mar 2024 18:20:00 +0530 Subject: [PATCH 35/59] JAVA-32170_D_G: Changes made for Fix formatting of POMs - D_G (#16113) --- deeplearning4j/pom.xml | 2 +- di-modules/guice/pom.xml | 2 +- di-modules/pom.xml | 2 +- disruptor/pom.xml | 2 +- docker-modules/docker-caching/multi-module-caching/pom.xml | 2 +- docker-modules/docker-caching/pom.xml | 2 +- docker-modules/docker-compose-2/pom.xml | 2 +- geotools/pom.xml | 2 +- google-auto-project/pom.xml | 2 +- google-cloud/pom.xml | 2 +- graphql-modules/pom.xml | 2 +- grpc/pom.xml | 2 +- guava-modules/pom.xml | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index deb5b34a39..bad7e8ecc1 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 deeplearning4j - deeplearning4j jar + deeplearning4j com.baeldung diff --git a/di-modules/guice/pom.xml b/di-modules/guice/pom.xml index d0d2876fc8..115bae5e7b 100644 --- a/di-modules/guice/pom.xml +++ b/di-modules/guice/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 guice - guice jar + guice com.baeldung diff --git a/di-modules/pom.xml b/di-modules/pom.xml index 984180cb28..b07d436867 100644 --- a/di-modules/pom.xml +++ b/di-modules/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 di-modules - di-modules pom + di-modules parent-modules diff --git a/disruptor/pom.xml b/disruptor/pom.xml index b3b065d67e..942eb83e7c 100644 --- a/disruptor/pom.xml +++ b/disruptor/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 disruptor - disruptor jar + disruptor com.baeldung diff --git a/docker-modules/docker-caching/multi-module-caching/pom.xml b/docker-modules/docker-caching/multi-module-caching/pom.xml index b9977f8f3a..3e9859a8d1 100644 --- a/docker-modules/docker-caching/multi-module-caching/pom.xml +++ b/docker-modules/docker-caching/multi-module-caching/pom.xml @@ -6,8 +6,8 @@ com.baeldung multi-module-caching 0.0.1-SNAPSHOT - Multi-module Maven caching example pom + Multi-module Maven caching example runner-module diff --git a/docker-modules/docker-caching/pom.xml b/docker-modules/docker-caching/pom.xml index 25572dfe4f..83cb7be9af 100644 --- a/docker-modules/docker-caching/pom.xml +++ b/docker-modules/docker-caching/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 docker-caching - docker-caching pom + docker-caching docker-modules diff --git a/docker-modules/docker-compose-2/pom.xml b/docker-modules/docker-compose-2/pom.xml index f7f01dc482..9d06aeb477 100644 --- a/docker-modules/docker-compose-2/pom.xml +++ b/docker-modules/docker-compose-2/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 docker-compose-2 - Demo project for Spring Boot and Docker - Module docker-compose-2 pom + Demo project for Spring Boot and Docker - Module docker-compose-2 com.baeldung diff --git a/geotools/pom.xml b/geotools/pom.xml index 61682ae0f5..026a902fa9 100644 --- a/geotools/pom.xml +++ b/geotools/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 geotools - geotools jar + geotools com.baeldung diff --git a/google-auto-project/pom.xml b/google-auto-project/pom.xml index 175e0c20c6..f91c0d56f4 100644 --- a/google-auto-project/pom.xml +++ b/google-auto-project/pom.xml @@ -5,8 +5,8 @@ 4.0.0 google-auto-project 1.0 - google-auto-project pom + google-auto-project com.baeldung diff --git a/google-cloud/pom.xml b/google-cloud/pom.xml index 8bb535f12a..b4cc3ba72f 100644 --- a/google-cloud/pom.xml +++ b/google-cloud/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 google-cloud - google-cloud jar + google-cloud Google Cloud Tutorials diff --git a/graphql-modules/pom.xml b/graphql-modules/pom.xml index 4b43cbffde..2525f75eff 100644 --- a/graphql-modules/pom.xml +++ b/graphql-modules/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.graphql graphql-modules - graphql-modules pom + graphql-modules com.baeldung diff --git a/grpc/pom.xml b/grpc/pom.xml index 758dc87c8f..31601a377e 100644 --- a/grpc/pom.xml +++ b/grpc/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 grpc - grpc jar + grpc com.baeldung diff --git a/guava-modules/pom.xml b/guava-modules/pom.xml index be5a48c0cf..6829a74e81 100644 --- a/guava-modules/pom.xml +++ b/guava-modules/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 guava-modules - guava-modules 0.0.1-SNAPSHOT pom + guava-modules com.baeldung From 012020c3121371697278ae54fa0719584f9684e1 Mon Sep 17 00:00:00 2001 From: Amol Gote Date: Sat, 16 Mar 2024 14:56:09 -0400 Subject: [PATCH 36/59] Incorporated Review comments for the package name. --- .../{start/stop/consumer => startstopconsumer}/Constants.java | 2 +- .../consumer => startstopconsumer}/KafkaConsumerConfig.java | 2 +- .../KafkaListenerControlService.java | 2 +- .../StartStopConsumerApplication.java | 2 +- .../{start/stop/consumer => startstopconsumer}/UserEvent.java | 2 +- .../stop/consumer => startstopconsumer}/UserEventListener.java | 2 +- .../stop/consumer => startstopconsumer}/UserEventStore.java | 2 +- .../StartStopConsumerLiveTest.java | 3 +-- 8 files changed, 8 insertions(+), 9 deletions(-) rename spring-kafka-3/src/main/java/com/baeldung/spring/kafka/{start/stop/consumer => startstopconsumer}/Constants.java (75%) rename spring-kafka-3/src/main/java/com/baeldung/spring/kafka/{start/stop/consumer => startstopconsumer}/KafkaConsumerConfig.java (97%) rename spring-kafka-3/src/main/java/com/baeldung/spring/kafka/{start/stop/consumer => startstopconsumer}/KafkaListenerControlService.java (94%) rename spring-kafka-3/src/main/java/com/baeldung/spring/kafka/{start/stop/consumer => startstopconsumer}/StartStopConsumerApplication.java (85%) rename spring-kafka-3/src/main/java/com/baeldung/spring/kafka/{start/stop/consumer => startstopconsumer}/UserEvent.java (86%) rename spring-kafka-3/src/main/java/com/baeldung/spring/kafka/{start/stop/consumer => startstopconsumer}/UserEventListener.java (93%) rename spring-kafka-3/src/main/java/com/baeldung/spring/kafka/{start/stop/consumer => startstopconsumer}/UserEventStore.java (89%) rename spring-kafka-3/src/test/java/com/baeldung/spring/kafka/{start/stop/consumer => startstopconsumer}/StartStopConsumerLiveTest.java (97%) diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/Constants.java similarity index 75% rename from spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java rename to spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/Constants.java index 9de3e117be..1b9f51f8a1 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/Constants.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/Constants.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.kafka.start.stop.consumer; +package com.baeldung.spring.kafka.startstopconsumer; public class Constants { public static final String MULTI_PARTITION_TOPIC = "multi_partition_topic"; diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaConsumerConfig.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/KafkaConsumerConfig.java similarity index 97% rename from spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaConsumerConfig.java rename to spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/KafkaConsumerConfig.java index f6b1d034a7..d37345d2de 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaConsumerConfig.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/KafkaConsumerConfig.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.kafka.start.stop.consumer; +package com.baeldung.spring.kafka.startstopconsumer; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.StringDeserializer; diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaListenerControlService.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/KafkaListenerControlService.java similarity index 94% rename from spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaListenerControlService.java rename to spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/KafkaListenerControlService.java index 64f7158a49..6d4c101c38 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/KafkaListenerControlService.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/KafkaListenerControlService.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.kafka.start.stop.consumer; +package com.baeldung.spring.kafka.startstopconsumer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.config.KafkaListenerEndpointRegistry; diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerApplication.java similarity index 85% rename from spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java rename to spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerApplication.java index c24517543b..f0cfe88717 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerApplication.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.kafka.start.stop.consumer; +package com.baeldung.spring.kafka.startstopconsumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEvent.java similarity index 86% rename from spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java rename to spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEvent.java index bfa8c72c39..1c4692b8ee 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEvent.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEvent.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.kafka.start.stop.consumer; +package com.baeldung.spring.kafka.startstopconsumer; public class UserEvent { private String userEventId; diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEventListener.java similarity index 93% rename from spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java rename to spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEventListener.java index d6338d7f3a..d68e70160f 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventListener.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEventListener.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.kafka.start.stop.consumer; +package com.baeldung.spring.kafka.startstopconsumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventStore.java b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEventStore.java similarity index 89% rename from spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventStore.java rename to spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEventStore.java index 071b39c7a3..3da6f7352d 100644 --- a/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/start/stop/consumer/UserEventStore.java +++ b/spring-kafka-3/src/main/java/com/baeldung/spring/kafka/startstopconsumer/UserEventStore.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.kafka.start.stop.consumer; +package com.baeldung.spring.kafka.startstopconsumer; import org.springframework.stereotype.Component; diff --git a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerLiveTest.java b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java similarity index 97% rename from spring-kafka-3/src/test/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerLiveTest.java rename to spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java index 5df40e6d4a..7ea8729111 100644 --- a/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/start/stop/consumer/StartStopConsumerLiveTest.java +++ b/spring-kafka-3/src/test/java/com/baeldung/spring/kafka/startstopconsumer/StartStopConsumerLiveTest.java @@ -1,6 +1,5 @@ -package com.baeldung.spring.kafka.start.stop.consumer; +package com.baeldung.spring.kafka.startstopconsumer; -import com.baeldung.spring.kafka.start.stop.consumer.*; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; From 23a43d837b208fe6d8f840c78dd2e20db93cee4a Mon Sep 17 00:00:00 2001 From: vunamtien Date: Sun, 17 Mar 2024 17:46:45 +0700 Subject: [PATCH 37/59] [JAVA-27510] Upgrade vaadin to boot 3 (#16122) --- vaadin/pom.xml | 5 +++-- vaadin/src/main/java/com/baeldung/Employee.java | 6 +++--- .../src/main/java/com/baeldung/introduction/VaadinUI.java | 3 +-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/vaadin/pom.xml b/vaadin/pom.xml index aa37a2392a..e3786471f5 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -32,6 +32,7 @@ javax.servlet javax.servlet-api + 4.0.1 provided diff --git a/vaadin/src/main/java/com/baeldung/Employee.java b/vaadin/src/main/java/com/baeldung/Employee.java index 726f0838b6..75a0dc84b3 100644 --- a/vaadin/src/main/java/com/baeldung/Employee.java +++ b/vaadin/src/main/java/com/baeldung/Employee.java @@ -1,8 +1,8 @@ package com.baeldung; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; @Entity public class Employee { diff --git a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java index 22ce19f5e0..05a8340bde 100644 --- a/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java +++ b/vaadin/src/main/java/com/baeldung/introduction/VaadinUI.java @@ -8,8 +8,6 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; -import javax.servlet.annotation.WebServlet; - import com.vaadin.annotations.Push; import com.vaadin.annotations.Theme; import com.vaadin.annotations.VaadinServletConfiguration; @@ -41,6 +39,7 @@ import com.vaadin.ui.TextField; import com.vaadin.ui.TwinColSelect; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; +import jakarta.servlet.annotation.WebServlet; @SuppressWarnings("serial") @Push From ed0991ca5c86b790cf32fdad7973d5b6a77bbe14 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Sun, 17 Mar 2024 16:19:56 +0530 Subject: [PATCH 38/59] JAVA-32170_H_J: Changes made for Fix formatting of POMs H_J (#16114) --- httpclient-simple/pom.xml | 2 +- jackson-modules/jackson-jr/pom.xml | 2 +- jackson-modules/pom.xml | 2 +- java-blockchain/pom.xml | 2 +- java-jdi/pom.xml | 2 +- java-panama/pom.xml | 2 +- javax-sound/pom.xml | 2 +- jenkins-modules/pom.xml | 2 +- jetbrains/pom.xml | 2 +- jgit/pom.xml | 2 +- jhipster-6/pom.xml | 2 +- jhipster-modules/jhipster-uaa/pom.xml | 2 +- jhipster-modules/pom.xml | 2 +- jmh/pom.xml | 2 +- json-modules/pom.xml | 2 +- jsoup/pom.xml | 2 +- jws/pom.xml | 2 +- 17 files changed, 17 insertions(+), 17 deletions(-) diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index 50b6f0b9f2..aaf00b2588 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 httpclient-simple - httpclient-simple war + httpclient-simple com.baeldung diff --git a/jackson-modules/jackson-jr/pom.xml b/jackson-modules/jackson-jr/pom.xml index 868c3ee17f..fdd7d85c70 100644 --- a/jackson-modules/jackson-jr/pom.xml +++ b/jackson-modules/jackson-jr/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jackson-jr - jackson-jr pom + jackson-jr com.baeldung diff --git a/jackson-modules/pom.xml b/jackson-modules/pom.xml index f4980445b3..4b249f12d2 100644 --- a/jackson-modules/pom.xml +++ b/jackson-modules/pom.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jackson-modules - jackson-modules 0.0.1-SNAPSHOT pom + jackson-modules com.baeldung diff --git a/java-blockchain/pom.xml b/java-blockchain/pom.xml index 422867176f..06838b8080 100644 --- a/java-blockchain/pom.xml +++ b/java-blockchain/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.blockchain java-blockchain - java-blockchain jar + java-blockchain com.baeldung diff --git a/java-jdi/pom.xml b/java-jdi/pom.xml index 22d7743998..935d2a23e4 100644 --- a/java-jdi/pom.xml +++ b/java-jdi/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 java-jdi - java-jdi jar + java-jdi com.baeldung diff --git a/java-panama/pom.xml b/java-panama/pom.xml index 61c8f2c5be..75835ac693 100644 --- a/java-panama/pom.xml +++ b/java-panama/pom.xml @@ -5,8 +5,8 @@ com.baeldung.java.panama java-panama 1.0 - java-panama jar + java-panama diff --git a/javax-sound/pom.xml b/javax-sound/pom.xml index 6652022a40..bea1d7f93b 100644 --- a/javax-sound/pom.xml +++ b/javax-sound/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.javax-sound javax-sound - javax-sound jar + javax-sound com.baeldung diff --git a/jenkins-modules/pom.xml b/jenkins-modules/pom.xml index 5cbc47d1f4..7543f82145 100644 --- a/jenkins-modules/pom.xml +++ b/jenkins-modules/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jenkins-modules - jenkins-modules pom + jenkins-modules parent-modules diff --git a/jetbrains/pom.xml b/jetbrains/pom.xml index 78d8b36b77..c1c7b8cdd8 100644 --- a/jetbrains/pom.xml +++ b/jetbrains/pom.xml @@ -5,8 +5,8 @@ 4.0.0 jetbrains 1.0-SNAPSHOT - jetbrains jar + jetbrains com.baeldung diff --git a/jgit/pom.xml b/jgit/pom.xml index 4e88808097..e91d3ae07b 100644 --- a/jgit/pom.xml +++ b/jgit/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jgit - jgit jar + jgit com.baeldung diff --git a/jhipster-6/pom.xml b/jhipster-6/pom.xml index f2406d1bdb..b51aca02e3 100644 --- a/jhipster-6/pom.xml +++ b/jhipster-6/pom.xml @@ -5,8 +5,8 @@ com.baeldung.jhipster jhipster-6 1.0.0-SNAPSHOT - jhipster-6 pom + jhipster-6 parent-boot-2 diff --git a/jhipster-modules/jhipster-uaa/pom.xml b/jhipster-modules/jhipster-uaa/pom.xml index 7c60f95e28..9085a07f0f 100644 --- a/jhipster-modules/jhipster-uaa/pom.xml +++ b/jhipster-modules/jhipster-uaa/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 jhipster-uaa - jhipster-uaa pom + jhipster-uaa jhipster-modules diff --git a/jhipster-modules/pom.xml b/jhipster-modules/pom.xml index 1e11d97f40..810f2b0c59 100644 --- a/jhipster-modules/pom.xml +++ b/jhipster-modules/pom.xml @@ -6,8 +6,8 @@ com.baeldung.jhipster jhipster-modules 1.0.0-SNAPSHOT - jhipster-modules pom + jhipster-modules - + spring-boot-runtime + spring-boot-runtime-2 spring-boot-security spring-boot-security-2 spring-boot-ssl-bundles diff --git a/spring-boot-modules/spring-boot-runtime-2/pom.xml b/spring-boot-modules/spring-boot-runtime-2/pom.xml index 356880975a..c925735817 100644 --- a/spring-boot-modules/spring-boot-runtime-2/pom.xml +++ b/spring-boot-modules/spring-boot-runtime-2/pom.xml @@ -75,5 +75,6 @@ 3.1.3 + com.baeldung.heap.HeapSizeDemoApplication \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime/pom.xml b/spring-boot-modules/spring-boot-runtime/pom.xml index 4cffc9a311..e43d6b0eb0 100644 --- a/spring-boot-modules/spring-boot-runtime/pom.xml +++ b/spring-boot-modules/spring-boot-runtime/pom.xml @@ -69,8 +69,8 @@ runtime - javax.persistence - javax.persistence-api + jakarta.persistence + jakarta.persistence-api org.subethamail @@ -79,14 +79,16 @@ test - org.apache.httpcomponents - httpclient + org.apache.httpcomponents.client5 + httpclient5 + 5.3.1 3.1.7 3.1.3 + com.baeldung.shutdown.Application \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java index 11ea5b70c9..9539b17c88 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/MyFooController.java @@ -4,7 +4,7 @@ import java.util.Collection; import java.util.HashMap; import java.util.Map; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java index 321f3be3ef..0f596f5816 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/sampleapp/web/controller/redirect/RedirectController.java @@ -1,6 +1,6 @@ package com.baeldung.sampleapp.web.controller.redirect; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/TerminateBean.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/TerminateBean.java index 4f3b81b920..1a0288b3dc 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/TerminateBean.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/shutdown/TerminateBean.java @@ -1,6 +1,6 @@ package com.baeldung.shutdown; -import javax.annotation.PreDestroy; +import jakarta.annotation.PreDestroy; public class TerminateBean { diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java index 6870f4e6bb..03f4959fbc 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/logging/SecurityConfig.java @@ -9,8 +9,8 @@ import org.springframework.security.web.SecurityFilterChain; public class SecurityConfig { @Bean public SecurityFilterChain securityFilter(HttpSecurity http) throws Exception { - return http.csrf() - .ignoringAntMatchers("/actuator/**").and() + return http + .csrf(csrf -> csrf.ignoringRequestMatchers("/actuator/**") ) .build(); } } diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/CustomTraceRepository.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/CustomTraceRepository.java index d85c043dc0..6dd2ab446b 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/CustomTraceRepository.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/CustomTraceRepository.java @@ -4,22 +4,23 @@ import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicReference; -import org.springframework.boot.actuate.trace.http.HttpTrace; -import org.springframework.boot.actuate.trace.http.HttpTraceRepository; +import org.apache.hc.client5.http.classic.methods.HttpTrace; +import org.springframework.boot.actuate.web.exchanges.HttpExchange; +import org.springframework.boot.actuate.web.exchanges.HttpExchangeRepository; import org.springframework.stereotype.Repository; @Repository -public class CustomTraceRepository implements HttpTraceRepository { +public class CustomTraceRepository implements HttpExchangeRepository { - AtomicReference lastTrace = new AtomicReference<>(); + AtomicReference lastTrace = new AtomicReference<>(); @Override - public List findAll() { + public List findAll() { return Collections.singletonList(lastTrace.get()); } @Override - public void add(HttpTrace trace) { + public void add(HttpExchange trace) { if ("GET".equals(trace.getRequest() .getMethod())) { lastTrace.set(trace); diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/TraceRequestFilter.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/TraceRequestFilter.java index fd6312df47..285c538580 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/TraceRequestFilter.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/spring/boot/management/trace/TraceRequestFilter.java @@ -1,23 +1,22 @@ package com.baeldung.spring.boot.management.trace; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; -import org.springframework.boot.actuate.trace.http.HttpExchangeTracer; -import org.springframework.boot.actuate.trace.http.HttpTraceRepository; -import org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter; +import org.springframework.boot.actuate.web.exchanges.HttpExchangeRepository; +import org.springframework.boot.actuate.web.exchanges.Include; +import org.springframework.boot.actuate.web.exchanges.servlet.HttpExchangesFilter; import org.springframework.stereotype.Component; @Component -public class TraceRequestFilter extends HttpTraceFilter { +public class TraceRequestFilter extends HttpExchangesFilter { /** - * Create a new {@link HttpTraceFilter} instance. + * Create a new {@link HttpExchangesFilter} instance. * * @param repository the trace repository - * @param tracer used to trace exchanges */ - public TraceRequestFilter(HttpTraceRepository repository, HttpExchangeTracer tracer) { - super(repository, tracer); + public TraceRequestFilter(HttpExchangeRepository repository) { + super(repository, Include.defaultIncludes()); } @Override diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedHttpServletRequest.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedHttpServletRequest.java index 51bbd51ea8..cc2257701a 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedHttpServletRequest.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedHttpServletRequest.java @@ -2,9 +2,9 @@ package com.baeldung.web.log.app; import org.springframework.util.StreamUtils; -import javax.servlet.ServletInputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; import java.io.*; public class CachedHttpServletRequest extends HttpServletRequestWrapper { diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedServletInputStream.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedServletInputStream.java index 673d04876b..fcea7b96cf 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedServletInputStream.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/CachedServletInputStream.java @@ -3,8 +3,8 @@ package com.baeldung.web.log.app; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.servlet.ReadListener; -import javax.servlet.ServletInputStream; +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/RequestCachingFilter.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/RequestCachingFilter.java index e0928550fc..607404831a 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/RequestCachingFilter.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/app/RequestCachingFilter.java @@ -8,11 +8,11 @@ import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebFilter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebFilter; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.StandardCharsets; diff --git a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java index b1ddf16dfe..9c5cc731e2 100644 --- a/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java +++ b/spring-boot-modules/spring-boot-runtime/src/main/java/com/baeldung/web/log/controller/TaxiFareController.java @@ -1,6 +1,6 @@ package com.baeldung.web.log.controller; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; From d58345c913d124ad07b80f823e5b1443d73b9900 Mon Sep 17 00:00:00 2001 From: Amit Pandey Date: Sun, 17 Mar 2024 18:12:29 +0530 Subject: [PATCH 42/59] JAVA-30991 :- Upgrade spring-boot-custom-starter to Boot 3. (#16140) * JAVA-30991 :- Upgrade spring-boot-custom-starter to Boot 3. * JAVA-30991 :- Upgrade spring-boot-custom-starter to Boot 3. * JAVA-30991 :- Remove unnecessary imports. * JAVA-30991 :- Used same parent pom and uncommented in the parent module. --- spring-boot-modules/pom.xml | 2 +- .../greeter/{sample => }/GreeterSampleApplication.java | 3 +-- .../src/test/java/com/baeldung/SpringContextTest.java | 2 +- .../GreeterSampleApplicationIntegrationTest.java | 2 +- spring-boot-modules/spring-boot-custom-starter/pom.xml | 5 +++++ 5 files changed, 9 insertions(+), 5 deletions(-) rename spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/{sample => }/GreeterSampleApplication.java (94%) rename spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/{sample => }/GreeterSampleApplicationIntegrationTest.java (97%) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index ae984f2b77..3f6670448b 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -35,7 +35,7 @@ spring-boot-disable-logging spring-boot-ci-cd - + spring-boot-custom-starter spring-boot-crud spring-boot-data spring-boot-environment diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/GreeterSampleApplication.java similarity index 94% rename from spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/GreeterSampleApplication.java index 5aa3ac7015..f573179c29 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/sample/GreeterSampleApplication.java +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/main/java/com/baeldung/greeter/GreeterSampleApplication.java @@ -1,4 +1,4 @@ -package com.baeldung.greeter.sample; +package com.baeldung.greeter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; @@ -6,7 +6,6 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.baeldung.greeter.library.Greeter; - @SpringBootApplication public class GreeterSampleApplication implements CommandLineRunner { diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java index 7103da97f3..e446dddc69 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/SpringContextTest.java @@ -5,7 +5,7 @@ import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import com.baeldung.greeter.sample.GreeterSampleApplication; +import com.baeldung.greeter.GreeterSampleApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = GreeterSampleApplication.class) diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/GreeterSampleApplicationIntegrationTest.java similarity index 97% rename from spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/GreeterSampleApplicationIntegrationTest.java index 50193ccd60..e53be5fafd 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/sample/GreeterSampleApplicationIntegrationTest.java +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-sample-app/src/test/java/com/baeldung/greeter/GreeterSampleApplicationIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.greeter.sample; +package com.baeldung.greeter; import static org.junit.Assert.assertEquals; diff --git a/spring-boot-modules/spring-boot-custom-starter/pom.xml b/spring-boot-modules/spring-boot-custom-starter/pom.xml index aee98b125e..d18aabac19 100644 --- a/spring-boot-modules/spring-boot-custom-starter/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/pom.xml @@ -23,4 +23,9 @@ parent-multi-module + + true + 3.2.2 + + \ No newline at end of file From 9bc0f1a4c20c6897e31c34c613d13bb59aff0ed6 Mon Sep 17 00:00:00 2001 From: Zeeshan Arif Date: Sun, 17 Mar 2024 18:58:50 +0500 Subject: [PATCH 43/59] BAEL-7460: Hibernate: Refresh, Evict, Replicate and Flush Created test cases for refresh() and replicate() Hibernate methods & Fixed indentation --- .../save/SaveMethodsIntegrationTest.java | 233 ++++++++++++------ .../src/test/resources/h2-trigger.sql | 5 + 2 files changed, 164 insertions(+), 74 deletions(-) create mode 100644 persistence-modules/hibernate-enterprise/src/test/resources/h2-trigger.sql diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java index 921459ac46..41924ad33f 100644 --- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java +++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java @@ -9,7 +9,9 @@ import static org.junit.Assert.assertSame; import jakarta.persistence.PersistenceException; +import org.h2.tools.RunScript; import org.hibernate.HibernateException; +import org.hibernate.ReplicationMode; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; @@ -24,35 +26,58 @@ import org.junit.Test; import com.baeldung.persistence.model.Person; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.sql.Connection; +import java.sql.DriverManager; + /** * Testing specific implementation details for different methods: - * persist, save, merge, update, saveOrUpdate. + * persist, save, merge, update, saveOrUpdate, refresh, replicate */ public class SaveMethodsIntegrationTest { - private static SessionFactory sessionFactory; + private static SessionFactory sessionFactory1; - private Session session; + private static SessionFactory sessionFactory2; + + private Session session1; + + private Session session2; private boolean doNotCommit = false; - @BeforeClass - public static void beforeTests() { + private static SessionFactory createSessionFactoryAndInitializeDBs(String dbUrl) throws Exception { Configuration configuration = new Configuration().addAnnotatedClass(Person.class) - .setProperty("hibernate.dialect", HSQLDialect.class.getName()) - .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) - .setProperty("hibernate.connection.url", "jdbc:hsqldb:mem:test") - .setProperty("hibernate.connection.username", "sa") - .setProperty("hibernate.connection.password", "") - .setProperty("hibernate.hbm2ddl.auto", "update"); + .setProperty("hibernate.dialect", HSQLDialect.class.getName()) + .setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName()) + .setProperty("hibernate.connection.url", dbUrl) + .setProperty("hibernate.connection.username", "sa") + .setProperty("hibernate.connection.password", "") + .setProperty("hibernate.hbm2ddl.auto", "update"); + Connection connection = DriverManager.getConnection(dbUrl, "sa", ""); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) - .build(); - sessionFactory = configuration.buildSessionFactory(serviceRegistry); + .build(); + SessionFactory sf = configuration.buildSessionFactory(serviceRegistry); + try (InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("h2-trigger.sql")) { + assert h2InitStream != null; + try (InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) { + RunScript.execute(connection, h2InitReader); + } + } + return sf; + } + @BeforeClass + public static void beforeTests() throws Exception{ + sessionFactory1 = createSessionFactoryAndInitializeDBs("jdbc:hsqldb:mem:test"); + sessionFactory2 = createSessionFactoryAndInitializeDBs("jdbc:hsqldb:mem:test2"); + } @Before - public void setUp() { - session = sessionFactory.openSession(); - session.beginTransaction(); + public void setUp() throws Exception { + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); + doNotCommit = false; } @@ -61,16 +86,16 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.persist(person); + session1.persist(person); - session.getTransaction() - .commit(); - session.close(); + session1.getTransaction() + .commit(); + session1.close(); - session = sessionFactory.openSession(); - session.beginTransaction(); + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); - assertNotNull(session.get(Person.class, person.getId())); + assertNotNull(session1.get(Person.class, person.getId())); } @@ -80,10 +105,10 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.persist(person); + session1.persist(person); Long id1 = person.getId(); - session.persist(person); + session1.persist(person); Long id2 = person.getId(); assertEquals(id1, id2); @@ -93,13 +118,13 @@ public class SaveMethodsIntegrationTest { public void whenPersistDetached_thenThrowsException() { doNotCommit = true; - + Person person = new Person(); person.setName("John"); - session.persist(person); - session.evict(person); - - session.persist(person); + session1.persist(person); + session1.evict(person); + + session1.persist(person); } @Test @@ -107,12 +132,12 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.save(person); - session.flush(); - session.evict(person); + session1.save(person); + session1.flush(); + session1.evict(person); person.setName("Mary"); - Person mergedPerson = (Person) session.merge(person); + Person mergedPerson = (Person) session1.merge(person); assertNotSame(person, mergedPerson); assertEquals("Mary", mergedPerson.getName()); @@ -127,20 +152,20 @@ public class SaveMethodsIntegrationTest { assertNull(person.getId()); - Long id = (Long) session.save(person); + Long id = (Long) session1.save(person); assertNotNull(id); - session.getTransaction() - .commit(); - session.close(); + session1.getTransaction() + .commit(); + session1.close(); assertEquals(id, person.getId()); - session = sessionFactory.openSession(); - session.beginTransaction(); + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); - assertNotNull(session.get(Person.class, person.getId())); + assertNotNull(session1.get(Person.class, person.getId())); } @@ -149,8 +174,8 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - Long id1 = (Long) session.save(person); - Long id2 = (Long) session.save(person); + Long id1 = (Long) session1.save(person); + Long id2 = (Long) session1.save(person); assertEquals(id1, id2); } @@ -160,10 +185,10 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - Long id1 = (Long) session.save(person); - session.evict(person); + Long id1 = (Long) session1.save(person); + session1.evict(person); - Long id2 = (Long) session.save(person); + Long id2 = (Long) session1.save(person); assertNotEquals(id1, id2); } @@ -173,11 +198,11 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - Person mergedPerson = (Person) session.merge(person); + Person mergedPerson = (Person) session1.merge(person); - session.getTransaction() - .commit(); - session.beginTransaction(); + session1.getTransaction() + .commit(); + session1.beginTransaction(); assertNotNull(person.getId()); assertNotNull(mergedPerson.getId()); @@ -189,9 +214,9 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.save(person); + session1.save(person); - Person mergedPerson = (Person) session.merge(person); + Person mergedPerson = (Person) session1.merge(person); assertSame(person, mergedPerson); @@ -202,11 +227,11 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.save(person); - session.evict(person); + session1.save(person); + session1.evict(person); person.setName("Mary"); - session.update(person); + session1.update(person); assertEquals("Mary", person.getName()); } @@ -216,7 +241,7 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.update(person); + session1.update(person); } @@ -225,9 +250,9 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.save(person); + session1.save(person); - session.update(person); + session1.update(person); } @@ -236,11 +261,11 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.save(person); - session.evict(person); + session1.save(person); + session1.evict(person); person.setName("Mary"); - session.saveOrUpdate(person); + session1.saveOrUpdate(person); assertEquals("Mary", person.getName()); } @@ -250,16 +275,75 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.saveOrUpdate(person); + session1.saveOrUpdate(person); - session.getTransaction() - .commit(); - session.close(); + session1.getTransaction() + .commit(); + session1.close(); - session = sessionFactory.openSession(); - session.beginTransaction(); + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); - assertNotNull(session.get(Person.class, person.getId())); + assertNotNull(session1.get(Person.class, person.getId())); + + } + + @Test + public void whenSaveAndTriggerUpdatedAndRefresh_thenRefreshPersistentEntity() { + + Person person = new Person(); + person.setName("Zeeshan Arif"); + session1.persist(person); + session1.getTransaction() + .commit(); + session1.close(); + + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); + session1.refresh(person); + session1.getTransaction() + .commit(); + session1.close(); + + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); + assertEquals(person.getName(), "Neymar Santos"); + + } + + @Test + public void whenReplicate_thenRefreshPersistentEntity() { + + Person p = new Person(); + p.setName("Ronaldinho Gaucho"); + session1.persist(p); + session1.getTransaction() + .commit(); + session1.close(); + + Session session2 = sessionFactory2.openSession(); + session2.beginTransaction(); + session2.replicate(p, ReplicationMode.LATEST_VERSION); + session2.getTransaction() + .commit(); + session2.close(); + + session2 = sessionFactory2.openSession(); + session2.beginTransaction(); + Person actual = session2.get(Person.class, p.getId()); + session2.getTransaction().commit(); + session2.close(); + + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); + Person expected = session1.get(Person.class, p.getId()); + session1.getTransaction().commit(); + session1.close(); + + session1 = sessionFactory1.openSession(); + session1.beginTransaction(); + assertEquals(expected.getId(), actual.getId()); + assertEquals(expected.getName(), actual.getName()); } @@ -268,24 +352,25 @@ public class SaveMethodsIntegrationTest { Person person = new Person(); person.setName("John"); - session.save(person); + session1.save(person); - session.saveOrUpdate(person); + session1.saveOrUpdate(person); } @After public void tearDown() { if (!doNotCommit) { - session.getTransaction() - .commit(); + session1.getTransaction() + .commit(); } - session.close(); + session1.close(); } @AfterClass public static void afterTests() { - sessionFactory.close(); + sessionFactory1.close(); + sessionFactory2.close(); } } diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/h2-trigger.sql b/persistence-modules/hibernate-enterprise/src/test/resources/h2-trigger.sql new file mode 100644 index 0000000000..a54b5c5003 --- /dev/null +++ b/persistence-modules/hibernate-enterprise/src/test/resources/h2-trigger.sql @@ -0,0 +1,5 @@ +CREATE TRIGGER IF NOT EXISTS TGR_UpdatePersonName AFTER INSERT +ON Person FOR EACH ROW UPDATE PERSON SET NAME = 'Neymar Santos' where NAME = 'Zeeshan Arif' + + + From ef96037176eb3045f762a934bb81d477c0d30302 Mon Sep 17 00:00:00 2001 From: Amit Pandey Date: Sun, 17 Mar 2024 19:36:36 +0530 Subject: [PATCH 44/59] JAVA-31001: Upgrade spring-boot-springdoc to boot 3 (#16139) * JAVA-31001: Upgrade spring-boot-springdoc * JAVA-31001: Upgrade spring-boot-springdoc * JAVA-31001: Upgrade spring-boot-springdoc. * Uncomment in Parent module POM. * JAVA-31001: Upgrade spring-boot-springdoc parent. --- spring-boot-modules/pom.xml | 2 +- spring-boot-modules/spring-boot-springdoc/pom.xml | 5 +++-- .../DefaultGlobalSecuritySchemeApplication.java | 2 +- .../DefaultGlobalSecuritySchemeOpenApiController.java | 2 +- .../defaultglobalsecurityscheme/dto/LoginDto.java | 3 ++- .../dto/PingResponseDto.java | 5 +++-- .../java/com/baeldung/jwt/SecurityConfiguration.java | 11 ++++++----- .../main/java/com/baeldung/restdocopenapi/Foo.java | 10 +++++----- .../com/baeldung/restdocopenapi/FooController.java | 2 +- .../com/baeldung/restdocopenapi/FooRepository.java | 3 ++- .../restdocopenapi/springdoc/FooBarController.java | 2 +- .../baeldung/springdoc/controller/BookController.java | 4 ++-- .../main/java/com/baeldung/springdoc/kotlin/Foo.kt | 9 ++++----- .../com/baeldung/springdoc/kotlin/FooController.kt | 3 ++- .../main/java/com/baeldung/springdoc/model/Book.java | 4 ++-- .../com/baeldung/jwt/OpenApiJwtIntegrationTest.java | 5 ++++- 16 files changed, 40 insertions(+), 32 deletions(-) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 3f6670448b..529bf595bc 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -72,7 +72,7 @@ spring-boot-security-2 spring-boot-ssl-bundles spring-boot-telegram - + spring-boot-springdoc spring-boot-swagger-jwt diff --git a/spring-boot-modules/spring-boot-springdoc/pom.xml b/spring-boot-modules/spring-boot-springdoc/pom.xml index 8ed9b7c22b..567ff5a606 100644 --- a/spring-boot-modules/spring-boot-springdoc/pom.xml +++ b/spring-boot-modules/spring-boot-springdoc/pom.xml @@ -119,10 +119,11 @@ - 1.7.0 - 1.5.6 + 1.8.0 + 2.2.6 ${project.build.directory}/generated-snippets 1.4 + true \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/DefaultGlobalSecuritySchemeApplication.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/DefaultGlobalSecuritySchemeApplication.java index 1ce81a1e83..fda191f785 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/DefaultGlobalSecuritySchemeApplication.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/DefaultGlobalSecuritySchemeApplication.java @@ -19,7 +19,7 @@ import io.swagger.v3.oas.annotations.security.SecurityScheme; public class DefaultGlobalSecuritySchemeApplication { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - return http.authorizeHttpRequests(authorizeRequests -> authorizeRequests.antMatchers("/api/auth/**", "/swagger-ui-custom.html", "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**", "/swagger-ui/index.html", "/api-docs/**") + return http.authorizeHttpRequests(authorizeRequests -> authorizeRequests.requestMatchers("/api/auth/**", "/swagger-ui-custom.html", "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**", "/swagger-ui/index.html", "/api-docs/**") .permitAll() .anyRequest() .authenticated()) diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/controller/DefaultGlobalSecuritySchemeOpenApiController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/controller/DefaultGlobalSecuritySchemeOpenApiController.java index 4ad7a2a2c3..9b3d6ef545 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/controller/DefaultGlobalSecuritySchemeOpenApiController.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/controller/DefaultGlobalSecuritySchemeOpenApiController.java @@ -3,7 +3,7 @@ package com.baeldung.defaultglobalsecurityscheme.controller; import java.time.OffsetDateTime; import java.time.ZoneOffset; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/LoginDto.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/LoginDto.java index cf88cc4d98..c7c71a67a3 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/LoginDto.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/LoginDto.java @@ -1,5 +1,6 @@ package com.baeldung.defaultglobalsecurityscheme.dto; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; @@ -30,7 +31,7 @@ public class LoginDto { * @return user */ - @Schema(name = "user", required = true) + @Schema(name = "user", requiredMode = RequiredMode.REQUIRED) public String getUser() { return user; } diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/PingResponseDto.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/PingResponseDto.java index 0d367785d8..0944dce438 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/PingResponseDto.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/defaultglobalsecurityscheme/dto/PingResponseDto.java @@ -1,9 +1,10 @@ package com.baeldung.defaultglobalsecurityscheme.dto; +import io.swagger.v3.oas.annotations.media.Schema.RequiredMode; import java.time.OffsetDateTime; import java.util.Objects; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.format.annotation.DateTimeFormat; @@ -33,7 +34,7 @@ public class PingResponseDto { * @return pong */ @Valid - @Schema(name = "pong", required = false) + @Schema(name = "pong", requiredMode = RequiredMode.REQUIRED) public OffsetDateTime getPong() { return pong; } diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/jwt/SecurityConfiguration.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/jwt/SecurityConfiguration.java index 8cb1ca1f60..e6c849ac45 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/jwt/SecurityConfiguration.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/jwt/SecurityConfiguration.java @@ -9,6 +9,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; @@ -53,15 +54,15 @@ public class SecurityConfiguration { return http .authorizeHttpRequests(authorizeRequests -> authorizeRequests - .antMatchers("/api/auth/**", "/swagger-ui-custom.html" ,"/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**", + .requestMatchers("/api/auth/**", "/swagger-ui-custom.html" ,"/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**", "/swagger-ui/index.html","/api-docs/**") .permitAll() .anyRequest() .authenticated()) - .cors().disable() - .csrf().disable() - .formLogin().disable() - .httpBasic().disable() + .cors(AbstractHttpConfigurer::disable) + .csrf(AbstractHttpConfigurer::disable) + .formLogin(AbstractHttpConfigurer::disable) + .httpBasic(AbstractHttpConfigurer::disable) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt) diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java index 99d63581be..cd58c4644c 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/Foo.java @@ -1,10 +1,10 @@ package com.baeldung.restdocopenapi; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Foo { diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java index 892eb05f8d..c6bfd42b73 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooController.java @@ -5,7 +5,7 @@ import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import java.util.List; import java.util.Optional; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java index 105b57b2ef..d4691c1f51 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/FooRepository.java @@ -1,9 +1,10 @@ package com.baeldung.restdocopenapi; +import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.stereotype.Repository; @Repository -public interface FooRepository extends PagingAndSortingRepository{ +public interface FooRepository extends JpaRepository { } diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java index 8af414c8fd..8e8e9f4a9e 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/restdocopenapi/springdoc/FooBarController.java @@ -5,7 +5,7 @@ import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import java.util.List; import java.util.Optional; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java index f2355a2ec3..d9e4fb1c7d 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/controller/BookController.java @@ -2,8 +2,8 @@ package com.baeldung.springdoc.controller; import java.util.Collection; -import javax.validation.Valid; -import javax.validation.constraints.NotNull; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotNull; import com.baeldung.springdoc.exception.BookNotFoundException; import com.baeldung.springdoc.model.Book; diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/Foo.kt b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/Foo.kt index 3bc3c8fe61..e40bcfde97 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/Foo.kt +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/Foo.kt @@ -1,10 +1,9 @@ package com.baeldung.springdoc.kotlin -import javax.persistence.Entity -import javax.persistence.GeneratedValue -import javax.persistence.Id -import javax.validation.constraints.NotBlank -import javax.validation.constraints.Size +import jakarta.persistence.Entity +import jakarta.persistence.Id +import jakarta.validation.constraints.NotBlank +import jakarta.validation.constraints.Size @Entity data class Foo( diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/FooController.kt b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/FooController.kt index d3ecd6a6ba..e253e92a6d 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/FooController.kt +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/kotlin/FooController.kt @@ -6,6 +6,7 @@ import io.swagger.v3.oas.annotations.media.Content import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.responses.ApiResponses +import org.hibernate.internal.util.collections.CollectionHelper import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @@ -13,7 +14,7 @@ import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/") class FooController() { - val fooList: List = listOf(Foo(1, "one"), Foo(2, "two")) + val fooList: List = CollectionHelper.listOf(Foo(1, "one"), Foo(2, "two")) @Operation(summary = "Get all foos") @ApiResponses(value = [ diff --git a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java index 8f678a7ec2..e2c473058a 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java +++ b/spring-boot-modules/spring-boot-springdoc/src/main/java/com/baeldung/springdoc/model/Book.java @@ -1,7 +1,7 @@ package com.baeldung.springdoc.model; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.Size; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; public class Book { diff --git a/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/jwt/OpenApiJwtIntegrationTest.java b/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/jwt/OpenApiJwtIntegrationTest.java index a4920914fd..85ddefcc4c 100644 --- a/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/jwt/OpenApiJwtIntegrationTest.java +++ b/spring-boot-modules/spring-boot-springdoc/src/test/java/com/baeldung/jwt/OpenApiJwtIntegrationTest.java @@ -1,11 +1,13 @@ package com.baeldung.jwt; +import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -15,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @DisplayName("OpenAPI JWT Live Tests") +@Disabled class OpenApiJwtIntegrationTest { @LocalServerPort From 8a7e5a82e02b130d9b4d9cb2b78c22ac80db4748 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Sun, 17 Mar 2024 16:14:47 +0200 Subject: [PATCH 45/59] [JAVA-30987] Upgraded spring-annotations-2 to spring boot 3 (#16133) --- spring-boot-modules/pom.xml | 2 +- .../spring-boot-annotations-2/pom.xml | 10 ++++++++++ .../annotations/conditional/ConditionalUtils.java | 8 ++++---- .../{Java8Condition.java => Java17Condition.java} | 4 ++-- ...ndedService.java => Java17DependedService.java} | 4 ++-- .../{Java8OrJava9.java => Java17OrJava21.java} | 12 ++++++------ .../{Java9Condition.java => Java21Condition.java} | 4 ++-- .../annotations/conditional/LoggingService.java | 4 ++-- ...nUnitTest.java => Java17ConditionUnitTest.java} | 14 +++++++------- ...nUnitTest.java => Java21ConditionUnitTest.java} | 14 +++++++------- 10 files changed, 43 insertions(+), 33 deletions(-) rename spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/{Java8Condition.java => Java17Condition.java} (77%) rename spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/{Java8DependedService.java => Java17DependedService.java} (69%) rename spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/{Java8OrJava9.java => Java17OrJava21.java} (52%) rename spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/{Java9Condition.java => Java21Condition.java} (77%) rename spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/{Java9ConditionUnitTest.java => Java17ConditionUnitTest.java} (71%) rename spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/{Java8ConditionUnitTest.java => Java21ConditionUnitTest.java} (72%) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 529bf595bc..e09ba5d7d6 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -20,7 +20,7 @@ spring-boot-admin spring-boot-angular spring-boot-annotations - + spring-boot-annotations-2 spring-boot-artifacts spring-boot-artifacts-2 spring-boot-autoconfiguration diff --git a/spring-boot-modules/spring-boot-annotations-2/pom.xml b/spring-boot-modules/spring-boot-annotations-2/pom.xml index 71fc7ff388..b7522772aa 100644 --- a/spring-boot-modules/spring-boot-annotations-2/pom.xml +++ b/spring-boot-modules/spring-boot-annotations-2/pom.xml @@ -26,6 +26,7 @@ org.mockito mockito-inline + ${mockito-inline.version} test @@ -33,6 +34,15 @@ spring-boot-starter-test test + + org.apache.commons + commons-lang3 + + + 5.2.0 + com.baeldung.springbootconfiguration.Application + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/ConditionalUtils.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/ConditionalUtils.java index 7294d843d1..facafb13c2 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/ConditionalUtils.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/ConditionalUtils.java @@ -9,12 +9,12 @@ public class ConditionalUtils { return SystemUtils.IS_OS_WINDOWS; } - public static boolean isJava8() { - return JavaVersion.getJavaVersion().equals(JavaVersion.EIGHT); + public static boolean isJava17() { + return JavaVersion.getJavaVersion().equals(JavaVersion.SEVENTEEN); } - public static boolean isJava9() { - return JavaVersion.getJavaVersion().equals(JavaVersion.NINE); + public static boolean isJava21() { + return JavaVersion.getJavaVersion().equals(JavaVersion.TWENTY_ONE); } } diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8Condition.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17Condition.java similarity index 77% rename from spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8Condition.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17Condition.java index c5f5e16d52..cdf6cfde58 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8Condition.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17Condition.java @@ -4,10 +4,10 @@ import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class Java8Condition implements Condition { +public class Java17Condition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - return ConditionalUtils.isJava8(); + return ConditionalUtils.isJava17(); } } diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8DependedService.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17DependedService.java similarity index 69% rename from spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8DependedService.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17DependedService.java index ab76dcd930..2cf3dea8ec 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8DependedService.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17DependedService.java @@ -4,6 +4,6 @@ import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Service; @Service -@Conditional(Java8Condition.class) -public class Java8DependedService { +@Conditional(Java17Condition.class) +public class Java17DependedService { } diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8OrJava9.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17OrJava21.java similarity index 52% rename from spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8OrJava9.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17OrJava21.java index 77c501ed08..fdc5f866bc 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java8OrJava9.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java17OrJava21.java @@ -3,14 +3,14 @@ package com.baeldung.annotations.conditional; import org.springframework.boot.autoconfigure.condition.AnyNestedCondition; import org.springframework.context.annotation.Conditional; -public class Java8OrJava9 extends AnyNestedCondition { - Java8OrJava9() { +public class Java17OrJava21 extends AnyNestedCondition { + Java17OrJava21() { super(ConfigurationPhase.REGISTER_BEAN); } - @Conditional(Java8Condition.class) - static class Java8 { } + @Conditional(Java17Condition.class) + static class Java17 { } - @Conditional(Java9Condition.class) - static class Java9 { } + @Conditional(Java21Condition.class) + static class Java21 { } } diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java9Condition.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java21Condition.java similarity index 77% rename from spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java9Condition.java rename to spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java21Condition.java index 2afa8b25a7..ec0f3a499e 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java9Condition.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/Java21Condition.java @@ -4,10 +4,10 @@ import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class Java9Condition implements Condition { +public class Java21Condition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { - return ConditionalUtils.isJava9(); + return ConditionalUtils.isJava21(); } } diff --git a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/LoggingService.java b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/LoggingService.java index e104ec86e1..fa619acdb7 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/LoggingService.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/main/java/com/baeldung/annotations/conditional/LoggingService.java @@ -8,12 +8,12 @@ import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Service; @Service -@Conditional({IsDevEnvCondition.class, IsWindowsCondition.class, Java8Condition.class}) +@Conditional({IsDevEnvCondition.class, IsWindowsCondition.class, Java17Condition.class}) @ConditionalOnProperty( value = "logging.enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnExpression("${logging.enabled:true} and '${logging.level}'.equals('DEBUG')") -@ConditionalOnJava(JavaVersion.EIGHT) +@ConditionalOnJava(JavaVersion.SEVENTEEN) public class LoggingService { } diff --git a/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java9ConditionUnitTest.java b/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java17ConditionUnitTest.java similarity index 71% rename from spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java9ConditionUnitTest.java rename to spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java17ConditionUnitTest.java index ce277e81fe..560cd5537d 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java9ConditionUnitTest.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java17ConditionUnitTest.java @@ -7,15 +7,15 @@ import org.mockito.Mockito; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class Java9ConditionUnitTest { +public class Java17ConditionUnitTest { @Test - public void whenOnJava9_thenJava9ConditionShouldPass() { + public void whenOnJava17_thenJava7ConditionShouldPass() { try (MockedStatic theMock = Mockito.mockStatic(ConditionalUtils.class)) { - theMock.when(ConditionalUtils::isJava9) + theMock.when(ConditionalUtils::isJava17) .thenReturn(true); Assertions.assertTrue( - new Java9Condition().matches( + new Java17Condition().matches( Mockito.mock(ConditionContext.class), Mockito.mock(AnnotatedTypeMetadata.class) ) ); @@ -24,12 +24,12 @@ public class Java9ConditionUnitTest { } @Test - public void whenNotOnJava9_thenJava9ConditionShouldNotPass() { + public void whenNotOnJava17_thenJava17ConditionShouldNotPass() { try (MockedStatic theMock = Mockito.mockStatic(ConditionalUtils.class)) { - theMock.when(ConditionalUtils::isJava9) + theMock.when(ConditionalUtils::isJava17) .thenReturn(false); Assertions.assertFalse( - new Java9Condition().matches( + new Java17Condition().matches( Mockito.mock(ConditionContext.class), Mockito.mock(AnnotatedTypeMetadata.class) ) ); diff --git a/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java8ConditionUnitTest.java b/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java21ConditionUnitTest.java similarity index 72% rename from spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java8ConditionUnitTest.java rename to spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java21ConditionUnitTest.java index 0d1b1eded6..397f95c16c 100644 --- a/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java8ConditionUnitTest.java +++ b/spring-boot-modules/spring-boot-annotations-2/src/test/java/com/baeldung/annotations/conditional/Java21ConditionUnitTest.java @@ -7,15 +7,15 @@ import org.mockito.Mockito; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; -public class Java8ConditionUnitTest { +public class Java21ConditionUnitTest { @Test - public void whenOnJava8_thenJava8ConditionShouldPass() { + public void whenOnJava21_thenJava21ConditionShouldPass() { try (MockedStatic theMock = Mockito.mockStatic(ConditionalUtils.class)) { - theMock.when(ConditionalUtils::isJava8) + theMock.when(ConditionalUtils::isJava21) .thenReturn(true); Assertions.assertTrue( - new Java8Condition().matches( + new Java21Condition().matches( Mockito.mock(ConditionContext.class), Mockito.mock(AnnotatedTypeMetadata.class) ) ); @@ -24,12 +24,12 @@ public class Java8ConditionUnitTest { } @Test - public void whenNotOnJava8_thenJava8ConditionShouldNotPass() { + public void whenNotOnJava21_thenJava21ConditionShouldNotPass() { try (MockedStatic theMock = Mockito.mockStatic(ConditionalUtils.class)) { - theMock.when(ConditionalUtils::isJava8) + theMock.when(ConditionalUtils::isJava21) .thenReturn(false); Assertions.assertFalse( - new Java8Condition().matches( + new Java21Condition().matches( Mockito.mock(ConditionContext.class), Mockito.mock(AnnotatedTypeMetadata.class) ) ); From 35dcd94d8a68d98af8e770ca122c07047adbdc86 Mon Sep 17 00:00:00 2001 From: ACHRAF TAITAI <43656331+achraftt@users.noreply.github.com> Date: Sun, 17 Mar 2024 17:19:34 +0100 Subject: [PATCH 46/59] BAEL-7569: Disallow Mocking Using @DoNotMock with Mockito (#16155) --- .../annotations/MockitoAnnotationUnitTest.java | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java index 20c70ce27b..fe4b2ad227 100644 --- a/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java +++ b/testing-modules/mockito-simple/src/test/java/com/baeldung/mockito/annotations/MockitoAnnotationUnitTest.java @@ -13,11 +13,7 @@ import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; +import org.mockito.*; import org.mockito.junit.jupiter.MockitoExtension; import com.baeldung.mockito.MyDictionary; @@ -127,4 +123,14 @@ class MockitoAnnotationUnitTest { assertEquals("aMeaning", dic.getMeaning("aWord")); } + + @DoNotMock(reason = "Use a real instance instead") + public abstract class NotToMock { + // Class implementation + } + @Test + public void testOperation() { + // This will cause an error due to @DoNotMock annotation + //NotToMock noToMock = mock(NotToMock.class); + } } From 60d8998604f4949534564d8350eabf9c77177740 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Mon, 18 Mar 2024 04:07:40 +0530 Subject: [PATCH 47/59] JAVA-29299 Upgrade spring-security-pkce (#16144) * JAVA-29299 Upgrade spring-security-pkce module * Upgrade spring-security-pkce to boot-3 --- .../pkce-auth-server/pom.xml | 5 -- .../conf/AuthServerConfiguration.java | 58 ++++++++----------- .../authserver/conf/JwksConfiguration.java | 2 +- .../spring-security-pkce/pom.xml | 3 +- 4 files changed, 27 insertions(+), 41 deletions(-) diff --git a/spring-security-modules/spring-security-pkce/pkce-auth-server/pom.xml b/spring-security-modules/spring-security-pkce/pkce-auth-server/pom.xml index 1fba6501f0..f1a8c71077 100644 --- a/spring-security-modules/spring-security-pkce/pkce-auth-server/pom.xml +++ b/spring-security-modules/spring-security-pkce/pkce-auth-server/pom.xml @@ -18,12 +18,7 @@ org.springframework.security spring-security-oauth2-authorization-server - ${spring-authorization-server.version} - - 0.3.1 - - \ No newline at end of file diff --git a/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/AuthServerConfiguration.java b/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/AuthServerConfiguration.java index b599880f3c..326bfc5bda 100644 --- a/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/AuthServerConfiguration.java +++ b/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/AuthServerConfiguration.java @@ -5,24 +5,22 @@ import java.util.UUID; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; +import org.springframework.http.MediaType; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; -import org.springframework.security.config.annotation.web.configurers.oauth2.server.authorization.OAuth2AuthorizationServerConfigurer; -import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer; -import org.springframework.security.crypto.password.NoOpPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.core.oidc.OidcScopes; import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; -import org.springframework.security.oauth2.server.authorization.config.ClientSettings; -import org.springframework.security.oauth2.server.authorization.config.ProviderSettings; +import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; +import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer; +import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings; +import org.springframework.security.oauth2.server.authorization.settings.ClientSettings; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; -import org.springframework.security.web.util.matcher.RequestMatcher; +import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher; @Configuration public class AuthServerConfiguration { @@ -30,38 +28,30 @@ public class AuthServerConfiguration { @Bean @Order(1) public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { - - OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = new OAuth2AuthorizationServerConfigurer<>(); - // @formatter:off + OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); + http.getConfigurer(OAuth2AuthorizationServerConfigurer.class) + .oidc(Customizer.withDefaults()); http - .requestMatcher(authorizationServerConfigurer.getEndpointsMatcher()) - .authorizeRequests(authorize -> - authorize - .anyRequest() - .authenticated()); - http - .exceptionHandling(exceptions -> - exceptions.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))) - .csrf( csrf -> - csrf - .ignoringRequestMatchers(authorizationServerConfigurer.getEndpointsMatcher())) - .apply(authorizationServerConfigurer); - - // Required by /userinfo endpoint - http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt); + // Redirect to the login page when not authenticated from the + // authorization endpoint + .exceptionHandling((exceptions) -> exceptions.defaultAuthenticationEntryPointFor(new LoginUrlAuthenticationEntryPoint("/login"), + new MediaTypeRequestMatcher(MediaType.TEXT_HTML))) + // Accept access tokens for User Info and/or Client Registration + .oauth2ResourceServer((resourceServer) -> resourceServer.jwt(Customizer.withDefaults())); + return http.build(); - // @formatter:on } @Bean @Order(2) public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { - // @formatter:off - return http - .formLogin(Customizer.withDefaults()) - .build(); - // @formatter:on + http + .authorizeHttpRequests((authorize) -> authorize + .anyRequest().authenticated() + ) + .formLogin(Customizer.withDefaults()); + return http.build(); } @Bean @@ -89,8 +79,8 @@ public class AuthServerConfiguration { } @Bean - public ProviderSettings providerSettings() { - return ProviderSettings + public AuthorizationServerSettings authorizationServerSettings() { + return AuthorizationServerSettings .builder() .build(); } diff --git a/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/JwksConfiguration.java b/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/JwksConfiguration.java index a253141101..e3307a7a30 100644 --- a/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/JwksConfiguration.java +++ b/spring-security-modules/spring-security-pkce/pkce-auth-server/src/main/java/com/baeldung/security/pkce/authserver/conf/JwksConfiguration.java @@ -8,8 +8,8 @@ import java.util.UUID; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; import org.springframework.security.oauth2.jwt.JwtDecoder; +import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.RSAKey; diff --git a/spring-security-modules/spring-security-pkce/pom.xml b/spring-security-modules/spring-security-pkce/pom.xml index e0bd8eb90e..7c86e2852a 100644 --- a/spring-security-modules/spring-security-pkce/pom.xml +++ b/spring-security-modules/spring-security-pkce/pom.xml @@ -10,7 +10,8 @@ com.baeldung - spring-security-modules + parent-boot-3 + ../../parent-boot-3 0.0.1-SNAPSHOT From 693d3728a78173ee8078f316a9a4d4fdfb98ead0 Mon Sep 17 00:00:00 2001 From: Amit Pandey Date: Mon, 18 Mar 2024 23:35:59 +0530 Subject: [PATCH 48/59] JAVA-29012 :- Update Spring WebFlux AMQP to Spring Boot 3. (#16076) --- .../spring-webflux-amqp/pom.xml | 20 ++++--------------- .../spring/amqp/AmqpReactiveController.java | 12 +++++------ .../amqp/SpringWebfluxAmqpLiveTest.java | 2 +- 3 files changed, 11 insertions(+), 23 deletions(-) diff --git a/spring-reactive-modules/spring-webflux-amqp/pom.xml b/spring-reactive-modules/spring-webflux-amqp/pom.xml index 8ab8277d08..67faed216e 100755 --- a/spring-reactive-modules/spring-webflux-amqp/pom.xml +++ b/spring-reactive-modules/spring-webflux-amqp/pom.xml @@ -11,24 +11,12 @@ Spring WebFlux AMQP Sample - com.baeldung.spring.reactive - spring-reactive-modules - 1.0.0-SNAPSHOT + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 - - - - - org.springframework.boot - spring-boot-dependencies - - 2.1.3.RELEASE - pom - import - - - diff --git a/spring-reactive-modules/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/AmqpReactiveController.java b/spring-reactive-modules/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/AmqpReactiveController.java index b71c32bd05..009ec87ddd 100644 --- a/spring-reactive-modules/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/AmqpReactiveController.java +++ b/spring-reactive-modules/spring-webflux-amqp/src/main/java/com/baeldung/spring/amqp/AmqpReactiveController.java @@ -2,7 +2,7 @@ package com.baeldung.spring.amqp; import java.time.Duration; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,7 +31,7 @@ import reactor.core.publisher.Mono; @RestController public class AmqpReactiveController { - private static Logger log = LoggerFactory.getLogger(AmqpReactiveController.class); + private static final Logger log = LoggerFactory.getLogger(AmqpReactiveController.class); @Autowired private AmqpTemplate amqpTemplate; @@ -142,10 +142,10 @@ public class AmqpReactiveController { MessageListenerContainer mlc = messageListenerContainerFactory.createMessageListenerContainer(d.getRoutingKey()); - Flux f = Flux. create(emitter -> { + Flux f = Flux.create(emitter -> { log.info("[I168] Adding listener, queue={}", d.getRoutingKey()); - mlc.setupMessageListener((MessageListener) m -> { + mlc.setupMessageListener(m -> { String qname = m.getMessageProperties() .getConsumerQueue(); @@ -233,11 +233,11 @@ public class AmqpReactiveController { MessageListenerContainer mlc = messageListenerContainerFactory.createMessageListenerContainer(qname); - Flux f = Flux. create(emitter -> { + Flux f = Flux.create(emitter -> { log.info("[I168] Adding listener, queue={}", qname); - mlc.setupMessageListener((MessageListener) m -> { + mlc.setupMessageListener(m -> { log.info("[I137] Message received, queue={}", qname); diff --git a/spring-reactive-modules/spring-webflux-amqp/src/test/java/com/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java b/spring-reactive-modules/spring-webflux-amqp/src/test/java/com/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java index 81782ce575..7829a9db67 100644 --- a/spring-reactive-modules/spring-webflux-amqp/src/test/java/com/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java +++ b/spring-reactive-modules/spring-webflux-amqp/src/test/java/com/baeldung/spring/amqp/SpringWebfluxAmqpLiveTest.java @@ -15,7 +15,7 @@ public class SpringWebfluxAmqpLiveTest { client.post() .uri("/queue/NYSE") - .syncBody("Test Message") + .bodyValue("Test Message") .exchange() .expectStatus().isAccepted(); From faf223b47a7b24e75686c2b56e2eb66e5ee6efa6 Mon Sep 17 00:00:00 2001 From: sam-gardner <53271849+sam-gardner@users.noreply.github.com> Date: Mon, 18 Mar 2024 18:21:32 +0000 Subject: [PATCH 49/59] JAVA-28828 Rename RestClientIntegrationTest to RestClientLiveTest (#16159) --- .../{RestClientIntegrationTest.java => RestClientLiveTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/{RestClientIntegrationTest.java => RestClientLiveTest.java} (99%) diff --git a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientLiveTest.java similarity index 99% rename from spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java rename to spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientLiveTest.java index 5650d2dd22..0284d780a9 100644 --- a/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientIntegrationTest.java +++ b/spring-boot-modules/spring-boot-3-2/src/test/java/com/baeldung/restclient/RestClientLiveTest.java @@ -23,7 +23,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestPropertySource(locations="classpath:connectiondetails/application-r2dbc.properties") -public class RestClientIntegrationTest { +public class RestClientLiveTest { @LocalServerPort private int port; From bb3e43fdec1300c9a9b26c541f8abd657296ea7b Mon Sep 17 00:00:00 2001 From: DiegoMarti2 <150871541+DiegoMarti2@users.noreply.github.com> Date: Mon, 18 Mar 2024 20:40:01 +0200 Subject: [PATCH 50/59] baeldung-articles : BAEL-6596 (#16143) Check if a given time lies between two times regardless of date. --- .../CheckIfTimeBetweenTwoTimesUnitTest.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/checkiftimebetweentwotimes/CheckIfTimeBetweenTwoTimesUnitTest.java diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/checkiftimebetweentwotimes/CheckIfTimeBetweenTwoTimesUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/checkiftimebetweentwotimes/CheckIfTimeBetweenTwoTimesUnitTest.java new file mode 100644 index 0000000000..1ffddaa241 --- /dev/null +++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/checkiftimebetweentwotimes/CheckIfTimeBetweenTwoTimesUnitTest.java @@ -0,0 +1,45 @@ +package com.baeldung.checkiftimebetweentwotimes; + +import org.junit.Test; + +import java.time.LocalTime; +import java.util.Calendar; +import java.util.Date; + +import static org.junit.Assert.assertTrue; + +public class CheckIfTimeBetweenTwoTimesUnitTest { + private LocalTime startTime = LocalTime.parse("09:00:00"); + private LocalTime endTime = LocalTime.parse("17:00:00"); + private LocalTime targetTime = LocalTime.parse("12:30:00"); + + @Test + public void givenLocalTime_whenUsingIsAfterIsBefore_thenTimeIsBetween() { + assertTrue(!targetTime.isBefore(startTime) && !targetTime.isAfter(endTime)); + } + + @Test + public void givenLocalTime_whenUsingCompareTo_thenTimeIsBetween() { + assertTrue(targetTime.compareTo(startTime) >= 0 && targetTime.compareTo(endTime) <= 0); + } + + @Test + public void givenDate_whenUsingAfterBefore_thenTimeIsBetween() { + Calendar startCalendar = Calendar.getInstance(); + startCalendar.set(Calendar.HOUR_OF_DAY, 9); + startCalendar.set(Calendar.MINUTE, 0); + Date startTime = startCalendar.getTime(); + + Calendar endCalendar = Calendar.getInstance(); + endCalendar.set(Calendar.HOUR_OF_DAY, 17); + endCalendar.set(Calendar.MINUTE, 0); + Date endTime = endCalendar.getTime(); + + Calendar targetCalendar = Calendar.getInstance(); + targetCalendar.set(Calendar.HOUR_OF_DAY, 12); + targetCalendar.set(Calendar.MINUTE, 30); + Date targetTime = targetCalendar.getTime(); + + assertTrue(!targetTime.before(startTime) && !targetTime.after(endTime)); + } +} \ No newline at end of file From 68db1db5f06fec822161060d8a75dc50fd05f2ca Mon Sep 17 00:00:00 2001 From: Amit Pandey Date: Tue, 19 Mar 2024 00:13:24 +0530 Subject: [PATCH 51/59] JAVA-29185 :- Upgrade Spring 5 to boot 3. (#16141) --- spring-5/pom.xml | 21 ++++++++++++++----- .../java/com/baeldung/assertions/Car.java | 4 ++-- .../main/java/com/baeldung/jsonb/Person.java | 8 +++---- .../com/baeldung/jsonb/PersonController.java | 2 +- .../com/baeldung/restdocs/CRUDController.java | 4 ++-- .../java/com/baeldung/restdocs/CrudInput.java | 4 ++-- .../src/main/java/com/baeldung/web/Foo.java | 8 +++---- .../java/com/baeldung/web/FooController.java | 6 +++--- .../BeanRegistrationIntegrationTest.java | 6 +++--- .../baeldung/jsonb/JsonbIntegrationTest.java | 1 - .../BookControllerMvcIntegrationTest.java | 4 ++-- ...BookControllerReactiveIntegrationTest.java | 4 ++-- ...kControllerRestAssuredIntegrationTest.java | 9 ++++---- 13 files changed, 45 insertions(+), 36 deletions(-) diff --git a/spring-5/pom.xml b/spring-5/pom.xml index c41b8aa301..d66f0fa01f 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -11,9 +11,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-boot-2 + ../parent-boot-3 @@ -42,17 +42,25 @@ spring-boot-starter-webflux - javax.json.bind - javax.json.bind-api + jakarta.json.bind + jakarta.json.bind-api org.apache.geronimo.specs geronimo-json_1.1_spec ${geronimo-json_1.1_spec.version} + + + jakarta.json + jakarta.json-api + ${jakarta.json-api.version} + + org.apache.johnzon johnzon-jsonb + ${johnzon-jsonb.version} @@ -151,9 +159,12 @@ 1.0 - 1.5.6 + 2.2.6 ${project.build.directory}/generated-snippets 5.1.0 + true + 2.0.1 + 2.0.0 \ No newline at end of file diff --git a/spring-5/src/main/java/com/baeldung/assertions/Car.java b/spring-5/src/main/java/com/baeldung/assertions/Car.java index abff27f0b0..d0153ce528 100644 --- a/spring-5/src/main/java/com/baeldung/assertions/Car.java +++ b/spring-5/src/main/java/com/baeldung/assertions/Car.java @@ -109,11 +109,11 @@ public class Car { car.startWithHasText("t"); car.startWithNotContain("132"); - List repairPartsCollection = new ArrayList(); + List repairPartsCollection = new ArrayList<>(); repairPartsCollection.add("part"); car.repair(repairPartsCollection); - Map repairPartsMap = new HashMap(); + Map repairPartsMap = new HashMap<>(); repairPartsMap.put("1", "part"); car.repair(repairPartsMap); diff --git a/spring-5/src/main/java/com/baeldung/jsonb/Person.java b/spring-5/src/main/java/com/baeldung/jsonb/Person.java index 7a54b37574..1c495f05bd 100644 --- a/spring-5/src/main/java/com/baeldung/jsonb/Person.java +++ b/spring-5/src/main/java/com/baeldung/jsonb/Person.java @@ -3,10 +3,10 @@ package com.baeldung.jsonb; import java.math.BigDecimal; import java.time.LocalDate; -import javax.json.bind.annotation.JsonbDateFormat; -import javax.json.bind.annotation.JsonbNumberFormat; -import javax.json.bind.annotation.JsonbProperty; -import javax.json.bind.annotation.JsonbTransient; +import jakarta.json.bind.annotation.JsonbDateFormat; +import jakarta.json.bind.annotation.JsonbNumberFormat; +import jakarta.json.bind.annotation.JsonbProperty; +import jakarta.json.bind.annotation.JsonbTransient; public class Person { diff --git a/spring-5/src/main/java/com/baeldung/jsonb/PersonController.java b/spring-5/src/main/java/com/baeldung/jsonb/PersonController.java index e216a282eb..f69fcf4795 100644 --- a/spring-5/src/main/java/com/baeldung/jsonb/PersonController.java +++ b/spring-5/src/main/java/com/baeldung/jsonb/PersonController.java @@ -6,7 +6,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import javax.annotation.PostConstruct; +import jakarta.annotation.PostConstruct; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java b/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java index b10cfd5f55..b92e23f757 100644 --- a/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/CRUDController.java @@ -5,7 +5,7 @@ import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import java.util.ArrayList; import java.util.List; -import javax.validation.Valid; +import jakarta.validation.Valid; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -53,7 +53,7 @@ public class CRUDController { @PatchMapping("/{id}") public List patch(@PathVariable("id") long id, @RequestBody CrudInput crudInput) { - List returnList = new ArrayList(); + List returnList = new ArrayList<>(); crudInput.setId(id); returnList.add(crudInput); return returnList; diff --git a/spring-5/src/main/java/com/baeldung/restdocs/CrudInput.java b/spring-5/src/main/java/com/baeldung/restdocs/CrudInput.java index 29046d7725..4e783150d5 100644 --- a/spring-5/src/main/java/com/baeldung/restdocs/CrudInput.java +++ b/spring-5/src/main/java/com/baeldung/restdocs/CrudInput.java @@ -4,8 +4,8 @@ import java.net.URI; import java.util.Collections; import java.util.List; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/spring-5/src/main/java/com/baeldung/web/Foo.java b/spring-5/src/main/java/com/baeldung/web/Foo.java index c4868a9958..ca058652a5 100644 --- a/spring-5/src/main/java/com/baeldung/web/Foo.java +++ b/spring-5/src/main/java/com/baeldung/web/Foo.java @@ -1,9 +1,9 @@ package com.baeldung.web; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; @Entity public class Foo { diff --git a/spring-5/src/main/java/com/baeldung/web/FooController.java b/spring-5/src/main/java/com/baeldung/web/FooController.java index a09e628421..23c258c3c7 100644 --- a/spring-5/src/main/java/com/baeldung/web/FooController.java +++ b/spring-5/src/main/java/com/baeldung/web/FooController.java @@ -7,9 +7,9 @@ import org.springframework.http.HttpStatus; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; -import javax.annotation.PostConstruct; -import javax.validation.constraints.Max; -import javax.validation.constraints.Min; +import jakarta.annotation.PostConstruct; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; import java.util.List; @RestController("/foos") diff --git a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java index 9c462e0412..2e5a1d6d04 100644 --- a/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/functional/BeanRegistrationIntegrationTest.java @@ -20,21 +20,21 @@ public class BeanRegistrationIntegrationTest { @Test public void whenRegisterBean_thenOk() { - context.registerBean(MyService.class, () -> new MyService()); + context.registerBean(MyService.class, MyService::new); MyService myService = (MyService) context.getBean("com.baeldung.functional.MyService"); assertTrue(myService.getRandomNumber() < 10); } @Test public void whenRegisterBeanWithName_thenOk() { - context.registerBean("mySecondService", MyService.class, () -> new MyService()); + context.registerBean("mySecondService", MyService.class, MyService::new); MyService mySecondService = (MyService) context.getBean("mySecondService"); assertTrue(mySecondService.getRandomNumber() < 10); } @Test public void whenRegisterBeanWithCallback_thenOk() { - context.registerBean("myCallbackService", MyService.class, () -> new MyService(), bd -> bd.setAutowireCandidate(false)); + context.registerBean("myCallbackService", MyService.class, MyService::new, bd -> bd.setAutowireCandidate(false)); MyService myCallbackService = (MyService) context.getBean("myCallbackService"); assertTrue(myCallbackService.getRandomNumber() < 10); } diff --git a/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java b/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java index f4749c0d33..14870460e4 100644 --- a/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/jsonb/JsonbIntegrationTest.java @@ -9,7 +9,6 @@ import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.ResponseEntity; diff --git a/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerMvcIntegrationTest.java b/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerMvcIntegrationTest.java index ab96364e6a..3172a06ca1 100644 --- a/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerMvcIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerMvcIntegrationTest.java @@ -7,7 +7,7 @@ import static org.springframework.restdocs.operation.preprocess.Preprocessors.pr import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; +import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; @@ -50,6 +50,6 @@ class BookControllerMvcIntegrationTest { mockMvc.perform(get("/books?page=2")) .andExpect(status().isOk()) .andDo(document("books", - requestParameters(parameterWithName("page").description("The page to retrieve")))); + queryParameters(parameterWithName("page").description("The page to retrieve")))); } } \ No newline at end of file diff --git a/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerReactiveIntegrationTest.java b/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerReactiveIntegrationTest.java index b2a6991f27..fdbad44480 100644 --- a/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerReactiveIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerReactiveIntegrationTest.java @@ -2,7 +2,7 @@ package com.baeldung.queryparamdoc; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; +import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; @@ -46,7 +46,7 @@ class BookControllerReactiveIntegrationTest { webTestClient.get().uri("/books?page=2") .exchange().expectStatus().isOk().expectBody() .consumeWith(document("books", - requestParameters(parameterWithName("page").description("The page to retrieve")))); + queryParameters(parameterWithName("page").description("The page to retrieve")))); } @TestConfiguration diff --git a/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerRestAssuredIntegrationTest.java b/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerRestAssuredIntegrationTest.java index 44c6b27285..e24a626114 100644 --- a/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerRestAssuredIntegrationTest.java +++ b/spring-5/src/test/java/com/baeldung/queryparamdoc/BookControllerRestAssuredIntegrationTest.java @@ -3,9 +3,7 @@ package com.baeldung.queryparamdoc; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.core.Is.is; import static org.springframework.restdocs.request.RequestDocumentation.parameterWithName; -import static org.springframework.restdocs.request.RequestDocumentation.requestParameters; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.document; -import static org.springframework.restdocs.restassured3.RestAssuredRestDocumentation.documentationConfiguration; +import static org.springframework.restdocs.request.RequestDocumentation.queryParameters; import io.restassured.RestAssured; import io.restassured.builder.RequestSpecBuilder; @@ -19,6 +17,7 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.restdocs.RestDocumentationContextProvider; import org.springframework.restdocs.RestDocumentationExtension; +import org.springframework.restdocs.restassured.RestAssuredRestDocumentation; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -31,7 +30,7 @@ class BookControllerRestAssuredIntegrationTest { @BeforeEach void setUp(RestDocumentationContextProvider restDocumentation, @LocalServerPort int port) { - this.spec = new RequestSpecBuilder().addFilter(documentationConfiguration(restDocumentation)) + this.spec = new RequestSpecBuilder().addFilter(RestAssuredRestDocumentation.documentationConfiguration(restDocumentation)) .setPort(port) .build(); } @@ -44,7 +43,7 @@ class BookControllerRestAssuredIntegrationTest { @Test @WithMockUser void givenEndpoint_whenSendGetRequest_thenSuccessfulResponse() { - RestAssured.given(this.spec).filter(document("users", requestParameters( + RestAssured.given(this.spec).filter(RestAssuredRestDocumentation.document("users", queryParameters( parameterWithName("page").description("The page to retrieve")))) .when().get("/books?page=2") .then().assertThat().statusCode(is(200)); From be47444fcb2145b418283176094a25ea1eabfc97 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Mon, 18 Mar 2024 21:06:12 +0200 Subject: [PATCH 52/59] [JAVA-31067] Fix integration jdk17 jersey tests: Assign random/available port to jersey server (#16135) --- web-modules/jersey/pom.xml | 2 +- .../exceptionhandling/rest/StocksResourceIntegrationTest.java | 1 + .../jersey/server/GreetingsResourceIntegrationTest.java | 2 ++ 3 files changed, 4 insertions(+), 1 deletion(-) diff --git a/web-modules/jersey/pom.xml b/web-modules/jersey/pom.xml index 779403e8c1..cf7d4eadb5 100644 --- a/web-modules/jersey/pom.xml +++ b/web-modules/jersey/pom.xml @@ -104,7 +104,7 @@ - 3.1.1 + 3.1.5 diff --git a/web-modules/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java b/web-modules/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java index 92f2e77670..432a8f2eb6 100644 --- a/web-modules/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java +++ b/web-modules/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java @@ -41,6 +41,7 @@ public class StocksResourceIntegrationTest extends JerseyTest { resourceConfig.register(IllegalArgumentExceptionMapper.class); resourceConfig.register(ServerExceptionMapper.class); resourceConfig.packages("com.baeldung.jersey.exceptionhandling.rest"); + forceSet(TestProperties.CONTAINER_PORT, "0"); return resourceConfig; } diff --git a/web-modules/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java b/web-modules/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java index 5f23209c16..47736f90d7 100644 --- a/web-modules/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java +++ b/web-modules/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java @@ -4,6 +4,7 @@ import static org.junit.Assert.assertEquals; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; +import org.glassfish.jersey.test.TestProperties; import org.junit.Test; import jakarta.ws.rs.core.Application; @@ -15,6 +16,7 @@ public class GreetingsResourceIntegrationTest extends JerseyTest { @Override protected Application configure() { + forceSet(TestProperties.CONTAINER_PORT, "0"); return new ResourceConfig(Greetings.class); } From 35837b24237ca66a32ab2833d7e9ffdd85e76d73 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Tue, 19 Mar 2024 00:47:23 +0530 Subject: [PATCH 53/59] [JAVA-31569] Upgrade micrometer-registry-atlas to latest version (#16097) --- metrics/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/metrics/pom.xml b/metrics/pom.xml index a8f5e113e8..0e06a479c3 100644 --- a/metrics/pom.xml +++ b/metrics/pom.xml @@ -85,7 +85,7 @@ 4.2.17 0.13.2 - 1.11.0 + 1.12.3 3.1.0 1.2.0 1.7.7 From 75ed16ffb5cbe5716923dd158e2f7f97fe17ed51 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Tue, 19 Mar 2024 01:01:58 +0530 Subject: [PATCH 54/59] [JAVA-31565] Changes made for update commons-validator (#16131) --- core-java-modules/core-java-string-algorithms-3/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml index b79248841f..6e7264dcdd 100644 --- a/core-java-modules/core-java-string-algorithms-3/pom.xml +++ b/core-java-modules/core-java-string-algorithms-3/pom.xml @@ -55,7 +55,7 @@ - 1.7 + 1.8.0 5.1.1 1.10.0 From 51ec697ebc147721b240d0d6f426f2737c588d43 Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Mon, 18 Mar 2024 22:24:13 +0200 Subject: [PATCH 55/59] This commit is related to BAEL-6825 (#15981) * This commit is related to BAEL-6825 This commit aims to add a test class "IntegersBitLevelUnitTest.java". * Update IntegersBitLevelUnitTest.java * Update IntegersBitLevelUnitTest.java * Update IntegersBitLevelUnitTest.java * Update IntegersBitLevelUnitTest.java --- .../IntegersBitLevelUnitTest.java | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/integersatbitlevel/IntegersBitLevelUnitTest.java diff --git a/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/integersatbitlevel/IntegersBitLevelUnitTest.java b/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/integersatbitlevel/IntegersBitLevelUnitTest.java new file mode 100644 index 0000000000..54c0b89d03 --- /dev/null +++ b/core-java-modules/core-java-lang-operators-2/src/test/java/com/baeldung/integersatbitlevel/IntegersBitLevelUnitTest.java @@ -0,0 +1,66 @@ +package com.baeldung.integersatbitlevel; + +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.assertEquals; + +class IntegersBitLevelUnitTest { + + @Test + void givenNumbers_whenBitwiseAND_thenResultIsExpected() { + int result = 0b1100 & 0b0111; + assertEquals(0b0100, result); + } + + @Test + void givenNumbers_whenBitwiseOR_thenResultIsExpected() { + int result = 0b1100 | 0b0111; + assertEquals(0b1111, result); + } + + @Test + void givenNumbers_whenBitwiseXOR_thenResultIsExpected() { + int result = 0b1100 ^ 0b0111; + assertEquals(0b1011, result); + } + + @Test + void givenNumber_whenBitwiseNOT_thenResultIsExpected() { + int result = ~0b0101; + assertEquals(-0b0110, result); + } + + @Test + void givenNumber_whenBitwiseLeftShift_thenResultIsExpected() { + int result = 0b0101 << 2; + assertEquals(0b10100, result); + } + + @Test + void givenNumber_whenBitwiseRightShift_thenResultIsExpected() { + int result = 0b0101 >> 1; + assertEquals(0b10, result); + } + + @Test + void givenOriginalColor_whenApplyingMask_thenObtainModifiedColor() { + int originalColor = 0xFF336699; + + int alphaMask = 0xFF000000; + int redMask = 0x00FF0000; + int greenMask = 0x0000FF00; + int blueMask = 0x000000FF; + + int alpha = (originalColor & alphaMask) >>> 24; + int red = (originalColor & redMask) >>> 16; + int green = (originalColor & greenMask) >>> 8; + int blue = originalColor & blueMask; + + red = Math.min(255, red + 50); + green = Math.min(255, green + 30); + + int modifiedColor = (alpha << 24) | (red << 16) | (green << 8) | blue; + + assertEquals(-10124135, modifiedColor); + } +} From a8fe0867142e85c8cea2da9d2b1f811115b54103 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Tue, 19 Mar 2024 14:33:09 +0200 Subject: [PATCH 56/59] [JAVA-27519] Upgrade spring-rest-angular to spring boot 3 (#16118) --- spring-web-modules/spring-rest-angular/pom.xml | 5 ++--- .../src/main/java/com/baeldung/web/entity/Student.java | 6 +++--- .../src/main/java/com/baeldung/web/service/IOperations.java | 2 +- .../baeldung/web/service/StudentServiceIntegrationTest.java | 2 +- 4 files changed, 7 insertions(+), 8 deletions(-) diff --git a/spring-web-modules/spring-rest-angular/pom.xml b/spring-web-modules/spring-rest-angular/pom.xml index 36f9694fa1..c94ba1dfbe 100644 --- a/spring-web-modules/spring-rest-angular/pom.xml +++ b/spring-web-modules/spring-rest-angular/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-2 + parent-boot-3 0.0.1-SNAPSHOT - ../../parent-boot-2 + ../../parent-boot-3 @@ -55,7 +55,6 @@ io.rest-assured spring-mock-mvc - ${rest-assured.version} test diff --git a/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/entity/Student.java b/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/entity/Student.java index 849b35cf24..49e73a9223 100644 --- a/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/entity/Student.java +++ b/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/entity/Student.java @@ -2,9 +2,9 @@ package com.baeldung.web.entity; import java.io.Serializable; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; @Entity public class Student implements Serializable { diff --git a/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/service/IOperations.java b/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/service/IOperations.java index 60cb4382f4..3ec108d0fc 100644 --- a/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/service/IOperations.java +++ b/spring-web-modules/spring-rest-angular/src/main/java/com/baeldung/web/service/IOperations.java @@ -4,6 +4,6 @@ import org.springframework.data.domain.Page; public interface IOperations { - public Page findPaginated(final int page, final int size); + Page findPaginated(final int page, final int size); } diff --git a/spring-web-modules/spring-rest-angular/src/test/java/com/baeldung/web/service/StudentServiceIntegrationTest.java b/spring-web-modules/spring-rest-angular/src/test/java/com/baeldung/web/service/StudentServiceIntegrationTest.java index 654c4ef647..0702eae8e5 100644 --- a/spring-web-modules/spring-rest-angular/src/test/java/com/baeldung/web/service/StudentServiceIntegrationTest.java +++ b/spring-web-modules/spring-rest-angular/src/test/java/com/baeldung/web/service/StudentServiceIntegrationTest.java @@ -11,7 +11,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) From 0040f230920606a96b511f35033f6b0cce8be94f Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Tue, 19 Mar 2024 19:35:50 +0530 Subject: [PATCH 57/59] JAVA-32170: Changes made for Fix formatting of POMs (#16102) --- akka-modules/pom.xml | 2 +- apache-cxf-modules/cxf-spring/pom.xml | 2 +- apache-cxf-modules/pom.xml | 3 ++- apache-cxf-modules/sse-jaxrs/pom.xml | 2 +- .../sse-jaxrs/sse-jaxrs-server/pom.xml | 2 +- apache-httpclient4/pom.xml | 3 +-- apache-libraries-2/pom.xml | 2 -- apache-spark/pom.xml | 2 +- apache-thrift/pom.xml | 2 +- apache-velocity/pom.xml | 2 +- aws-modules/aws-dynamodb/pom.xml | 2 +- .../lambda-function/pom.xml | 2 +- aws-modules/aws-lambda-modules/pom.xml | 2 +- .../ShippingFunction/pom.xml | 2 +- .../todo-reminder-lambda/ToDoFunction/pom.xml | 2 +- aws-modules/aws-miscellaneous/pom.xml | 2 +- aws-modules/aws-s3/pom.xml | 4 +--- aws-modules/pom.xml | 20 +++++++++---------- azure/pom.xml | 2 +- 19 files changed, 28 insertions(+), 32 deletions(-) diff --git a/akka-modules/pom.xml b/akka-modules/pom.xml index 60432c4eea..be0b8aa891 100644 --- a/akka-modules/pom.xml +++ b/akka-modules/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 akka-modules - akka-modules pom + akka-modules parent-modules diff --git a/apache-cxf-modules/cxf-spring/pom.xml b/apache-cxf-modules/cxf-spring/pom.xml index 234a19eebc..e1e5033e2d 100644 --- a/apache-cxf-modules/cxf-spring/pom.xml +++ b/apache-cxf-modules/cxf-spring/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 cxf-spring - cxf-spring war + cxf-spring com.baeldung diff --git a/apache-cxf-modules/pom.xml b/apache-cxf-modules/pom.xml index 245a31614b..a571f5477c 100644 --- a/apache-cxf-modules/pom.xml +++ b/apache-cxf-modules/pom.xml @@ -5,8 +5,9 @@ 4.0.0 apache-cxf-modules 0.0.1-SNAPSHOT - apache-cxf-modules pom + apache-cxf-modules + com.baeldung diff --git a/apache-cxf-modules/sse-jaxrs/pom.xml b/apache-cxf-modules/sse-jaxrs/pom.xml index baa32a516a..2fade99152 100644 --- a/apache-cxf-modules/sse-jaxrs/pom.xml +++ b/apache-cxf-modules/sse-jaxrs/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 sse-jaxrs - sse-jaxrs pom + sse-jaxrs com.baeldung diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml index 3bd3e5cb27..13ec2a681f 100644 --- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml +++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 sse-jaxrs-server - sse-jaxrs-server war + sse-jaxrs-server com.baeldung diff --git a/apache-httpclient4/pom.xml b/apache-httpclient4/pom.xml index 48d39b0858..89e85fc1b4 100644 --- a/apache-httpclient4/pom.xml +++ b/apache-httpclient4/pom.xml @@ -5,8 +5,8 @@ 4.0.0 apache-httpclient4 0.1-SNAPSHOT - apache-httpclient4 war + apache-httpclient4 com.baeldung @@ -193,7 +193,6 @@ true - diff --git a/apache-libraries-2/pom.xml b/apache-libraries-2/pom.xml index 2e7ef0344c..9b8d5d9ad4 100644 --- a/apache-libraries-2/pom.xml +++ b/apache-libraries-2/pom.xml @@ -24,14 +24,12 @@ camel-core ${camel.version} - org.apache.camel camel-test-junit5 ${camel.version} test - org.apache.camel camel-main diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml index fbb6e9ba5e..210ea4f28b 100644 --- a/apache-spark/pom.xml +++ b/apache-spark/pom.xml @@ -5,8 +5,8 @@ 4.0.0 apache-spark 1.0-SNAPSHOT - apache-spark jar + apache-spark com.baeldung diff --git a/apache-thrift/pom.xml b/apache-thrift/pom.xml index d2623f92e7..f5c5dec928 100644 --- a/apache-thrift/pom.xml +++ b/apache-thrift/pom.xml @@ -5,8 +5,8 @@ 4.0.0 apache-thrift 0.0.1-SNAPSHOT - apache-thrift pom + apache-thrift com.baeldung diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml index 4718ad2f62..5dd56a1d68 100644 --- a/apache-velocity/pom.xml +++ b/apache-velocity/pom.xml @@ -5,8 +5,8 @@ 4.0.0 apache-velocity 0.1-SNAPSHOT - apache-velocity war + apache-velocity com.baeldung diff --git a/aws-modules/aws-dynamodb/pom.xml b/aws-modules/aws-dynamodb/pom.xml index 199b9a187e..6d1ad5ad34 100644 --- a/aws-modules/aws-dynamodb/pom.xml +++ b/aws-modules/aws-dynamodb/pom.xml @@ -5,8 +5,8 @@ 4.0.0 aws-dynamodb 0.1.0-SNAPSHOT - aws-dynamodb jar + aws-dynamodb com.baeldung diff --git a/aws-modules/aws-lambda-modules/lambda-function/pom.xml b/aws-modules/aws-lambda-modules/lambda-function/pom.xml index 8c56aaabed..9a24802e3f 100644 --- a/aws-modules/aws-lambda-modules/lambda-function/pom.xml +++ b/aws-modules/aws-lambda-modules/lambda-function/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 lambda-function - 0.1.0-SNAPSHOT lambda-function + 0.1.0-SNAPSHOT jar diff --git a/aws-modules/aws-lambda-modules/pom.xml b/aws-modules/aws-lambda-modules/pom.xml index 9886ff58d2..a4b7197fee 100644 --- a/aws-modules/aws-lambda-modules/pom.xml +++ b/aws-modules/aws-lambda-modules/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 aws-lambda-modules - aws-lambda-modules pom + aws-lambda-modules com.baeldung diff --git a/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml index 74a21068ee..0f294fabeb 100644 --- a/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml +++ b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml @@ -3,8 +3,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 ShippingFunction - 1.0 ShippingFunction + 1.0 jar diff --git a/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml index 8eb0879237..acc14b55ff 100644 --- a/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml +++ b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml @@ -4,8 +4,8 @@ 4.0.0 helloworld ToDoFunction - 1.0 ToDoFunction + 1.0 jar diff --git a/aws-modules/aws-miscellaneous/pom.xml b/aws-modules/aws-miscellaneous/pom.xml index 8a90ec8cc9..2e42cff0c3 100644 --- a/aws-modules/aws-miscellaneous/pom.xml +++ b/aws-modules/aws-miscellaneous/pom.xml @@ -5,8 +5,8 @@ 4.0.0 aws-miscellaneous 0.1.0-SNAPSHOT - aws-miscellaneous jar + aws-miscellaneous com.baeldung diff --git a/aws-modules/aws-s3/pom.xml b/aws-modules/aws-s3/pom.xml index f63158b889..09ab7649d6 100644 --- a/aws-modules/aws-s3/pom.xml +++ b/aws-modules/aws-s3/pom.xml @@ -5,8 +5,8 @@ 4.0.0 aws-s3 0.1.0-SNAPSHOT - aws-s3 jar + aws-s3 com.baeldung @@ -26,7 +26,6 @@ ${aws.java.sdk.version} test - commons-io commons-io @@ -56,7 +55,6 @@ ${com.adobe.testing.version} test - org.testcontainers junit-jupiter diff --git a/aws-modules/pom.xml b/aws-modules/pom.xml index 6d5f3fb168..c6bf59c1b2 100644 --- a/aws-modules/pom.xml +++ b/aws-modules/pom.xml @@ -4,6 +4,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 aws-modules + pom aws-modules @@ -12,16 +13,6 @@ 1.0.0-SNAPSHOT - - - com.amazonaws - aws-java-sdk-dynamodb - 1.12.523 - compile - - - pom - aws-app-sync aws-dynamodb @@ -31,6 +22,15 @@ aws-s3 + + + com.amazonaws + aws-java-sdk-dynamodb + 1.12.523 + compile + + + 1.12.331 2.24.9 diff --git a/azure/pom.xml b/azure/pom.xml index 6a06282a71..61ae0c7d68 100644 --- a/azure/pom.xml +++ b/azure/pom.xml @@ -5,8 +5,8 @@ 4.0.0 azure 0.1 - azure war + azure Demo project for Spring Boot on Azure From 8915b634d18309b1e246f212a9b26c5b3dd83348 Mon Sep 17 00:00:00 2001 From: Bipin kumar Date: Tue, 19 Mar 2024 19:37:45 +0530 Subject: [PATCH 58/59] JAVA-32170_M_01: Changes made for Fix formatting of POMs (#16116) --- mapstruct/pom.xml | 2 +- .../animal-sniffer-mvn-plugin/pom.xml | 2 +- .../core-java-exclusions/pom.xml | 3 +-- maven-modules/dependency-exclusion/pom.xml | 2 +- .../jacoco-coverage-aggregate-report/pom.xml | 2 +- .../pom.xml | 2 +- .../jacoco-coverage-services-example/pom.xml | 2 +- .../jacoco-coverage-aggregation/pom.xml | 2 +- maven-modules/maven-archetype/pom.xml | 2 +- maven-modules/maven-build-lifecycle/pom.xml | 19 ++++++++++--------- .../maven-build-optimization/pom.xml | 2 +- maven-modules/maven-copy-files/pom.xml | 2 +- .../counter-maven-plugin/pom.xml | 2 +- maven-modules/maven-custom-plugin/pom.xml | 2 +- maven-modules/maven-generate-war/pom.xml | 2 +- maven-modules/maven-integration-test/pom.xml | 2 +- maven-modules/maven-polyglot/pom.xml | 2 +- .../maven-reactor/patient-web/pom.xml | 2 ++ 18 files changed, 28 insertions(+), 26 deletions(-) diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml index 5332bcaeb3..277e4401d7 100644 --- a/mapstruct/pom.xml +++ b/mapstruct/pom.xml @@ -5,8 +5,8 @@ 4.0.0 mapstruct 1.0 - mapstruct jar + mapstruct com.baeldung diff --git a/maven-modules/animal-sniffer-mvn-plugin/pom.xml b/maven-modules/animal-sniffer-mvn-plugin/pom.xml index 0b508651af..04dbd722bb 100644 --- a/maven-modules/animal-sniffer-mvn-plugin/pom.xml +++ b/maven-modules/animal-sniffer-mvn-plugin/pom.xml @@ -5,8 +5,8 @@ 4.0.0 animal-sniffer-mvn-plugin 1.0-SNAPSHOT - animal-sniffer-mvn-plugin jar + animal-sniffer-mvn-plugin http://maven.apache.org diff --git a/maven-modules/dependency-exclusion/core-java-exclusions/pom.xml b/maven-modules/dependency-exclusion/core-java-exclusions/pom.xml index 9fd09f83e2..98fb78ddf3 100644 --- a/maven-modules/dependency-exclusion/core-java-exclusions/pom.xml +++ b/maven-modules/dependency-exclusion/core-java-exclusions/pom.xml @@ -4,8 +4,8 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 core-java-exclusions - core-java-exclusions jar + core-java-exclusions com.baeldung.dependency-exclusion @@ -19,7 +19,6 @@ junit test - diff --git a/maven-modules/dependency-exclusion/pom.xml b/maven-modules/dependency-exclusion/pom.xml index 649d7cdfb9..2564058482 100644 --- a/maven-modules/dependency-exclusion/pom.xml +++ b/maven-modules/dependency-exclusion/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.dependency-exclusion dependency-exclusion - dependency-exclusion pom + dependency-exclusion com.baeldung diff --git a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-aggregate-report/pom.xml b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-aggregate-report/pom.xml index c9aea0fac3..052b07e8ea 100644 --- a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-aggregate-report/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-aggregate-report/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.jacoco-coverage-aggregation jacoco-coverage-aggregate-report - jacoco-coverage-aggregate-report pom + jacoco-coverage-aggregate-report com.baeldung diff --git a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/pom.xml b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/pom.xml index 0b4491a7b3..90c3980e63 100644 --- a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-controllers-example/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.jacoco-coverage-aggregation jacoco-coverage-controllers-example - jacoco-coverage-controllers-example jar + jacoco-coverage-controllers-example com.baeldung diff --git a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml index 89dbc15d33..048511c1ad 100644 --- a/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/jacoco-coverage-services-example/pom.xml @@ -5,8 +5,8 @@ 4.0.0 com.baeldung.jacoco-coverage-aggregation jacoco-coverage-services-example - jacoco-coverage-services-example jar + jacoco-coverage-services-example com.baeldung diff --git a/maven-modules/jacoco-coverage-aggregation/pom.xml b/maven-modules/jacoco-coverage-aggregation/pom.xml index 1f6992f95a..bc70c60b50 100644 --- a/maven-modules/jacoco-coverage-aggregation/pom.xml +++ b/maven-modules/jacoco-coverage-aggregation/pom.xml @@ -5,8 +5,8 @@ 4.0.0 jacoco-coverage-aggregation 1.0 - jacoco-coverage-aggregation pom + jacoco-coverage-aggregation com.baeldung diff --git a/maven-modules/maven-archetype/pom.xml b/maven-modules/maven-archetype/pom.xml index 5e5323cbdf..5fd0b0cbb9 100644 --- a/maven-modules/maven-archetype/pom.xml +++ b/maven-modules/maven-archetype/pom.xml @@ -6,8 +6,8 @@ com.baeldung.archetypes maven-archetype 1.0-SNAPSHOT - maven-archetype maven-archetype + maven-archetype Archetype used to generate rest application based on jaxrs 2.1 diff --git a/maven-modules/maven-build-lifecycle/pom.xml b/maven-modules/maven-build-lifecycle/pom.xml index aafa256002..f9025a9c46 100644 --- a/maven-modules/maven-build-lifecycle/pom.xml +++ b/maven-modules/maven-build-lifecycle/pom.xml @@ -1,21 +1,16 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 + maven-build-lifecycle + com.baeldung maven-modules 0.0.1-SNAPSHOT - maven-build-lifecycle - - - 3.1.2 - 3.1.2 - 5.3.1 - @@ -49,4 +44,10 @@ + + 3.1.2 + 3.1.2 + 5.3.1 + + \ No newline at end of file diff --git a/maven-modules/maven-build-optimization/pom.xml b/maven-modules/maven-build-optimization/pom.xml index 86d3b2d34f..30e96fb2be 100644 --- a/maven-modules/maven-build-optimization/pom.xml +++ b/maven-modules/maven-build-optimization/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-build-optimization 0.0.1-SNAPSHOT - maven-build-optimization pom + maven-build-optimization com.baeldung diff --git a/maven-modules/maven-copy-files/pom.xml b/maven-modules/maven-copy-files/pom.xml index e6ad639b21..90b40171a7 100644 --- a/maven-modules/maven-copy-files/pom.xml +++ b/maven-modules/maven-copy-files/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-copy-files 1.0-SNAPSHOT - maven-copy-files pom + maven-copy-files http://www.example.com diff --git a/maven-modules/maven-custom-plugin/counter-maven-plugin/pom.xml b/maven-modules/maven-custom-plugin/counter-maven-plugin/pom.xml index f2e4992d20..38e5119dd4 100644 --- a/maven-modules/maven-custom-plugin/counter-maven-plugin/pom.xml +++ b/maven-modules/maven-custom-plugin/counter-maven-plugin/pom.xml @@ -6,8 +6,8 @@ com.baeldung counter-maven-plugin 0.0.1-SNAPSHOT - counter-maven-plugin maven-plugin + counter-maven-plugin http://maven.apache.org diff --git a/maven-modules/maven-custom-plugin/pom.xml b/maven-modules/maven-custom-plugin/pom.xml index 731abe472d..2931789830 100644 --- a/maven-modules/maven-custom-plugin/pom.xml +++ b/maven-modules/maven-custom-plugin/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-custom-plugin 0.0.1-SNAPSHOT - maven-custom-plugin pom + maven-custom-plugin com.baeldung diff --git a/maven-modules/maven-generate-war/pom.xml b/maven-modules/maven-generate-war/pom.xml index 211a9ad6cb..ab2413385b 100644 --- a/maven-modules/maven-generate-war/pom.xml +++ b/maven-modules/maven-generate-war/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-generate-war 0.0.1-SNAPSHOT - maven-generate-war war + maven-generate-war Spring boot project to demonstrate war file generation diff --git a/maven-modules/maven-integration-test/pom.xml b/maven-modules/maven-integration-test/pom.xml index 9befb9f6b9..261a885ce3 100644 --- a/maven-modules/maven-integration-test/pom.xml +++ b/maven-modules/maven-integration-test/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-integration-test 0.0.1-SNAPSHOT - maven-integration-test war + maven-integration-test com.baeldung diff --git a/maven-modules/maven-polyglot/pom.xml b/maven-modules/maven-polyglot/pom.xml index 7ff375b9ba..3583563aba 100644 --- a/maven-modules/maven-polyglot/pom.xml +++ b/maven-modules/maven-polyglot/pom.xml @@ -5,8 +5,8 @@ 4.0.0 maven-polyglot 0.0.1-SNAPSHOT - maven-polyglot pom + maven-polyglot com.baeldung diff --git a/maven-modules/maven-reactor/patient-web/pom.xml b/maven-modules/maven-reactor/patient-web/pom.xml index 9d2ddd819d..eb1ec57382 100644 --- a/maven-modules/maven-reactor/patient-web/pom.xml +++ b/maven-modules/maven-reactor/patient-web/pom.xml @@ -6,11 +6,13 @@ patient-web 1.0-SNAPSHOT patient-web + com.baeldung maven-reactor 1.0-SNAPSHOT + com.baeldung From b47fb18816bbc7c9723290930ad3098fb60eeb4c Mon Sep 17 00:00:00 2001 From: MohamedHelmyKassab <137485958+MohamedHelmyKassab@users.noreply.github.com> Date: Tue, 19 Mar 2024 19:06:41 +0200 Subject: [PATCH 59/59] This PR is related to BAEL-6922 (#16171) * Update pom.xml * Add files via upload * This commit is related to BAEL-6922 This commit aims to add a test class named ExcelToJsonUnitTest that provides ways to convert Excel to JSON in Java. * Update ExcelToJsonUnitTest.java * Update ExcelToJsonUnitTest.java --- json-modules/json-conversion/pom.xml | 5 ++ .../exceltojson/ExcelToJsonUnitTest.java | 84 ++++++++++++++++++ .../src/test/resources/Book1.xlsx | Bin 0 -> 8878 bytes 3 files changed, 89 insertions(+) create mode 100644 json-modules/json-conversion/src/test/java/com/baeldung/exceltojson/ExcelToJsonUnitTest.java create mode 100644 json-modules/json-conversion/src/test/resources/Book1.xlsx diff --git a/json-modules/json-conversion/pom.xml b/json-modules/json-conversion/pom.xml index 9eebac16b4..624af3181a 100644 --- a/json-modules/json-conversion/pom.xml +++ b/json-modules/json-conversion/pom.xml @@ -29,6 +29,11 @@ jackson-databind ${jackson.version} + + org.apache.poi + poi-ooxml + 5.2.3 + com.google.guava guava diff --git a/json-modules/json-conversion/src/test/java/com/baeldung/exceltojson/ExcelToJsonUnitTest.java b/json-modules/json-conversion/src/test/java/com/baeldung/exceltojson/ExcelToJsonUnitTest.java new file mode 100644 index 0000000000..ec7e5ff841 --- /dev/null +++ b/json-modules/json-conversion/src/test/java/com/baeldung/exceltojson/ExcelToJsonUnitTest.java @@ -0,0 +1,84 @@ +package com.baeldung.exceltojson; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.json.JSONArray; +import org.junit.Test; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; + +public class ExcelToJsonUnitTest { + public static String filePath = Objects.requireNonNull(ExcelToJsonUnitTest.class.getClassLoader().getResource("Book1.xlsx")).getFile(); + public String expectedJson = "[[\"C1\",\"C2\",\"C3\",\"C4\",\"C5\"]," + + "[\"1.0\",\"2.0\",\"3.0\",\"4.0\",\"5.0\"]," + + "[\"1.0\",\"2.0\",\"3.0\",\"4.0\",\"5.0\"]," + + "[\"1.0\",\"2.0\",\"3.0\",\"4.0\",\"5.0\"]," + + "[\"1.0\",\"2.0\",\"3.0\",\"4.0\",\"5.0\"]]"; + private Workbook workbook; + private Sheet sheet; + private InputStream inputStream; + + public ExcelToJsonUnitTest() throws IOException { + inputStream = new FileInputStream(filePath); + workbook = new XSSFWorkbook(inputStream); + sheet = workbook.getSheetAt(0); + } + + @Test + public void givenExcelFile_whenUsingApachePOIConversion_thenConvertToJson() { + JSONArray jsonArray = new JSONArray(); + + Row headerRow = sheet.getRow(0); + List headers = new ArrayList<>(); + for (Cell cell : headerRow) { + headers.add(cell.toString()); + } + jsonArray.put(headers); + + for (int i = 1; i <= sheet.getLastRowNum(); i++) { + Row row = sheet.getRow(i); + List rowData = new ArrayList<>(); + for (Cell cell : row) { + rowData.add(cell.toString()); + } + jsonArray.put(rowData); + } + + assertEquals(expectedJson, jsonArray.toString()); + } + + @Test + public void givenExcelFile_whenUsingJacksonConversion_thenConvertToJson() throws JsonProcessingException { + List> data = new ArrayList<>(); + + Row headerRow = sheet.getRow(0); + List headers = new ArrayList<>(); + for (Cell cell : headerRow) { + headers.add(cell.toString()); + } + data.add(headers); + + for (int i = 1; i <= sheet.getLastRowNum(); i++) { + Row row = sheet.getRow(i); + List rowData = new ArrayList<>(); + for (Cell cell : row) { + rowData.add(cell.toString()); + } + data.add(rowData); + } + + ObjectMapper objectMapper = new ObjectMapper(); + String json = objectMapper.writeValueAsString(data); + + assertEquals(expectedJson, json); + } +} diff --git a/json-modules/json-conversion/src/test/resources/Book1.xlsx b/json-modules/json-conversion/src/test/resources/Book1.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..592c78c8286ad0a41599375bd80720ef46672907 GIT binary patch literal 8878 zcmeHNg5`IWh@pFgL0U>AMN+!Eh6X7~=@1ZU5TxTbdhWfR z!#Tgd;NCsY?0M#UzO|m&d#`uBYu@##D?x2>NI*<%;uVn zu9wM5ZEj2rJX6mt;FmZduUoMeN0uKnw+T?G@RC&(Mw}EG^uD%dZTB9DG^Kq9-jfI+eg+Am2x|c`ge;H<|q#yc2X~1F|6WKbT5-zHf6@Xwp1md zb!1z~>&ui@6B1wn2Nd)VGzdb~_ADs;obtzz*AZpT?+8wDx0;TjQaA%p8hZb*y_Nng zVc*?P8-_3UkKSwra^F4x0PgM(0P25%Wvw*BzSz!4f%A;)C4yXF zYryr#`9+cF?S7imFT5p@cm%?9b)Kb=il0XTAregqHt1E+Uot;0gPW4l+AD=r)C**7Cyb^A zetwg`g(?0@NO^ZWg|Oev+btRH~}HM~cI8Q$Fjs9nYVhXdfqhaZ+;4E1-AfT`<=%n<+peHfKt z!*<5Yfx{E%YHtn%+W+LO5^YCd+7pr+v8`L=ZcpO0dYnlR8pjw*t=80wy=27%^n5+I zA-;SC?Y;H`E_&N$BV((@?C#zGs+iFux83xBrOBkDZp%Iy9-aYIe#~i0+Rfp$q3b%M zEGX|2nY47BY%`wY6!)*2)q!FeWuZo*D3#oRtgRO>3ZIc1=p-kV_ zs4BWi<@{LF1IPLDn(3q><(%vcMYl3NF&;)v0{c@ZsZ+fB*%(ev+6zOV@!vuI-lS9I6-5S;IIVBX4^%RF|dfv(QBlX zs$YwNbe|>3aulbKhMg@xc^&x9WKydCD#V?YVeU$xH#e+cMW951r}Q&?2VLROh3*kl z1tNT9%xnui_I8D1Xn3!tj>F{JCR)B(vDR@$Ea2ksjvmXEvo20JL)K=W!;fI4FoFJd zp@aSwjwScu3-D>t0+GJOh%zyY4^C5VnsLZV#pcD%C5P9QWYb;VY)^nq-sO|#4Tr_n zIZ5p3VM?HDWoF8&nXIoDH_oDn2VP~0hxnO-uenG3&8{mEdqZ$c(@f`5XNUYy7XSqV z=~?~JbnB{*P$R(fvN7bN88dXYis`{|KOp1IF7UPQ1yVb91unT6oS*KP9I%TFs+ZG@ zx^X`Po*Bp%V+@rx)3_*Bh)$6@CJ6U1HI(Zeji7(=gt4fL8*fA*^yfee(fiL{y zk!`$eW?5|8c~`s34dyA9=N(h3l|r6@VruD1;I~vl+&!p54)w~_8;5lyT#umaW@_~H zcxG9R_2zyhq8I@hg>;`t-715CqmDtw3P?SvwkU16++4RljV&VFXSBuv?S>e#muj`s>X?gIR8<~)B3G#Y1jk^p z#N=Zb44Yt_MFv2DgTe6++WIpn|4m_Vu!<4}>i_OhqN$?P&56^BejCQ=ndU)=I}75V z-PPW~Mj5DKo_|Ec6L7Lj&eCM8H?72h0EBoS4EK4Q@nL;I!2i*~`XK@j(Ffn*Ko|)) zd_0VRV!l^O1(rj?$J^cBDc(cJN_E3;6pQa?%Onu|dd|c^8kUn!D}B;94&k*M;dJM= zbNfX35thOSYu1A? z$-#^Dfxf9_*h&9AgR=rz{f}VbqK6CskihQvR|a>pv9bcWas2w=`kBhp;|+m1oH(J& zx^s8WFEU8_tx(Yln?mibboTNNVo1S+rh4;@h1-D#5{WgMCfSPA(a2ZAZio5{lr^-% z&L#$0pDYQq;ALkFQr#u*Zv3OT75!H7zkVcR`i3jgY8Y@=H)B|T^jLygp0h2>5yg1q zE%9TUeYrY>m!@Ppyx0vO`>(>tEmT;xJ>!CzT*G! zz-=+bmT!6|c#Go0*itQz*e+AFkD1CI*^*k%3bH2%G#O3e0UJDJD0q=t)xO&)&bo4~ zZ_0Eo1r{l+6pLp`AWB4s#EWIJ+6&zDGCK6gpL9Vo`(<7Wdjay$3~r$zcMo|hq~Sa? z&W+wpQH4o}3u`{@s%N>byE3Kz>?kqIJh$r>|G5vZ1sarn$h6lN06V(7yI-f9I5CFx zl#>LqY8Yn%Rdk`9vYZT+|7u8 zN~bLk`_9LP{QFyxrs+qK`l=v87MH0H(zzPCgV!cxlYXXeGja2qrJk`!=lz^Sab8%5 z%$DIKp=lKUoUlV~EpG!A3yz<#TqgZ->F4!}OEv#r#m27{@eX&Ob#me$elkV9g44m> z%G>HmKz`qjGw+BunNgunaJR&=&JV=md8&X@C!)5k^U9b=4cYaSc~`+1(xPV%Q5V2s zkZyYrtzYDOXqS1~oSFXhtpR^xpf9cGOVUi0@UG6wiMTpOy{@|X*7s+rZym2;VE8*s zDrGQtjbQr>PxJFn`Y)J(Y^)ruIDXB)5VEVU6iY6E*M{65NPWq^GgaCLt$JU;cpByC zWy#^XE}xi6<)KAgNQxdD3>DhIqn7ZfOh!7b3!|0~Le!&6z9vE7ubO>WDdVA}67#{! zA(mK`lLs1=dRe4b!V*xzZqj~1Z}u$_MZtRxwdgYo9PL(!n(dPVMC`sCO;!obRZs+} zngXL9F6lzc(UIKeqs#~eDV+WSS8PwPUSW?(BO4=U)CON0HM5_<8f^y}RZoiu;W@_1 zqY|UyXJi|Q6TA}4suFvxvr(!jMcPH~&%lATWMuX~I--9_KYb8e81M7EvpX&mvYW{7 zI+0K$JD9Y~6RgU$gUET8_%3jD!LH>Eri-XwQF06z>fLpxLh@Dfk zFh!{6+Kb1QMAj^)c?<|pc3guDn_0}veB%L#q(F;!42?2|4aA2kiI}dwjfvV|ZEGU~ zx5|OD3(+U#F9ouc0~1BQA~pa!qZWVCX1(7C(t z`%lDPoam{8BsRI|SK$kcI-T=$NVT^Qb?+cw6T;b-=w{-l`N7(*_VV+Pb?Hx`+lcj& z_Rl3v!~$=>%&Ku@-dyz%o3?nJ`is?TZ1nG~ft&_!PRq;hu3|^W0t2o$fy>u?X_q1< zbLYCt{ukSurU7cAB@NC!gY7qm+XW9zZf}ZB+i!YvT3HV(F&|EZ$b*v8-y@3zBl+wy z_I(+q@8!ymL5z{Cm;0gKgLSx%#`CaD&WKnH4=O0OQo3Q$H=U!$M)+gMk5QFkg=Vv) zFZ45<=ZVpqu)aai{yQT!#|4BaHGj7=mu*C^1|z_p=DUvp$`m{YJn1YVjLaJHfqiNy zMFZY*!2m7#j3~hEEgfKPs()G zL5D1^-*Wav*B@%Gb{Dut;lB{R1{BX&ua7AzJ1nTPygEtejDcv;=Ba(n4EkXp*^Yp* zhJ8h2$iS}2GzmMPe~~i#9SxS?BI&+d zqTp(PD6R;iYpn_ko^)U}L8jgk?ZRR#D}PsaAGdLw;O-pZWEy4b#)85gf)t5ZmzLD0 zE;SLNlk?6aZ?ls<5!n;C78FZP1s`zXk zwr%Jdo|?p}LL5m;776&|UddA7C>LMcKZ>G0DOso5ANLXO9huF0mnUwj+Znzrb4s#1 z*avLlkc6~UV&Ghb`t$S-rDVy!<$}O>$<%YAmt?i~DO= z+jE#saqHF&X+K``z4GCxRn};eu+jqgDc>OSNGiU>6{LS-MImfcEe`w^@m)r1%2R|+LJZZ}G!v%mMXgsAK!rB68es1L5c zR;$LcsV!>GND*ex>G5Kii+b9pX!T9D`rEeSWSZF40?7RH1Dja^uFljUzU+Oj>_)1P zSJ#=iFRYTyW#%npl!{Hm>?nJpS)ny5&sKhrcPRNXzUnNg#)uYTnksmrs-NIZX-t`} z6n(;O%`J?OwP0c`fxA^#=f3&T?xo7x?-FYlKe$Pcu(irs<+8FWRgp* z*}Rn;jVHDA4A)+TX|o|Xk6){TAj2IjD+)Gzi)sP_lY(MbEvkYR;w~{Us)dXuloR{; zuje@jrR4db+#?iD@{ATQLs)2WaugUp4K7g2+_uJt%XMbGZ6&i%_2P z(>j_e+Pe`-Wud(}-Di)&s$7PMxJJ|n(uQ~%XvU(2zS^!K>@b`12!iHA``rAYZO4UI zmpKN$BecU`hCq5U?@|M}{R6{Vth8NTJ<+k6bX+R8>TuuV`z)F5qZa--y@^;5hixKa zfMTMiXP&o2Ncf?_D`d!*0Y?yOOrij3N{wiA`OpLaqtdC-A9g#;qz&kz^b;&M*dZWl(fj}Dy{{i6J2}a z=5KNYDBr4O9Vg4`eWNv-mnf4uCCjz#&d6KGv&Mi}vM&QB?P4<@e47mFa%z3Z4=L5m znL9}Cl$GJgn_}ndGAJeIZ!R^P@lQ?WT?vg+bZrkRj*b?%{Z-oBm*%8%*NrP+G+h7_ z?lAu#V>ghugO%IQLN!-g1vt-%(TY72hy(JpYIb>pSQnXB7!1G2NljT%Y(5yS?oSdQ zFGPO2EH|sVmes{yll+#puuo3Yay(534fMR%wUnE}IFy7-dpn}o5z;P3)PX^_^P%X& zrwFU_ezvxO<#we~VYIp>uCF)}OlhkbZo^<4!~M6pr-}l~!FkiNn#gk140T*lI@6}{ z;BGTPhIrRd-;hwYJ7j6i;~F4Xa}e^RZ57;X5f&Q9Mto+Nhq;K7H7AR2kjclk zAa|ne6`i+j%~WkOyixW}YVt0_qEHIHL1rA_!d+fNs`H%oY`O){RtiJdd08yIpjKxj zTk{}k&>2J8AC*W=F;F*DKr#%uT%=a~Q!v^m>9^~)g`xcYk~>+h8L}D!KCy-@=e^Dc zI$8rgmAZW}%*}IvhOyUX-A5riW0a(e_`z#QI zn7!IW1vqaeeC@w+MI?+NjUx?BMDr6y4HovdWwx@YAr(`u+njrBwyO#pHjj;TBz&BR zm?+hGc7B=egaMzc#Z5CEklQvzJmVNWX+kuUGnx7CYv%E6|l) z*Vc{Pjk||FKDrur;0Y1GqNH9C!osns-t2Vwf!rCSU%QDH(uOcH>ZY5%$)p}0F$LmS zSgYphvcAACJ~!z^#4s^Emu$wOg9nyKpZ3ASlmI*f7?lr`sQ3^;DD3{;+JG=~v}!#N9Df zs9S&)UHge%@RkA9bsJIWu4}#h9|g4z_3WEMSV&*O-UR;&Z5uOJD@!eqtF4puuL!ps zQTbUCLsnZ?C_8ugN&{cfZ%G{@`UHK7;s2y;XU*c{OUK0C$96D6m^9Hx zD>$@5Rh6u?(7}tEnV05AljrQX23|BzH@@<8v9SQdAJ@>{NZOYfMr9@!%6&|>C(BMw z?^1CS&jL2cB+hJUYwUtff+ePG=_@Oc_%s`0y{>C{DAI8~*`kT8PYT+qQu}>q)50C@ zvX2k;VW9kb2~8;_M?wo*G%gIexBzN6OQ40iE6~}E!vg4P^+%VB;(wY1?9Bhakr*cm zlbdlMp7gg**F{~#&YXPaXJ z3x0&NhFVf6GJ&Z>cRD!kbQDaZ|5~#l;Z!(!jeRlQxHCn}fa|6IvYbDE)as_%;r_*z zyB;6G_O&jCy0$Za4c!pH9g4s~o$R6YJyTR<+VEMPiw|+H{@apmdPZ;A@#`EYKHs!y z==eixj#~?(1cz2mRd5lsJx1>awq<`0I5P!QobaCk2NS4qU~1TZ0?y3Y`Hy%*{9nAm zb}l_$@+V`49w1yk#8@O3T2#jfE-{zaJ*hB*i?6d*$+vi4MgOWKZufI+-Pq);&vx{> zuh*rt!Xm{J)05X@J?h~b*#t<4ES1$y9w}OEu*D&1FHgkh#N$^MHz#r1Z#$t-9x?RXI8AN$K@=_R(Q{ z$UD7Whz!dQwyB0HYNB08YqxEuUgo_;2L*aL>Smui;yg%KJb5IH|EluA{A5(En!LVv z&vn#e!25WIw-5`Vvl06<84fuF;>})~=kR8$6fT?n2)B0pk0yk>2ZfIMIgeBY=YxSy z+(raUQq(RPeJPtQJL5vNesqOe`^h(Z*`t_z_7;0KKW+Kp0!ej840BQx$bCg)xtLlJ zb~$z2&M9)ccGC6ZyN^Zy`-QPJ55w|p)h+tJ!xs+zF)Z!>^OFJh)51SIC!ntMR|kLX zVgA`cG7J-c>S*3Kyx-UPZQ25>x$bp&?i>GAh5l^{04SmTGX8%w>HB`}OOwAn1z`N= zNBm8wyzk|{a`W3u9;{;pTgrVM=e~pc)#h&p+{C{e{H{Iko8D*h-=>&kf0*9q_WK_G zN}9jz0f28X5C6$%|EAFU=6_9re>T^r{FC{=5~8{i66|yV05sSu2*%PR)IY!dA3n5N A761SM literal 0 HcmV?d00001