From 95b1df4addf7d2492d7630064c1398fe1e4184a7 Mon Sep 17 00:00:00 2001 From: gantoin Date: Wed, 18 Jan 2023 11:09:58 +0100 Subject: [PATCH 001/113] fix: Typos in Avro module --- .../AvroDeSerializer.java} | 10 +++---- .../AvroSerializer.java} | 10 +++---- ...erializerDeSerializerIntegrationTest.java} | 26 +++++++++---------- 3 files changed, 23 insertions(+), 23 deletions(-) rename apache-libraries/src/main/java/com/baeldung/avro/util/{serealization/AvroDeSerealizer.java => serialization/AvroDeSerializer.java} (84%) rename apache-libraries/src/main/java/com/baeldung/avro/util/{serealization/AvroSerealizer.java => serialization/AvroSerializer.java} (87%) rename apache-libraries/src/test/java/com/baeldung/avro/util/{serealization/AvroSerealizerDeSerealizerIntegrationTest.java => serialization/AvroSerializerDeSerializerIntegrationTest.java} (75%) diff --git a/apache-libraries/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java b/apache-libraries/src/main/java/com/baeldung/avro/util/serialization/AvroDeSerializer.java similarity index 84% rename from apache-libraries/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java rename to apache-libraries/src/main/java/com/baeldung/avro/util/serialization/AvroDeSerializer.java index 7d30c3d1ee..cf4c360ba4 100644 --- a/apache-libraries/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java +++ b/apache-libraries/src/main/java/com/baeldung/avro/util/serialization/AvroDeSerializer.java @@ -1,4 +1,4 @@ -package com.baeldung.avro.util.serealization; +package com.baeldung.avro.util.serialization; import com.baeldung.avro.util.model.AvroHttpRequest; import org.apache.avro.io.DatumReader; @@ -10,11 +10,11 @@ import org.slf4j.LoggerFactory; import java.io.IOException; -public class AvroDeSerealizer { +public class AvroDeSerializer { - private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class); + private static Logger logger = LoggerFactory.getLogger(AvroDeSerializer.class); - public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) { + public AvroHttpRequest deSerializeAvroHttpRequestJSON(byte[] data) { DatumReader reader = new SpecificDatumReader<>(AvroHttpRequest.class); Decoder decoder = null; try { @@ -27,7 +27,7 @@ public class AvroDeSerealizer { return null; } - public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data) { + public AvroHttpRequest deSerializeAvroHttpRequestBinary(byte[] data) { DatumReader employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class); Decoder decoder = DecoderFactory.get() .binaryDecoder(data, null); diff --git a/apache-libraries/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java b/apache-libraries/src/main/java/com/baeldung/avro/util/serialization/AvroSerializer.java similarity index 87% rename from apache-libraries/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java rename to apache-libraries/src/main/java/com/baeldung/avro/util/serialization/AvroSerializer.java index 767b688dea..6d39060ec8 100644 --- a/apache-libraries/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java +++ b/apache-libraries/src/main/java/com/baeldung/avro/util/serialization/AvroSerializer.java @@ -1,4 +1,4 @@ -package com.baeldung.avro.util.serealization; +package com.baeldung.avro.util.serialization; import com.baeldung.avro.util.model.AvroHttpRequest; import org.apache.avro.io.*; @@ -9,11 +9,11 @@ import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; -public class AvroSerealizer { +public class AvroSerializer { - private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class); + private static final Logger logger = LoggerFactory.getLogger(AvroSerializer.class); - public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request) { + public byte[] serializeAvroHttpRequestJSON(AvroHttpRequest request) { DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class); byte[] data = new byte[0]; ByteArrayOutputStream stream = new ByteArrayOutputStream(); @@ -30,7 +30,7 @@ public class AvroSerealizer { return data; } - public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request) { + public byte[] serializeAvroHttpRequestBinary(AvroHttpRequest request) { DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class); byte[] data = new byte[0]; ByteArrayOutputStream stream = new ByteArrayOutputStream(); diff --git a/apache-libraries/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerIntegrationTest.java b/apache-libraries/src/test/java/com/baeldung/avro/util/serialization/AvroSerializerDeSerializerIntegrationTest.java similarity index 75% rename from apache-libraries/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerIntegrationTest.java rename to apache-libraries/src/test/java/com/baeldung/avro/util/serialization/AvroSerializerDeSerializerIntegrationTest.java index 3d413e1939..964eeb6d87 100644 --- a/apache-libraries/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerIntegrationTest.java +++ b/apache-libraries/src/test/java/com/baeldung/avro/util/serialization/AvroSerializerDeSerializerIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.avro.util.serealization; +package com.baeldung.avro.util.serialization; import com.baeldung.avro.util.model.Active; import com.baeldung.avro.util.model.AvroHttpRequest; @@ -13,16 +13,16 @@ import java.util.Objects; import static org.junit.Assert.*; -public class AvroSerealizerDeSerealizerIntegrationTest { +public class AvroSerializerDeSerializerIntegrationTest { - AvroSerealizer serealizer; - AvroDeSerealizer deSerealizer; + AvroSerializer serializer; + AvroDeSerializer deserializer; AvroHttpRequest request; @Before public void setUp() throws Exception { - serealizer = new AvroSerealizer(); - deSerealizer = new AvroDeSerealizer(); + serializer = new AvroSerializer(); + deserializer = new AvroDeSerializer(); ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder() .setHostName("localhost") @@ -49,22 +49,22 @@ public class AvroSerealizerDeSerealizerIntegrationTest { @Test public void WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() { - byte[] data = serealizer.serealizeAvroHttpRequestJSON(request); + byte[] data = serializer.serializeAvroHttpRequestJSON(request); assertTrue(Objects.nonNull(data)); assertTrue(data.length > 0); } @Test public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() { - byte[] data = serealizer.serealizeAvroHttpRequestBinary(request); + byte[] data = serializer.serializeAvroHttpRequestBinary(request); assertTrue(Objects.nonNull(data)); assertTrue(data.length > 0); } @Test public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() { - byte[] data = serealizer.serealizeAvroHttpRequestJSON(request); - AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data); + byte[] data = serializer.serializeAvroHttpRequestJSON(request); + AvroHttpRequest actualRequest = deserializer.deSerializeAvroHttpRequestJSON(data); assertEquals(actualRequest, request); assertTrue(actualRequest.getRequestTime() .equals(request.getRequestTime())); @@ -72,12 +72,12 @@ public class AvroSerealizerDeSerealizerIntegrationTest { @Test public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() { - byte[] data = serealizer.serealizeAvroHttpRequestBinary(request); - AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data); + byte[] data = serializer.serializeAvroHttpRequestBinary(request); + AvroHttpRequest actualRequest = deserializer.deSerializeAvroHttpRequestBinary(data); assertEquals(actualRequest, request); assertTrue(actualRequest.getRequestTime() .equals(request.getRequestTime())); } - + } From 2526646b62c78fbb35d1b6cd23dddced004581bf Mon Sep 17 00:00:00 2001 From: Amit Kumatr Date: Fri, 27 Jan 2023 00:32:13 +0530 Subject: [PATCH 002/113] added code of collections-vs-stream --- .../spring-data-jpa-query-3/pom.xml | 5 ++ .../data/jpa/collections/vsstream/User.java | 61 +++++++++++++++++++ .../collections/vsstream/UserRepository.java | 14 +++++ .../UserRepositoryIntegrationTest.java | 41 +++++++++++++ 4 files changed, 121 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/User.java create mode 100644 persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/UserRepository.java create mode 100644 persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/collections/vsstream/UserRepositoryIntegrationTest.java diff --git a/persistence-modules/spring-data-jpa-query-3/pom.xml b/persistence-modules/spring-data-jpa-query-3/pom.xml index 135d31aaba..a80b6349c9 100644 --- a/persistence-modules/spring-data-jpa-query-3/pom.xml +++ b/persistence-modules/spring-data-jpa-query-3/pom.xml @@ -22,6 +22,11 @@ com.h2database h2 + + com.github.javafaker + javafaker + 0.15 + org.springframework.boot spring-boot-starter-test diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/User.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/User.java new file mode 100644 index 0000000000..85843bd92b --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/User.java @@ -0,0 +1,61 @@ +package com.baeldung.spring.data.jpa.collections.vsstream; + +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "_user") +public class User { + private String firstName; + private String lastName; + private int age; + @Id + private int id; + + public User() { + } + + public User(String firstName, String lastName, int age) { + this.firstName = firstName; + this.lastName = lastName; + this.age = age; + } + + public User(String firstName, String lastName, int age, int id) { + this(firstName, lastName, age); + this.id = id; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/UserRepository.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/UserRepository.java new file mode 100644 index 0000000000..05acb84691 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/UserRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.spring.data.jpa.collections.vsstream; + +import java.util.List; +import java.util.stream.Stream; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends JpaRepository { + Stream findAllByAgeGreaterThan(int age); + + List findByAgeGreaterThan(int age); +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/collections/vsstream/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/collections/vsstream/UserRepositoryIntegrationTest.java new file mode 100644 index 0000000000..9bf3774999 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/collections/vsstream/UserRepositoryIntegrationTest.java @@ -0,0 +1,41 @@ +package com.baeldung.spring.data.jpa.query.collections.vsstream; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.transaction.annotation.Transactional; + +import com.baeldung.spring.data.jpa.collections.vsstream.User; +import com.baeldung.spring.data.jpa.collections.vsstream.UserRepository; + +@DataJpaTest +class UserRepositoryIntegrationTest { + + @Autowired + private UserRepository userRepository; + + @Test + public void whenAgeIs20_thenItShouldReturnAllUsersWhoseAgeIsGreaterThan20InAList() { + List users = userRepository.findByAgeGreaterThan(20); + assertThat(users).isNotEmpty(); + assertThat(users.stream() + .map(User::getAge) + .allMatch(age -> age > 20)).isTrue(); + } + + @Test + @Transactional + public void whenAgeIs20_thenItShouldReturnAllUsersWhoseAgeIsGreaterThan20InAStream() { + Stream users = userRepository.findAllByAgeGreaterThan(20); + assertThat(users).isNotNull(); + assertThat(users.map(User::getAge) + .allMatch(age -> age > 20)).isTrue(); + } +} From c4faa5dd177558488971820be8476f33f3ac6fe1 Mon Sep 17 00:00:00 2001 From: Amit Kumatr Date: Fri, 27 Jan 2023 00:54:56 +0530 Subject: [PATCH 003/113] added setup and teardown method --- .../UserRepositoryIntegrationTest.java | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/collections/vsstream/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/collections/vsstream/UserRepositoryIntegrationTest.java index 9bf3774999..be25a82126 100644 --- a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/collections/vsstream/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/collections/vsstream/UserRepositoryIntegrationTest.java @@ -3,17 +3,20 @@ package com.baeldung.spring.data.jpa.query.collections.vsstream; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import java.util.stream.Stream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.data.jdbc.DataJdbcTest; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; import com.baeldung.spring.data.jpa.collections.vsstream.User; import com.baeldung.spring.data.jpa.collections.vsstream.UserRepository; +import com.github.javafaker.Faker; @DataJpaTest class UserRepositoryIntegrationTest { @@ -21,6 +24,24 @@ class UserRepositoryIntegrationTest { @Autowired private UserRepository userRepository; + @BeforeEach + public void setup() { + Faker faker = new Faker(); + List people = IntStream.range(1, 100) + .parallel() + .mapToObj(i -> new User(faker.name() + .firstName(), faker.name() + .lastName(), faker.number() + .numberBetween(1, 100), i)) + .collect(Collectors.toList()); + userRepository.saveAll(people); + } + + @AfterEach + public void tearDown() { + userRepository.deleteAll(); + } + @Test public void whenAgeIs20_thenItShouldReturnAllUsersWhoseAgeIsGreaterThan20InAList() { List users = userRepository.findByAgeGreaterThan(20); From 5baf3bfa14d35378ea116fb3cff76d965415783e Mon Sep 17 00:00:00 2001 From: Amit Kumatr Date: Tue, 31 Jan 2023 18:30:43 +0530 Subject: [PATCH 004/113] rename the package --- .../spring-data-jpa-query-3/pom.xml | 5 ++++- .../ListVsStreamQueryApplication.java | 15 +++++++++++++++ .../vsstream => collectionsvsstream}/User.java | 2 +- .../UserRepository.java | 2 +- .../UserRepositoryIntegrationTest.java | 6 +++--- 5 files changed, 24 insertions(+), 6 deletions(-) create mode 100644 persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/ListVsStreamQueryApplication.java rename persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/{collections/vsstream => collectionsvsstream}/User.java (95%) rename persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/{collections/vsstream => collectionsvsstream}/UserRepository.java (85%) rename persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/{query/collections/vsstream => collectionsvsstream}/UserRepositoryIntegrationTest.java (89%) diff --git a/persistence-modules/spring-data-jpa-query-3/pom.xml b/persistence-modules/spring-data-jpa-query-3/pom.xml index a80b6349c9..18df57fe14 100644 --- a/persistence-modules/spring-data-jpa-query-3/pom.xml +++ b/persistence-modules/spring-data-jpa-query-3/pom.xml @@ -5,6 +5,9 @@ 4.0.0 spring-data-jpa-query-3 spring-data-jpa-query-3 + + 0.15 + com.baeldung @@ -25,7 +28,7 @@ com.github.javafaker javafaker - 0.15 + ${javafaker.version} org.springframework.boot diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/ListVsStreamQueryApplication.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/ListVsStreamQueryApplication.java new file mode 100644 index 0000000000..2585aa0497 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/ListVsStreamQueryApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.spring.data.jpa.collectionsvsstream; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ListVsStreamQueryApplication { + + @Autowired private UserRepository userRepository; + + public static void main(String[] args) { + SpringApplication.run(ListVsStreamQueryApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/User.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/User.java similarity index 95% rename from persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/User.java rename to persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/User.java index 85843bd92b..d2174c343f 100644 --- a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/User.java +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/User.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.jpa.collections.vsstream; +package com.baeldung.spring.data.jpa.collectionsvsstream; import javax.persistence.Entity; import javax.persistence.Id; diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/UserRepository.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepository.java similarity index 85% rename from persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/UserRepository.java rename to persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepository.java index 05acb84691..ed37cb7036 100644 --- a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collections/vsstream/UserRepository.java +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepository.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.jpa.collections.vsstream; +package com.baeldung.spring.data.jpa.collectionsvsstream; import java.util.List; import java.util.stream.Stream; diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/collections/vsstream/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryIntegrationTest.java similarity index 89% rename from persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/collections/vsstream/UserRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryIntegrationTest.java index be25a82126..415bfcfc41 100644 --- a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/query/collections/vsstream/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryIntegrationTest.java @@ -1,4 +1,4 @@ -package com.baeldung.spring.data.jpa.query.collections.vsstream; +package com.baeldung.spring.data.jpa.collectionsvsstream; import static org.assertj.core.api.Assertions.assertThat; @@ -14,8 +14,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.transaction.annotation.Transactional; -import com.baeldung.spring.data.jpa.collections.vsstream.User; -import com.baeldung.spring.data.jpa.collections.vsstream.UserRepository; +import com.baeldung.spring.data.jpa.collectionsvsstream.User; +import com.baeldung.spring.data.jpa.collectionsvsstream.UserRepository; import com.github.javafaker.Faker; @DataJpaTest From e4a50c278ef33ca6baab2cf0cb24e9998a5d2233 Mon Sep 17 00:00:00 2001 From: Amit Kumatr Date: Tue, 31 Jan 2023 18:31:35 +0530 Subject: [PATCH 005/113] removed unwanted code --- .../ListVsStreamQueryApplication.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/ListVsStreamQueryApplication.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/ListVsStreamQueryApplication.java index 2585aa0497..58123afa6c 100644 --- a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/ListVsStreamQueryApplication.java +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/collectionsvsstream/ListVsStreamQueryApplication.java @@ -1,15 +1,12 @@ package com.baeldung.spring.data.jpa.collectionsvsstream; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ListVsStreamQueryApplication { - @Autowired private UserRepository userRepository; - - public static void main(String[] args) { - SpringApplication.run(ListVsStreamQueryApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(ListVsStreamQueryApplication.class, args); + } } From c09a9ff8293d66467c3b329fa506f6392160b1a4 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Tue, 31 Jan 2023 19:10:03 +0200 Subject: [PATCH 006/113] BAEL-5856 mark manual test --- ...ntIntegrationTest.java => OrderRestEndpointManualTest.java} | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) rename axon/src/test/java/com/baeldung/axon/gui/{OrderRestEndpointIntegrationTest.java => OrderRestEndpointManualTest.java} (98%) diff --git a/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointIntegrationTest.java b/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java similarity index 98% rename from axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointIntegrationTest.java rename to axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java index a30e42766b..3b5c130c89 100644 --- a/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointIntegrationTest.java +++ b/axon/src/test/java/com/baeldung/axon/gui/OrderRestEndpointManualTest.java @@ -27,7 +27,8 @@ import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest(classes = OrderApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -class OrderRestEndpointIntegrationTest { +//marked as manual as the test is unstable on Jenkins due to low resources +class OrderRestEndpointManualTest { @LocalServerPort private int port; From acd2e6c9783995afcf271e05470f814c7d68ed88 Mon Sep 17 00:00:00 2001 From: Amit Kumatr Date: Wed, 1 Feb 2023 02:06:26 +0530 Subject: [PATCH 007/113] removed transactional annotation --- .../collectionsvsstream/UserRepositoryIntegrationTest.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryIntegrationTest.java index 415bfcfc41..009ace0f9c 100644 --- a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryIntegrationTest.java @@ -12,10 +12,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; -import org.springframework.transaction.annotation.Transactional; -import com.baeldung.spring.data.jpa.collectionsvsstream.User; -import com.baeldung.spring.data.jpa.collectionsvsstream.UserRepository; import com.github.javafaker.Faker; @DataJpaTest @@ -52,7 +49,6 @@ class UserRepositoryIntegrationTest { } @Test - @Transactional public void whenAgeIs20_thenItShouldReturnAllUsersWhoseAgeIsGreaterThan20InAStream() { Stream users = userRepository.findAllByAgeGreaterThan(20); assertThat(users).isNotNull(); From 3d2661d407271cb5760d333718c98bb1f64c75c6 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Wed, 1 Feb 2023 03:11:14 +0100 Subject: [PATCH 008/113] [strArrayToIntArray] convert str array to int array (#13217) --- .../StringArrayToIntArrayUnitTest.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/StringArrayToIntArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/StringArrayToIntArrayUnitTest.java b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/StringArrayToIntArrayUnitTest.java new file mode 100644 index 0000000000..3675778f90 --- /dev/null +++ b/core-java-modules/core-java-arrays-convert/src/test/java/com/baeldung/array/conversions/StringArrayToIntArrayUnitTest.java @@ -0,0 +1,63 @@ +package com.baeldung.array.conversions; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + + +public class StringArrayToIntArrayUnitTest { + private final String[] stringArray = new String[] { "1", "2", "3", "4", "5", "6", "42" }; + private final int[] expected = new int[] { 1, 2, 3, 4, 5, 6, 42 }; + + private final String[] stringArrayWithInvalidNum = new String[] { "1", "2", "hello", "4", "world", "6", "42" }; + private final int[] expectedWithInvalidInput = new int[] { 1, 2, Integer.MIN_VALUE, 4, Integer.MIN_VALUE, 6, 42 }; + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Test + void givenStringArray_whenUseStreamApi_shouldGetExpectedIntArray() { + int[] result = Arrays.stream(stringArray).mapToInt(Integer::parseInt).toArray(); + assertArrayEquals(expected, result); + } + + @Test + void givenStringArrayWithInvalidNum_whenUseStreamApi_shouldGetExpectedIntArray() { + int[] result = Arrays.stream(stringArrayWithInvalidNum).mapToInt(s -> { + try { + return Integer.parseInt(s); + } catch (NumberFormatException ex) { + logger.warn("Invalid number format detected: {}, use Int.MinValue as the fallback", s); + return Integer.MIN_VALUE; + } + }).toArray(); + assertArrayEquals(expectedWithInvalidInput, result); + } + + @Test + void givenStringArray_whenConvertInLoop_shouldGetExpectedIntArray() { + int[] result = new int[stringArray.length]; + for (int i = 0; i < stringArray.length; i++) { + result[i] = Integer.parseInt(stringArray[i]); + } + assertArrayEquals(expected, result); + } + + @Test + void givenStringArrayWithInvalidNum_whenConvertInLoop_shouldGetExpectedIntArray() { + int[] result = new int[stringArrayWithInvalidNum.length]; + for (int i = 0; i < stringArrayWithInvalidNum.length; i++) { + try { + result[i] = Integer.parseInt(stringArrayWithInvalidNum[i]); + } catch (NumberFormatException exception) { + logger.warn("Invalid number format detected: [{}], use Int.MinValue as the fallback", stringArrayWithInvalidNum[i]); + result[i] = Integer.MIN_VALUE; + } + } + + assertArrayEquals(expectedWithInvalidInput, result); + } +} From ac6a85ac227abaaa54ff18b47734a770ade9a630 Mon Sep 17 00:00:00 2001 From: Olu <56642018+olu-damilare@users.noreply.github.com> Date: Wed, 1 Feb 2023 08:04:40 +0100 Subject: [PATCH 009/113] BAEL 5932 - Callback Functions in Java (#13364) --- .../AsynchronousCallbackUnitTest.java | 5 ++--- .../ConsumerCallbackUnitTest.java | 15 +++++++++++---- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/AsynchronousCallbackUnitTest.java b/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/AsynchronousCallbackUnitTest.java index 494d7365d3..de9e386395 100644 --- a/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/AsynchronousCallbackUnitTest.java +++ b/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/AsynchronousCallbackUnitTest.java @@ -6,8 +6,7 @@ import com.baeldung.callbackfunctions.EventListener; import com.baeldung.callbackfunctions.asynchronous.AsynchronousEventConsumer; import com.baeldung.callbackfunctions.asynchronous.AsynchronousEventListenerImpl; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.*; public class AsynchronousCallbackUnitTest { @@ -17,6 +16,6 @@ public class AsynchronousCallbackUnitTest { AsynchronousEventConsumer asynchronousEventListenerConsumer = new AsynchronousEventConsumer(listener); asynchronousEventListenerConsumer.doAsynchronousOperation(); - verify(listener, times(1)).onTrigger(); + verify(listener, timeout(1000).times(1)).onTrigger(); } } diff --git a/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/ConsumerCallbackUnitTest.java b/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/ConsumerCallbackUnitTest.java index ba09a7e50c..9ba5cdb6ef 100644 --- a/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/ConsumerCallbackUnitTest.java +++ b/core-java-modules/core-java-functional/src/test/java/com/baeldung/callbackfunctions/ConsumerCallbackUnitTest.java @@ -3,18 +3,25 @@ package com.baeldung.callbackfunctions; import org.junit.jupiter.api.Test; import com.baeldung.callbackfunctions.ConsumerCallback; +import java.util.concurrent.atomic.AtomicInteger; + import static org.junit.jupiter.api.Assertions.assertEquals; public class ConsumerCallbackUnitTest { @Test - public void whenIncreasingInitialAgeByGivenValueThroughCallback_shouldIncreaseAge(){ + void whenIncreasingInitialAgeByGivenValueThroughCallback_shouldIncreaseAge(){ ConsumerCallback consumerCallback = new ConsumerCallback(); - consumerCallback.getAge(20, (initialAge) -> { - int ageDifference = 10; + int ageDifference = 10; + AtomicInteger newAge1 = new AtomicInteger(); + int initialAge = 20; + consumerCallback.getAge(initialAge, (initialAge1) -> { consumerCallback.increaseAge(initialAge, ageDifference, (newAge) -> { - assertEquals(initialAge + ageDifference, newAge); + System.out.printf("New age ==> %s", newAge); + newAge1.set(newAge); + }); }); + assertEquals(initialAge + ageDifference, newAge1.get()); } } From c57a192c13b98e182a350952a536f4df566a9304 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Thu, 2 Feb 2023 04:01:09 +0100 Subject: [PATCH 010/113] [abs-int-diff] Return Absolute Difference Between Two Integers in Java (#13379) --- .../AbsoluteDifferenceOfTwoIntUnitTest.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 core-java-modules/core-java-numbers-5/src/test/java/com/baeldung/absintdiff/AbsoluteDifferenceOfTwoIntUnitTest.java diff --git a/core-java-modules/core-java-numbers-5/src/test/java/com/baeldung/absintdiff/AbsoluteDifferenceOfTwoIntUnitTest.java b/core-java-modules/core-java-numbers-5/src/test/java/com/baeldung/absintdiff/AbsoluteDifferenceOfTwoIntUnitTest.java new file mode 100644 index 0000000000..eec3924202 --- /dev/null +++ b/core-java-modules/core-java-numbers-5/src/test/java/com/baeldung/absintdiff/AbsoluteDifferenceOfTwoIntUnitTest.java @@ -0,0 +1,58 @@ +package com.baeldung.absintdiff; + +import static com.baeldung.absintdiff.IntDiffUtil.absDiff; +import static com.baeldung.absintdiff.IntDiffUtil.absDiff2; +import static com.baeldung.absintdiff.IntDiffUtil.absDiffAsLong; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class IntDiffUtil { + static int absDiff(int num1, int num2) { + int result = Math.abs(num1 - num2); + System.out.println("Absolute diff: " + result); + return result; + } + + static int absDiff2(int num1, int num2) { + return Math.abs(Math.subtractExact(num1, num2)); + } + + static long absDiffAsLong(int num1, int num2) { + return Math.abs((long) num1 - num2); + } +} + +public class AbsoluteDifferenceOfTwoIntUnitTest { + + @Test + void givenTwoIntegers_whenCallingAbsDiff_shouldGetExpectedResult() { + int diff1 = absDiff(100, -200); + assertEquals(300, diff1); + + int diff2 = absDiff(100, 200); + assertEquals(100, diff2); + + //integer overflow! output: Absolute diff: 2147483449 + //absDiff(Integer.MAX_VALUE, -200); + } + + @Test + void givenTwoIntegers_whenCallingAbsDiff2_shouldThrowException() { + int diff1 = absDiff2(100, -200); + assertEquals(300, diff1); + + int diff2 = absDiff2(100, 200); + assertEquals(100, diff2); + + //overflow -> exception + assertThrows(ArithmeticException.class, () -> absDiff2(Integer.MAX_VALUE, -200)); + } + + @Test + void givenTwoIntegers_whenCallingAbsDiffAsLong_shouldThrowException() { + long diff = absDiffAsLong(Integer.MAX_VALUE, -200); + assertEquals(Integer.MAX_VALUE + 200L, diff); + } +} \ No newline at end of file From edcca45a43080f44b8859f502aa6bcd342bbb1d1 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 2 Feb 2023 11:01:37 +0200 Subject: [PATCH 011/113] update tests to use junit5, mark live test --- persistence-modules/spring-data-redis/pom.xml | 5 ----- ...ngContextTest.java => SpringContextLiveTest.java} | 12 ++++++------ 2 files changed, 6 insertions(+), 11 deletions(-) rename persistence-modules/spring-data-redis/src/test/java/com/baeldung/{SpringContextTest.java => SpringContextLiveTest.java} (83%) diff --git a/persistence-modules/spring-data-redis/pom.xml b/persistence-modules/spring-data-redis/pom.xml index 330f0d975a..ab133192a0 100644 --- a/persistence-modules/spring-data-redis/pom.xml +++ b/persistence-modules/spring-data-redis/pom.xml @@ -42,11 +42,6 @@ spring-boot-starter-test test - - org.junit.platform - junit-platform-runner - test - cglib cglib-nodep diff --git a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/SpringContextLiveTest.java similarity index 83% rename from persistence-modules/spring-data-redis/src/test/java/com/baeldung/SpringContextTest.java rename to persistence-modules/spring-data-redis/src/test/java/com/baeldung/SpringContextLiveTest.java index 5167e63721..c370fdfecf 100644 --- a/persistence-modules/spring-data-redis/src/test/java/com/baeldung/SpringContextTest.java +++ b/persistence-modules/spring-data-redis/src/test/java/com/baeldung/SpringContextLiveTest.java @@ -1,8 +1,8 @@ package com.baeldung; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -13,17 +13,17 @@ import redis.embedded.RedisServerBuilder; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringRedisApplication.class) @DirtiesContext(classMode = ClassMode.BEFORE_CLASS) -public class SpringContextTest { +public class SpringContextLiveTest { private static redis.embedded.RedisServer redisServer; - @BeforeClass + @BeforeAll public static void startRedisServer() { redisServer = new RedisServerBuilder().port(6379).setting("maxmemory 256M").build(); redisServer.start(); } - @AfterClass + @AfterAll public static void stopRedisServer() { redisServer.stop(); } From 7f5722c564197e8375ce1d4a212b8d0b915567ef Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 2 Feb 2023 11:03:11 +0200 Subject: [PATCH 012/113] update path to xml file --- spring-boot-modules/spring-boot-keycloak/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml index 2b259346c3..a59a1e6874 100644 --- a/spring-boot-modules/spring-boot-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -89,7 +89,7 @@ com.baeldung - src/main/resources/products.xsd + ${project.basedir}/src/main/resources/products.xsd From adb277c07ef2875cf439f68cf47c4e27dcff34ea Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 2 Feb 2023 14:25:53 +0200 Subject: [PATCH 013/113] match boot version, update path --- spring-boot-modules/spring-boot-keycloak/pom.xml | 2 +- testing-modules/zerocode/pom.xml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml index a59a1e6874..1a2c1232b5 100644 --- a/spring-boot-modules/spring-boot-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -89,7 +89,7 @@ com.baeldung - ${project.basedir}/src/main/resources/products.xsd + /${project.basedir}/src/main/resources/products.xsd diff --git a/testing-modules/zerocode/pom.xml b/testing-modules/zerocode/pom.xml index bcd51bea85..15ef45be63 100644 --- a/testing-modules/zerocode/pom.xml +++ b/testing-modules/zerocode/pom.xml @@ -37,6 +37,7 @@ org.springframework.boot spring-boot-maven-plugin + ${spring.boot.version} it From 3809f71a49718484bf31ecdfd282fbb8c2401c71 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Thu, 2 Feb 2023 16:20:16 +0200 Subject: [PATCH 014/113] downgrade jaxb plugin --- spring-boot-modules/spring-boot-keycloak/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-keycloak/pom.xml b/spring-boot-modules/spring-boot-keycloak/pom.xml index 1a2c1232b5..34e93299ae 100644 --- a/spring-boot-modules/spring-boot-keycloak/pom.xml +++ b/spring-boot-modules/spring-boot-keycloak/pom.xml @@ -77,7 +77,7 @@ org.codehaus.mojo jaxb2-maven-plugin - 2.5.0 + 2.3.1 xjc From a33b690d0de19769ff6074b5a894526d8c2ddcb1 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 2 Feb 2023 22:34:44 +0800 Subject: [PATCH 015/113] Update README.md [skip ci] --- spring-boot-modules/spring-boot-3-native/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-3-native/README.md b/spring-boot-modules/spring-boot-3-native/README.md index 6f46263257..025a40c1d0 100644 --- a/spring-boot-modules/spring-boot-3-native/README.md +++ b/spring-boot-modules/spring-boot-3-native/README.md @@ -1,2 +1,3 @@ ## Relevant Articles - [Native Images with Spring Boot and GraalVM](https://www.baeldung.com/spring-native-intro) +- [Ahead of Time Optimizations in Spring 6](https://www.baeldung.com/spring-6-ahead-of-time-optimizations) From e1e7232d19900821742f42640839a3c333f8dc67 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 2 Feb 2023 22:37:10 +0800 Subject: [PATCH 016/113] Update README.md [skip ci] --- core-java-modules/core-java-19/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-19/README.md b/core-java-modules/core-java-19/README.md index 9663296da0..6a9c6c7fdd 100644 --- a/core-java-modules/core-java-19/README.md +++ b/core-java-modules/core-java-19/README.md @@ -1,2 +1,3 @@ ## Relevant Articles - [Record Patterns in Java 19](https://www.baeldung.com/java-19-record-patterns) +- [Structured Concurrency in Java 19](https://www.baeldung.com/java-structured-concurrency) From 697b3d7f53fb24322ddc624fdcd9eda1bb0462ba Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 2 Feb 2023 22:42:42 +0800 Subject: [PATCH 017/113] Update README.md [skip ci] --- docker-modules/docker-compose-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docker-modules/docker-compose-2/README.md b/docker-modules/docker-compose-2/README.md index 729105e3fd..353b85f154 100644 --- a/docker-modules/docker-compose-2/README.md +++ b/docker-modules/docker-compose-2/README.md @@ -1 +1,2 @@ ## Relevant Articles: +- [Communicating With Docker Containers on the Same Machine](https://www.baeldung.com/ops/docker-communicating-with-containers-on-same-machine) From 246fca6031332816207076673981eadcc5e7c03c Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 2 Feb 2023 22:55:14 +0800 Subject: [PATCH 018/113] Update README.md [skip ci] --- core-java-modules/core-java-11-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-11-3/README.md b/core-java-modules/core-java-11-3/README.md index e77e5b7f3d..4f5eb3ea56 100644 --- a/core-java-modules/core-java-11-3/README.md +++ b/core-java-modules/core-java-11-3/README.md @@ -5,3 +5,4 @@ This module contains articles about Java 11 core features ### Relevant articles - [Adding Parameters to Java HttpClient Requests](https://www.baeldung.com/java-httpclient-request-parameters) - [Writing a List of Strings Into a Text File](https://www.baeldung.com/java-list-to-text-file) +- [Java HttpClient – Map JSON Response to Java Class](https://www.baeldung.com/java-httpclient-map-json-response) From 3e3ac6772e5ac5a9bb485489de8bbea2a6a9afe3 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 2 Feb 2023 23:00:22 +0800 Subject: [PATCH 019/113] Update README.md [skip ci] --- core-java-modules/core-java-lang-oop-types-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-oop-types-2/README.md b/core-java-modules/core-java-lang-oop-types-2/README.md index 61b2853af9..ca8742d6c0 100644 --- a/core-java-modules/core-java-lang-oop-types-2/README.md +++ b/core-java-modules/core-java-lang-oop-types-2/README.md @@ -8,3 +8,4 @@ This module contains articles about types in Java - [Check if an Enum Value Exists in Java](https://www.baeldung.com/java-search-enum-values) - [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value) - [Filling a List With All Enum Values in Java](https://www.baeldung.com/java-enum-values-to-list) +- [Comparing a String to an Enum Value in Java](https://www.baeldung.com/java-comparing-string-to-enum) From 588591d05bcba5a8b8b6cc36d1d1ed1f4efd2757 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 2 Feb 2023 23:10:18 +0800 Subject: [PATCH 020/113] Update README.md [skip ci] --- spring-boot-modules/spring-boot-logging-log4j2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-logging-log4j2/README.md b/spring-boot-modules/spring-boot-logging-log4j2/README.md index 9688f8f83c..45d6c0a2f5 100644 --- a/spring-boot-modules/spring-boot-logging-log4j2/README.md +++ b/spring-boot-modules/spring-boot-logging-log4j2/README.md @@ -7,3 +7,4 @@ This module contains articles about logging in Spring Boot projects with Log4j 2 - [Logging to Graylog with Spring Boot](https://www.baeldung.com/graylog-with-spring-boot) - [Log Groups in Spring Boot 2.1](https://www.baeldung.com/spring-boot-log-groups) - [Writing Log Data to Syslog Using Log4j2](https://www.baeldung.com/log4j-to-syslog) +- [Spring Boot Logback and Log4j2 Extensions](https://www.baeldung.com/spring-boot-logback-log4j2) From aff5b83c2f51c23e0ca01c8411d929162bdaba82 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 2 Feb 2023 23:15:00 +0800 Subject: [PATCH 021/113] Update README.md [skip ci] --- spring-core-6/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-core-6/README.md b/spring-core-6/README.md index 1cb5935cc5..90e2dfed01 100644 --- a/spring-core-6/README.md +++ b/spring-core-6/README.md @@ -3,3 +3,4 @@ - [Instantiating Multiple Beans of the Same Class with Spring Annotations](https://www.baeldung.com/spring-same-class-multiple-beans) - [Using Environment Variables in Spring Boot’s application.properties](https://www.baeldung.com/spring-boot-properties-env-variables) - [Reinitialize Singleton Bean in Spring Context](https://www.baeldung.com/spring-reinitialize-singleton-bean) +- [HTTP Interface in Spring 6](https://www.baeldung.com/spring-6-http-interface) From 491bbf9eea3b4accf4e0efb2a6fc17a9fb08b272 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 2 Feb 2023 23:20:20 +0800 Subject: [PATCH 022/113] Update README.md [skip ci] --- core-java-modules/core-java-numbers-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-numbers-5/README.md b/core-java-modules/core-java-numbers-5/README.md index 7a010e2fbf..34651c8e6c 100644 --- a/core-java-modules/core-java-numbers-5/README.md +++ b/core-java-modules/core-java-numbers-5/README.md @@ -7,3 +7,4 @@ - [Make Division of Two Integers Result in a Float](https://www.baeldung.com/java-integer-division-float-result) - [Creating Random Numbers With No Duplicates in Java](https://www.baeldung.com/java-unique-random-numbers) - [Multiply a BigDecimal by an Integer in Java](https://www.baeldung.com/java-bigdecimal-multiply-integer) +- [Check if an Integer Value is null or Zero in Java](https://www.baeldung.com/java-check-integer-null-or-zero) From db514563bee7dbf456aa63def38ce0459ea4fc21 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 2 Feb 2023 23:25:16 +0800 Subject: [PATCH 023/113] Update README.md [skip ci] --- testing-modules/instancio/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/testing-modules/instancio/README.md b/testing-modules/instancio/README.md index 881477f036..35166ee017 100644 --- a/testing-modules/instancio/README.md +++ b/testing-modules/instancio/README.md @@ -1 +1,2 @@ -### Relevant articles +## Relevant articles +- [Generate Unit Test Data in Java Using Instancio](https://www.baeldung.com/java-test-data-instancio) From 6ce5eab40dbab4a9b0396d4070079f2ae0b8c4a9 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 2 Feb 2023 23:27:36 +0800 Subject: [PATCH 024/113] Update README.md [skip ci] --- core-java-modules/core-java-streams-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-streams-4/README.md b/core-java-modules/core-java-streams-4/README.md index b210c2775a..8e5e0652ef 100644 --- a/core-java-modules/core-java-streams-4/README.md +++ b/core-java-modules/core-java-streams-4/README.md @@ -6,3 +6,4 @@ - [Java 8 Streams: Multiple Filters vs. Complex Condition](https://www.baeldung.com/java-streams-multiple-filters-vs-condition) - [Finding Max Date in List Using Streams](https://www.baeldung.com/java-max-date-list-streams) - [Batch Processing of Stream Data in Java](https://www.baeldung.com/java-stream-batch-processing) +- [Stream to Iterable in Java](https://www.baeldung.com/java-stream-to-iterable) From 43e3204e3dc312cbdb237d231b41854310edb002 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 2 Feb 2023 23:29:26 +0800 Subject: [PATCH 025/113] Update README.md [skip ci] --- core-java-modules/core-java-lang-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-lang-5/README.md b/core-java-modules/core-java-lang-5/README.md index b8deff199e..5ff3e83d2c 100644 --- a/core-java-modules/core-java-lang-5/README.md +++ b/core-java-modules/core-java-lang-5/README.md @@ -14,3 +14,4 @@ This module contains articles about core features in the Java language - [Convert Between int and char in Java](https://www.baeldung.com/java-convert-int-char) - [Converting a Number from One Base to Another in Java](https://www.baeldung.com/java-converting-a-number-from-one-base-to-another) - [Check if Command-Line Arguments Are Null in Java](https://www.baeldung.com/java-check-command-line-args) +- [Determine if a Class Implements an Interface in Java](https://www.baeldung.com/java-check-class-implements-interface) From 7108eaa8ef2c7e4627c31dd80b6d19bdc251268c Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Thu, 2 Feb 2023 17:04:40 +0000 Subject: [PATCH 026/113] [JAVA-15024] Upgraded multipart functionality to apache client 5 (#13378) Co-authored-by: panagiotiskakos --- apache-httpclient/pom.xml | 40 ++++ .../HttpClientMultipartLiveTest.java | 207 +++++++++--------- .../CustomHttpClientResponseHandler.java | 11 + 3 files changed, 152 insertions(+), 106 deletions(-) create mode 100644 apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java diff --git a/apache-httpclient/pom.xml b/apache-httpclient/pom.xml index 26eb319ac0..47dd41dce7 100644 --- a/apache-httpclient/pom.xml +++ b/apache-httpclient/pom.xml @@ -54,6 +54,42 @@ + + org.apache.httpcomponents.core5 + httpcore5 + ${httpcore5.version} + + + commons-logging + commons-logging + + + + + + org.apache.httpcomponents.client5 + httpclient5-fluent + ${httpclient5-fluent.version} + + + commons-logging + commons-logging + + + + + + org.apache.httpcomponents.client5 + httpclient5 + ${httpclient5.version} + + + commons-logging + commons-logging + + + + com.github.tomakehurst wiremock @@ -78,6 +114,10 @@ 2.5.1 4.5.8 + + 5.2 + 5.2 + 5.2 \ No newline at end of file diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java index 7576e49034..b5ede3ed60 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java @@ -1,19 +1,24 @@ package com.baeldung.httpclient; -import org.apache.http.HttpEntity; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.entity.mime.content.FileBody; -import org.apache.http.entity.mime.content.StringBody; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.entity.mime.FileBody; +import org.apache.hc.client5.http.entity.mime.HttpMultipartMode; +import org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder; +import org.apache.hc.client5.http.entity.mime.StringBody; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; + +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.HttpEntity; +import org.apache.hc.core5.http.HttpStatus; import java.io.BufferedReader; import java.io.File; @@ -22,14 +27,10 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; -import java.util.logging.Level; -import java.util.logging.Logger; -import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; +import com.baeldung.httpclient.handler.CustomHttpClientResponseHandler; -public class HttpClientMultipartLiveTest { +class HttpClientMultipartLiveTest { // No longer available // private static final String SERVER = "http://echo.200please.com"; @@ -38,41 +39,16 @@ public class HttpClientMultipartLiveTest { private static final String TEXTFILENAME = "temp.txt"; private static final String IMAGEFILENAME = "image.jpg"; private static final String ZIPFILENAME = "zipFile.zip"; - private static final Logger LOGGER = Logger.getLogger("com.baeldung.httpclient.HttpClientMultipartLiveTest"); - private CloseableHttpClient client; private HttpPost post; private BufferedReader rd; - private CloseableHttpResponse response; - @Before - public final void before() { - client = HttpClientBuilder.create() - .build(); + @BeforeEach + public void before() { post = new HttpPost(SERVER); } - @After - public final void after() throws IllegalStateException, IOException { - post.completed(); - try { - client.close(); - } catch (final IOException e1) { - LOGGER.log(Level.SEVERE, e1.getMessage(), e1); - throw e1; - } - try { - rd.close(); - } catch (final IOException e) { - LOGGER.log(Level.SEVERE, e.getMessage(), e); - throw e; - } - ResponseUtil.closeResponse(response); - } - - // tests - @Test - public final void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { + void givenFileandMultipleTextParts_whenUploadwithAddPart_thenNoExceptions() throws IOException { final URL url = Thread.currentThread() .getContextClassLoader() .getResource("uploads/" + TEXTFILENAME); @@ -83,53 +59,61 @@ public class HttpClientMultipartLiveTest { final StringBody stringBody2 = new StringBody("This is message 2", ContentType.MULTIPART_FORM_DATA); // final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + builder.setMode(HttpMultipartMode.LEGACY); builder.addPart("file", fileBody); builder.addPart("text1", stringBody1); builder.addPart("text2", stringBody2); final HttpEntity entity = builder.build(); - // - post.setEntity(entity); - response = client.execute(post); - final int statusCode = response.getStatusLine() - .getStatusCode(); - final String responseString = getContent(); - final String contentTypeInHeader = getContentTypeHeader(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - // assertTrue(responseString.contains("Content-Type: multipart/form-data;")); - assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); - System.out.println(responseString); - System.out.println("POST Content Type: " + contentTypeInHeader); + post.setEntity(entity); + try(CloseableHttpClient client = HttpClientBuilder.create() + .build(); + + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(post, new CustomHttpClientResponseHandler())){ + final int statusCode = response.getCode(); + final String responseString = getContent(response.getEntity()); + final String contentTypeInHeader = getContentTypeHeader(); + + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); + System.out.println(responseString); + System.out.println("POST Content Type: " + contentTypeInHeader); + } } @Test - public final void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException { + void givenFileandTextPart_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoExeption() throws IOException { final URL url = Thread.currentThread() .getContextClassLoader() .getResource("uploads/" + TEXTFILENAME); final File file = new File(url.getPath()); final String message = "This is a multipart post"; final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + builder.setMode(HttpMultipartMode.LEGACY); builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, TEXTFILENAME); builder.addTextBody("text", message, ContentType.DEFAULT_BINARY); final HttpEntity entity = builder.build(); post.setEntity(entity); - response = client.execute(post); - final int statusCode = response.getStatusLine() - .getStatusCode(); - final String responseString = getContent(); - final String contentTypeInHeader = getContentTypeHeader(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - // assertTrue(responseString.contains("Content-Type: multipart/form-data;")); - assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); - System.out.println(responseString); - System.out.println("POST Content Type: " + contentTypeInHeader); + + try(CloseableHttpClient client = HttpClientBuilder.create() + .build(); + + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(post, new CustomHttpClientResponseHandler())){ + + final int statusCode = response.getCode(); + final String responseString = getContent(response.getEntity()); + final String contentTypeInHeader = getContentTypeHeader(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); + System.out.println(responseString); + System.out.println("POST Content Type: " + contentTypeInHeader); + } } @Test - public final void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { + void givenFileAndInputStreamandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final URL url = Thread.currentThread() .getContextClassLoader() .getResource("uploads/" + ZIPFILENAME); @@ -140,64 +124,75 @@ public class HttpClientMultipartLiveTest { final File file = new File(url2.getPath()); final String message = "This is a multipart post"; final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + builder.setMode(HttpMultipartMode.STRICT); builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, IMAGEFILENAME); builder.addBinaryBody("upstream", inputStream, ContentType.create("application/zip"), ZIPFILENAME); builder.addTextBody("text", message, ContentType.TEXT_PLAIN); final HttpEntity entity = builder.build(); post.setEntity(entity); - response = client.execute(post); - final int statusCode = response.getStatusLine() - .getStatusCode(); - final String responseString = getContent(); - final String contentTypeInHeader = getContentTypeHeader(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - // assertTrue(responseString.contains("Content-Type: multipart/form-data;")); - assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); - System.out.println(responseString); - System.out.println("POST Content Type: " + contentTypeInHeader); - inputStream.close(); + + try(CloseableHttpClient client = HttpClientBuilder.create() + .build(); + + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(post, new CustomHttpClientResponseHandler())){ + + final int statusCode = response.getCode(); + final String responseString = getContent(response.getEntity()); + final String contentTypeInHeader = getContentTypeHeader(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); + System.out.println(responseString); + System.out.println("POST Content Type: " + contentTypeInHeader); + inputStream.close(); + } } @Test - public final void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { + void givenCharArrayandText_whenUploadwithAddBinaryBodyandAddTextBody_ThenNoException() throws IOException { final String message = "This is a multipart post"; final byte[] bytes = "binary code".getBytes(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); + builder.setMode(HttpMultipartMode.STRICT); builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, TEXTFILENAME); builder.addTextBody("text", message, ContentType.TEXT_PLAIN); final HttpEntity entity = builder.build(); post.setEntity(entity); - response = client.execute(post); - final int statusCode = response.getStatusLine() - .getStatusCode(); - final String responseString = getContent(); - final String contentTypeInHeader = getContentTypeHeader(); - assertThat(statusCode, equalTo(HttpStatus.SC_OK)); - // assertTrue(responseString.contains("Content-Type: multipart/form-data;")); - assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); - System.out.println(responseString); - System.out.println("POST Content Type: " + contentTypeInHeader); + + try(CloseableHttpClient client = HttpClientBuilder.create() + .build(); + + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(post, new CustomHttpClientResponseHandler())){ + + final int statusCode = response.getCode(); + final String responseString = getContent(response.getEntity()); + final String contentTypeInHeader = getContentTypeHeader(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + assertTrue(contentTypeInHeader.contains("Content-Type: multipart/form-data;")); + System.out.println(responseString); + System.out.println("POST Content Type: " + contentTypeInHeader); + } + } // UTIL - private String getContent() throws IOException { - rd = new BufferedReader(new InputStreamReader(response.getEntity() - .getContent())); + private String getContent(HttpEntity httpEntity) throws IOException { + rd = new BufferedReader(new InputStreamReader(httpEntity.getContent())); String body = ""; StringBuilder content = new StringBuilder(); while ((body = rd.readLine()) != null) { - content.append(body).append("\n"); + content.append(body) + .append("\n"); } - return content.toString().trim(); + return content.toString() + .trim(); } - private String getContentTypeHeader() throws IOException { + private String getContentTypeHeader() { return post.getEntity() - .getContentType() - .toString(); + .getContentType(); } } diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java new file mode 100644 index 0000000000..0559854b35 --- /dev/null +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/handler/CustomHttpClientResponseHandler.java @@ -0,0 +1,11 @@ +package com.baeldung.httpclient.handler; + +import org.apache.hc.core5.http.ClassicHttpResponse; +import org.apache.hc.core5.http.io.HttpClientResponseHandler; + +public class CustomHttpClientResponseHandler implements HttpClientResponseHandler { + @Override + public ClassicHttpResponse handleResponse(ClassicHttpResponse response) { + return response; + } +} \ No newline at end of file From 629dbc140174265b56465a56b4000d56fb125e6c Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Thu, 2 Feb 2023 19:45:55 +0200 Subject: [PATCH 027/113] JAVA-17281 GitHub Issue: Read only Spring Boot App- NoUniqueBeanDefinitionException: No qualifying bean of type available: expected single matching bean but found 2 (#13394) Co-authored-by: n --- .../com/baeldung/boot/readonlyrepository/BookRepository.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/readonlyrepository/BookRepository.java b/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/readonlyrepository/BookRepository.java index 363b310c8c..11a75ba881 100644 --- a/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/readonlyrepository/BookRepository.java +++ b/spring-boot-modules/spring-boot-data-2/src/test/java/com/baeldung/boot/readonlyrepository/BookRepository.java @@ -2,5 +2,5 @@ package com.baeldung.boot.readonlyrepository; import org.springframework.data.repository.CrudRepository; -public interface BookRepository extends BookReadOnlyRepository, CrudRepository { +public interface BookRepository extends CrudRepository { } From 8c9e26a93320fca2e3058e0f0066fa5e2bea183f Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Thu, 2 Feb 2023 20:08:39 +0200 Subject: [PATCH 028/113] JAVA-16681 GitHub Issue: CacheUtils shown in this tutorial are now Deprecated and marked for removal (#13397) Co-authored-by: timis1 --- .../baeldung/webflux/caching/ItemService.java | 18 ++++++++---------- .../caching/MonoFluxResultCachingLiveTest.java | 6 +++--- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/spring-5-webflux-2/src/main/java/com/baeldung/webflux/caching/ItemService.java b/spring-5-webflux-2/src/main/java/com/baeldung/webflux/caching/ItemService.java index 7fc3732ba5..9bf934b504 100644 --- a/spring-5-webflux-2/src/main/java/com/baeldung/webflux/caching/ItemService.java +++ b/spring-5-webflux-2/src/main/java/com/baeldung/webflux/caching/ItemService.java @@ -1,22 +1,22 @@ package com.baeldung.webflux.caching; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Service; + import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.stereotype.Service; -import reactor.cache.CacheMono; + import reactor.core.publisher.Mono; @Service public class ItemService { private final ItemRepository repository; - private final LoadingCache cache; + private final LoadingCache> cache; public ItemService(ItemRepository repository) { this.repository = repository; - this.cache = Caffeine.newBuilder() - .build(this::getItem_withAddons); + this.cache = Caffeine.newBuilder().build(this::getItem_withCaffeine); } @Cacheable("items") @@ -34,9 +34,7 @@ public class ItemService { } @Cacheable("items") - public Mono getItem_withAddons(String id) { - return CacheMono.lookup(cache.asMap(), id) - .onCacheMissResume(() -> repository.findById(id).cast(Object.class)).cast(Item.class); + public Mono getItem_withCaffeine(String id) { + return cache.asMap().computeIfAbsent(id, k -> repository.findById(id).cast(Item.class)); } - } diff --git a/spring-5-webflux-2/src/test/java/com/baeldung/webflux/caching/MonoFluxResultCachingLiveTest.java b/spring-5-webflux-2/src/test/java/com/baeldung/webflux/caching/MonoFluxResultCachingLiveTest.java index 028a6d33a3..2075c1e77e 100644 --- a/spring-5-webflux-2/src/test/java/com/baeldung/webflux/caching/MonoFluxResultCachingLiveTest.java +++ b/spring-5-webflux-2/src/test/java/com/baeldung/webflux/caching/MonoFluxResultCachingLiveTest.java @@ -73,19 +73,19 @@ public void givenItem_whenGetItemIsCalled_thenMonoIsCached() { } @Test - public void givenItem_whenGetItemWithAddonsIsCalled_thenMonoResultIsCached() { + public void givenItem_whenGetItemWithCaffeineIsCalled_thenMonoResultIsCached() { Mono glass = itemService.save(new Item("glass", 1.00)); String id = glass.block().get_id(); - Mono mono = itemService.getItem_withAddons(id); + Mono mono = itemService.getItem_withCaffeine(id); Item item = mono.block(); assertThat(item).isNotNull(); assertThat(item.getName()).isEqualTo("glass"); assertThat(item.getPrice()).isEqualTo(1.00); - Mono mono2 = itemService.getItem_withAddons(id); + Mono mono2 = itemService.getItem_withCaffeine(id); Item item2 = mono2.block(); assertThat(item2).isNotNull(); From 13d4258e67df7d9629a8879c48097484be8235a5 Mon Sep 17 00:00:00 2001 From: Ulisses Lima Date: Thu, 2 Feb 2023 18:43:55 -0300 Subject: [PATCH 029/113] calling start() (#13417) --- .../java/com/baeldung/anonymousclass/AnonymousClassExample.java | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java b/core-java-modules/core-java/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java index a58dbf9864..1ea85942ee 100644 --- a/core-java-modules/core-java/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java +++ b/core-java-modules/core-java/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java @@ -9,5 +9,6 @@ public class AnonymousClassExample{ System.out.println("Thread: "+Thread.currentThread().getName()+" started"); } }); + t1.start(); } } \ No newline at end of file From d6bf32214dcc07085a78c9f54eae29ac6da80595 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Fri, 3 Feb 2023 10:27:34 +0530 Subject: [PATCH 030/113] Java 12714 eugen (#13358) * Java 12714 - Test build (#13191) * [JAVA-12714] Moved modules from default-first to jdk9-and-above profile * [JAVA-12714] Moved modules from default-second to jdk9-and-above profile * [JAVA-12714] Moved modules from default-heavy to jdk9-and-above profile * [JAVA-12714] Clean up - test build * [JAVA-12714] Clean up * [JAVA-12714] test build * [JAVA-12714] test build * [JAVA-12714] test build * [JAVA-12714] test build * [JAVA-12714] test build * [JAVA-12714] Clean up Co-authored-by: panagiotiskakos * Master to JAVA-12714-eugen (#13302) * Java 15029 (#13257) * [JAVA-15029] Formatting * [JAVA-15029] Clean up Co-authored-by: panagiotiskakos * Java 15030 (#13253) * [JAVA-15030] Upgrade to http client 5 * [JAVA-15030] Fixed MimeType test Co-authored-by: panagiotiskakos * Java 16961 (#13236) * [JAVA-16961] Moved code for article "Create an Empty Map in Java" * [JAVA-16961] Alter README.md * [JAVA-16961] Moved code for article "Sorting a Hashset in Java" * [JAVA-16961] Added links to README.md files * [JAVA-16961] Revert link changes * [JAVA-16961] Replaced junit4 with junit5 annotations * [JAVA-16961] test build * [JAVA-16961] Added junit annotations * [JAVA-16961] Added links Co-authored-by: panagiotiskakos * [List-CaseInsenContains] Case-Insensitive Searching in ArrayList (#13280) * Bael 5436 new (#13283) * BAEL-5777 - Mocking a singleton with Mockito * BAEL-5436 - Root mapping * Revert "BAEL-5777 - Mocking a singleton with Mockito" This reverts commit 358a061997a4b853e3215dea0217a070f0e391e4. * BAEL-5436 - Uncommenting controller * JAVA-15609 Changed to IntegrationTest to reproduce issue on Jenkins * BAEL-5959: Adjust code style (#13299) * BAEL-5959: Monad in Java * Fix test name * Fix code style * JAVA-16085, Potential issue in "A Guide to SAML with Spring Security" article (#13279) * JAVA-16085, Potential issue in "A Guide to SAML with Spring Security" article. * JAVA-16085, Cleanup unnecessary resources samlKeystore.jks and library maven-war-plugin. Co-authored-by: jogra * JAVA-15621, Potential issue in "Guide to UUID in Java" article. (#13271) * JAVA-15621, Potential issue in "Guide to UUID in Java" article. * JAVA-15621, Keep the raw strings in the article to make it easy for users to understand. * JAVA-15621, Keep the raw strings in the article to make it easy for users to understand. Co-authored-by: jogra * [JAVA-17295] Create and initialize ThreadPoolTaskExecutor (#13249) Co-authored-by: panagiotiskakos * [JAVA-15025] Upgraded to apache http 5 (#13296) * [JAVA-15025] Upgraded to apache http 5 * [JAVA-15025] Clean up Co-authored-by: panagiotiskakos * [JAVA-15016] Upgraded to apache http client 5.2 (#13269) * [JAVA-15016] Upgraded to apache http client 5.2 * [JAVA-15016] Clean up * [JAVA-15016] Junit 5 clean up Co-authored-by: panagiotiskakos Co-authored-by: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Co-authored-by: panagiotiskakos Co-authored-by: Kai Yuan Co-authored-by: Abhinav Pandey Co-authored-by: Anastasios Ioannidis Co-authored-by: Anastasios Ioannidis <121166333+anastasiosioannidis@users.noreply.github.com> Co-authored-by: Thiago dos Santos Hora Co-authored-by: jsgrah-spring Co-authored-by: jogra * Update pom.xml * [JAVA-12714] Removed plugin from atomix module (#13342) * [JAVA-12714] Removed plugin from atomix module * [JAVA-12714] Removed compiler plugin * [JAVA-12714] Removed compiler plugin Co-authored-by: panagiotiskakos * JAVA-12714 Fixed conflicts * JAVA-12714 Temporarily disabling ItemsUnitTest * JAVA-12714 Removed Duplicate Classes --------- Co-authored-by: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Co-authored-by: panagiotiskakos Co-authored-by: Kai Yuan Co-authored-by: Abhinav Pandey Co-authored-by: Anastasios Ioannidis Co-authored-by: Anastasios Ioannidis <121166333+anastasiosioannidis@users.noreply.github.com> Co-authored-by: Thiago dos Santos Hora Co-authored-by: jsgrah-spring Co-authored-by: jogra --- akka-modules/akka-http/pom.xml | 1 + annotations/annotation-processing/pom.xml | 1 + discord4j/pom.xml | 9 - feign/pom.xml | 1 - java-blockchain/pom.xml | 16 - java-websocket/pom.xml | 9 + javaxval-2/pom.xml | 3 - javaxval/pom.xml | 3 - .../baeldung/jersey/server/ItemsUnitTest.java | 4 + jgit/pom.xml | 1 + libraries-server-2/pom.xml | 4 + mapstruct/pom.xml | 5 - pom.xml | 628 +++++++++--------- spring-di/pom.xml | 4 + spring-exceptions/pom.xml | 4 + spring-katharsis/pom.xml | 4 + spring-mobile/pom.xml | 9 + spring-native/pom.xml | 3 - vaadin/pom.xml | 6 +- 19 files changed, 369 insertions(+), 346 deletions(-) diff --git a/akka-modules/akka-http/pom.xml b/akka-modules/akka-http/pom.xml index 9372107fc9..3af7c492ca 100644 --- a/akka-modules/akka-http/pom.xml +++ b/akka-modules/akka-http/pom.xml @@ -36,6 +36,7 @@ + 10.0.11 2.5.11 diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml index 14bbc409e5..2a17242ee5 100644 --- a/annotations/annotation-processing/pom.xml +++ b/annotations/annotation-processing/pom.xml @@ -21,6 +21,7 @@ + 1.0-rc2 diff --git a/discord4j/pom.xml b/discord4j/pom.xml index e15bd47583..3ea85c05c7 100644 --- a/discord4j/pom.xml +++ b/discord4j/pom.xml @@ -53,19 +53,10 @@ org.springframework.boot spring-boot-maven-plugin - - org.apache.maven.plugins - maven-compiler-plugin - - 1.8 - 1.8 - - - 1.8 3.1.1 diff --git a/feign/pom.xml b/feign/pom.xml index 369fa00137..3ac816fc1d 100644 --- a/feign/pom.xml +++ b/feign/pom.xml @@ -116,7 +116,6 @@ - 1.8 11.8 1.6.3 diff --git a/java-blockchain/pom.xml b/java-blockchain/pom.xml index 6d3910df80..2279a7ceff 100644 --- a/java-blockchain/pom.xml +++ b/java-blockchain/pom.xml @@ -24,22 +24,6 @@ true - - - org.apache.maven.plugins - maven-compiler-plugin - ${maven-compiler-plugin.version} - - ${maven.compiler.source} - ${maven.compiler.target} - - - - - 1.8 - 1.8 - - \ No newline at end of file diff --git a/java-websocket/pom.xml b/java-websocket/pom.xml index ffc2b0631e..7c3f32b092 100644 --- a/java-websocket/pom.xml +++ b/java-websocket/pom.xml @@ -28,6 +28,15 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + 1.1 2.8.0 diff --git a/javaxval-2/pom.xml b/javaxval-2/pom.xml index a63d21969b..5c311e10f8 100644 --- a/javaxval-2/pom.xml +++ b/javaxval-2/pom.xml @@ -60,9 +60,6 @@ 6.2.3.Final 6.2.0.Final - 3.6.1 - 1.8 - 1.8 3.0.0 5.3.21 2.7.1 diff --git a/javaxval/pom.xml b/javaxval/pom.xml index 753a46cffe..76472e29fb 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -60,9 +60,6 @@ 6.2.3.Final 6.2.0.Final - 3.6.1 - 1.8 - 1.8 3.0.0 5.3.21 2.7.1 diff --git a/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java b/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java index df85e26b76..b158d63720 100644 --- a/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java +++ b/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java @@ -9,10 +9,14 @@ import org.glassfish.grizzly.http.server.HttpServer; import org.junit.After; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; +import org.junit.jupiter.api.Disabled; import com.baeldung.jersey.server.http.EmbeddedHttpServer; +@Disabled +@Ignore public class ItemsUnitTest { private HttpServer server; diff --git a/jgit/pom.xml b/jgit/pom.xml index ca58709583..91881fbec8 100644 --- a/jgit/pom.xml +++ b/jgit/pom.xml @@ -36,6 +36,7 @@ + 4.5.0.201609210915-r diff --git a/libraries-server-2/pom.xml b/libraries-server-2/pom.xml index 7377fa3fa9..359954a6d2 100644 --- a/libraries-server-2/pom.xml +++ b/libraries-server-2/pom.xml @@ -34,6 +34,10 @@ + + org.apache.maven.plugins + maven-compiler-plugin + org.eclipse.jetty jetty-maven-plugin diff --git a/mapstruct/pom.xml b/mapstruct/pom.xml index cdcbc798a4..62c9ca5870 100644 --- a/mapstruct/pom.xml +++ b/mapstruct/pom.xml @@ -49,10 +49,7 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven-compiler-plugin.version} - ${maven.compiler.source} - ${maven.compiler.target} org.mapstruct @@ -78,8 +75,6 @@ 1.5.3.Final 4.3.4.RELEASE - 1.8 - 1.8 0.2.0 diff --git a/pom.xml b/pom.xml index 0b19c6eee6..77eb94f035 100644 --- a/pom.xml +++ b/pom.xml @@ -330,161 +330,104 @@ parent-spring-5 parent-java - akka-modules - algorithms-modules - annotations - antlr apache-cxf-modules - apache-kafka - apache-kafka-2 apache-libraries - apache-olingo apache-poi - apache-poi-2 - apache-rocketmq - apache-thrift - apache-tika apache-velocity - + di-modules asciidoctor - asm - - atomix aws-modules - axon - azure - - bazel checker-plugin - code-generation core-groovy-modules - core-java-modules - couchbase custom-pmd - data-structures - ddd deeplearning4j - di-modules - discord4j - disruptor - dozer drools - dubbo + - feign - + geotools - google-cloud + gradle-modules/gradle/maven-to-gradle - graphql-modules - grpc + guava-modules - hazelcast apache-httpclient httpclient-simple - hystrix + jackson-modules - jackson-simple - java-blockchain + javafx java-jdi - java-rmi - java-spi java-websocket - javax-sound - javaxval - javaxval-2 - javax-validation-advanced + jaxb jersey - jgit jhipster-5 - jib jmeter jmh - java-native + jsf json-modules - jsoup + kubernetes-modules - ksqldb + language-interop libraries-2 libraries-3 - libraries-7 - - libraries-apache-commons - libraries-apache-commons-collections - libraries-apache-commons-io libraries-data - libraries-data-2 + + libraries-data-db - libraries-data-io - libraries-files - libraries-http - libraries-http-2 - libraries-io - libraries-primitive - libraries-rpc libraries-security - libraries-server libraries-server-2 libraries-testing logging-modules lombok-modules - lucene - mapstruct maven-modules - mesos-marathon messaging-modules - metrics + microservices-modules muleesb - mustache - mybatis + netflix-modules - orika osgi + orika patterns-modules - pdf - pdf-2 + performance-tests persistence-modules - protobuffer + quarkus-modules - reactor-core - rsocket rule-engines-modules rxjava-modules - atomikos + reactive-systems security-modules - slack + vavr-modules web-modules @@ -533,93 +476,51 @@ saas-modules server-modules - spf4j - spring-4 - - spring-5 spring-reactive-modules - spring-5-webflux - spring-5-webflux-2 - - spring-activiti spring-aop spring-aop-2 - spring-batch - spring-batch-2 spring-bom spring-boot-modules spring-boot-rest - spring-caching - spring-caching-2 - spring-cloud-modules - spring-core - spring-core-2 - spring-core-3 spring-core-4 - spring-core-5 - spring-credhub - spring-cucumber - spring-di spring-di-2 - spring-di-3 spring-drools - spring-ejb-modules + spring-exceptions - spring-integration - spring-jenkins-pipeline spring-jersey spring-jinq - - spring-kafka spring-katharsis - spring-mobile - spring-native - spring-protobuf - spring-quartz - spring-remoting-modules + - spring-scheduling spring-security-modules spring-shell spring-soap spring-spel - spring-state-machine spring-static-resources spring-swagger-codegen - - spring-threads - spring-vault - spring-web-modules spring-websockets - static-analysis - - tensorflow-java testing-modules - vertx-modules video-tutorials - - webrtc xml xml-2 - xstream @@ -674,7 +575,6 @@ libraries-4 libraries-5 libraries-6 - spring-boot-modules/spring-boot-react spring-ejb-modules/ejb-beans @@ -715,161 +615,104 @@ parent-spring-5 parent-java - akka-modules - algorithms-modules - annotations - antlr apache-cxf-modules - apache-kafka - apache-kafka-2 apache-libraries - apache-olingo apache-poi - apache-poi-2 - apache-rocketmq - apache-thrift - apache-tika apache-velocity - + di-modules asciidoctor - asm - - atomix aws-modules - axon - azure - - bazel checker-plugin - code-generation core-groovy-modules - core-java-modules - couchbase custom-pmd - data-structures - ddd deeplearning4j - di-modules - discord4j - disruptor - dozer drools - dubbo + - feign - + geotools - google-cloud + gradle-modules/gradle/maven-to-gradle - graphql-modules - grpc + guava-modules - hazelcast apache-httpclient httpclient-simple - hystrix + jackson-modules - jackson-simple - java-blockchain + javafx java-jdi - java-rmi - java-spi java-websocket - javax-sound - javaxval - javaxval-2 - javax-validation-advanced + jaxb jersey - jgit jhipster-5 - jib jmeter jmh - java-native + jsf json-modules - jsoup + kubernetes-modules - ksqldb + language-interop libraries-2 libraries-3 - libraries-7 - - libraries-apache-commons - libraries-apache-commons-collections - libraries-apache-commons-io libraries-data - libraries-data-2 + + libraries-data-db - libraries-data-io - libraries-files - libraries-http - libraries-http-2 - libraries-io - libraries-primitive - libraries-rpc libraries-security - libraries-server libraries-server-2 libraries-testing logging-modules lombok-modules - lucene - mapstruct maven-modules - mesos-marathon messaging-modules - metrics + microservices-modules muleesb - mustache - mybatis + netflix-modules - orika osgi + orika patterns-modules - pdf - pdf-2 + performance-tests persistence-modules - protobuffer + quarkus-modules - reactor-core - rsocket rule-engines-modules rxjava-modules - atomikos + reactive-systems security-modules - slack + vavr-modules web-modules @@ -910,94 +753,50 @@ saas-modules server-modules - spf4j - spring-4 - - spring-5 spring-reactive-modules - spring-5-webflux - spring-5-webflux-2 - - - spring-activiti spring-aop spring-aop-2 - spring-batch - spring-batch-2 spring-bom spring-boot-modules spring-boot-rest - spring-caching - spring-caching-2 - spring-cloud-modules - spring-core - spring-core-2 - spring-core-3 spring-core-4 - spring-core-5 - spring-credhub - spring-cucumber - spring-di spring-di-2 - spring-di-3 spring-drools - spring-ejb-modules spring-exceptions - spring-integration - spring-jenkins-pipeline spring-jersey spring-jinq - - spring-kafka spring-katharsis - spring-mobile - spring-native - spring-protobuf - spring-quartz - spring-remoting-modules + - spring-scheduling spring-security-modules spring-shell spring-soap spring-spel - spring-state-machine spring-static-resources spring-swagger-codegen - - spring-threads - spring-vault - spring-web-modules spring-websockets - static-analysis - - tensorflow-java testing-modules - vertx-modules video-tutorials - - webrtc xml xml-2 - xstream @@ -1044,12 +843,10 @@ libraries-4 libraries-5 libraries-6 - spring-boot-modules/spring-boot-react spring-ejb-modules/ejb-beans - vaadin - vavr-modules + vavr-modules @@ -1119,64 +916,173 @@ core-java-modules/core-java-9-improvements core-java-modules/core-java-9-jigsaw - core-java-modules/core-java-9-streams - core-java-modules/core-java-10 - core-java-modules/core-java-11 - core-java-modules/core-java-11-2 - core-java-modules/core-java-11-3 - - - - - - - - core-java-modules/core-java-collections-set - core-java-modules/core-java-collections-list-4 - core-java-modules/core-java-collections-array-list - core-java-modules/core-java-collections-maps-4 - core-java-modules/core-java-collections-maps-5 - core-java-modules/core-java-concurrency-simple - core-java-modules/core-java-date-operations-1 - core-java-modules/core-java-datetime-conversion - core-java-modules/core-java-datetime-string - core-java-modules/core-java-io-conversions-2 - core-java-modules/core-java-jpms - core-java-modules/core-java-os - core-java-modules/core-java-streams-4 - core-java-modules/core-java-string-algorithms-3 - core-java-modules/core-java-string-operations-3 - core-java-modules/core-java-string-operations-4 - core-java-modules/core-java-string-operations-5 - core-java-modules/core-java-time-measurements - core-java-modules/core-java-networking-3 - core-java-modules/core-java-strings - core-java-modules/core-java-httpclient - spring-core-6 - ddd-contexts - docker-modules - apache-httpclient-2 - kubernetes-modules/kubernetes-spring - libraries-concurrency - maven-modules/compiler-plugin-java-9 - maven-modules/maven-generate-war - maven-modules/multimodulemavenproject - optaplanner - persistence-modules/sirix - persistence-modules/spring-data-cassandra-2 - quarkus-modules/quarkus-vs-springboot - quarkus-modules/quarkus-jandex - spring-boot-modules/spring-boot-cassandre - spring-boot-modules/spring-boot-camel - spring-boot-modules/spring-boot-3 - spring-boot-modules/spring-boot-3-native + core-java-modules/core-java-9-streams + core-java-modules/core-java-10 + core-java-modules/core-java-11 + core-java-modules/core-java-11-2 + core-java-modules/core-java-11-3 + + + + + + + + core-java-modules/core-java-collections-set + core-java-modules/core-java-collections-list-4 + core-java-modules/core-java-collections-array-list + core-java-modules/core-java-collections-maps-4 + core-java-modules/core-java-collections-maps-5 + core-java-modules/core-java-concurrency-simple + core-java-modules/core-java-date-operations-1 + core-java-modules/core-java-datetime-conversion + core-java-modules/core-java-datetime-string + core-java-modules/core-java-io-conversions-2 + core-java-modules/core-java-jpms + core-java-modules/core-java-os + core-java-modules/core-java-streams-4 + core-java-modules/core-java-string-algorithms-3 + core-java-modules/core-java-string-operations-3 + core-java-modules/core-java-string-operations-4 + core-java-modules/core-java-string-operations-5 + core-java-modules/core-java-time-measurements + core-java-modules/core-java-networking-3 + core-java-modules/core-java-strings + core-java-modules/core-java-httpclient + spring-core-6 + ddd-contexts + docker-modules + apache-httpclient-2 + kubernetes-modules/kubernetes-spring + libraries-concurrency + maven-modules/compiler-plugin-java-9 + maven-modules/maven-generate-war + maven-modules/multimodulemavenproject + optaplanner + persistence-modules/sirix + persistence-modules/spring-data-cassandra-2 + quarkus-modules/quarkus-vs-springboot + quarkus-modules/quarkus-jandex + spring-boot-modules/spring-boot-cassandre + spring-boot-modules/spring-boot-camel + spring-boot-modules/spring-boot-3 + spring-boot-modules/spring-boot-3-native spring-boot-modules/spring-boot-3-observation - spring-swagger-codegen/custom-validations-opeanpi-codegen - testing-modules/testing-assertions - persistence-modules/fauna - lightrun - tablesaw + spring-swagger-codegen/custom-validations-opeanpi-codegen + testing-modules/testing-assertions + persistence-modules/fauna + lightrun + tablesaw + + + + akka-modules + annotations + apache-httpclient + antlr + apache-kafka + apache-kafka-2 + apache-olingo + + apache-poi-2 + apache-rocketmq + apache-thrift + apache-tika + + asm + atomikos + atomix + axon + + bazel + code-generation + ddd + discord4j + disruptor + dozer + dubbo + feign + google-cloud + graphql-modules + grpc + hazelcast + hystrix + jackson-simple + java-blockchain + + java-rmi + java-spi + javax-sound + javaxval + javaxval-2 + javax-validation-advanced + jgit + jib + + java-native + jsoup + ksqldb + libraries-7 + libraries-apache-commons + libraries-apache-commons-collections + libraries-apache-commons-io + libraries-data-2 + libraries-data-io + libraries-files + libraries-http + libraries-http-2 + libraries-io + libraries-primitive + libraries-rpc + libraries-server + + lucene + mapstruct + mesos-marathon + metrics + mustache + mybatis + pdf + pdf-2 + protobuffer + reactor-core + rsocket + slack + + + + spring-5 + spring-5-webflux + spring-5-webflux-2 + spring-activiti + spring-batch-2 + spring-caching-2 + spring-core-2 + spring-core-3 + spring-core-5 + spring-di-3 + spring-cucumber + + spring-kafka + + spring-native + spring-protobuf + spring-quartz + + spring-scheduling + + spring-state-machine + spring-threads + tensorflow-java + xstream + webrtc + + + UTF-8 + 11 + 11 + @@ -1217,8 +1123,10 @@ + core-java-modules/core-java-collections-set core-java-modules/core-java-collections-list-4 + core-java-modules/core-java-collections-array-list core-java-modules/core-java-collections-maps-4 core-java-modules/core-java-collections-maps-5 core-java-modules/core-java-concurrency-simple @@ -1237,6 +1145,7 @@ core-java-modules/core-java-networking-3 core-java-modules/core-java-strings core-java-modules/core-java-httpclient + spring-core-6 ddd-contexts docker-modules apache-httpclient-2 @@ -1259,9 +1168,120 @@ testing-modules/testing-assertions persistence-modules/fauna lightrun - spring-core-6 tablesaw + + + + akka-modules + annotations + apache-httpclient + antlr + apache-kafka + apache-kafka-2 + apache-olingo + + apache-poi-2 + apache-rocketmq + apache-thrift + apache-tika + + asm + atomikos + atomix + axon + + bazel + code-generation + ddd + discord4j + disruptor + dozer + + dubbo + feign + google-cloud + graphql-modules + grpc + hazelcast + hystrix + jackson-simple + java-blockchain + + java-rmi + java-spi + javax-sound + javaxval + javaxval-2 + javax-validation-advanced + jgit + jib + + java-native + jsoup + ksqldb + + libraries-7 + libraries-apache-commons + libraries-apache-commons-collections + libraries-apache-commons-io + libraries-data-2 + libraries-data-io + libraries-files + libraries-http + libraries-http-2 + libraries-io + libraries-primitive + libraries-rpc + libraries-server + + lucene + mapstruct + mesos-marathon + metrics + mustache + mybatis + pdf + pdf-2 + protobuffer + reactor-core + rsocket + slack + + + + + spring-5 + spring-5-webflux + spring-5-webflux-2 + spring-activiti + spring-batch-2 + spring-caching-2 + spring-core-2 + spring-core-3 + spring-core-5 + spring-di-3 + spring-cucumber + + spring-kafka + + spring-native + spring-protobuf + spring-quartz + + spring-scheduling + + spring-state-machine + spring-threads + tensorflow-java + xstream + webrtc + + + UTF-8 + 11 + 11 + diff --git a/spring-di/pom.xml b/spring-di/pom.xml index af0601deb6..9d2a260a06 100644 --- a/spring-di/pom.xml +++ b/spring-di/pom.xml @@ -111,6 +111,10 @@ + + org.apache.maven.plugins + maven-compiler-plugin + org.apache.maven.plugins maven-war-plugin diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index 0621009bdd..6d573b6813 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -144,6 +144,10 @@ + + org.apache.maven.plugins + maven-compiler-plugin + org.apache.maven.plugins maven-war-plugin diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index b836a42bca..2fcc87e2dd 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -55,6 +55,10 @@ + + org.apache.maven.plugins + maven-compiler-plugin + org.codehaus.cargo cargo-maven2-plugin diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index 7f715c8735..bac1d2cdc9 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -32,6 +32,15 @@ + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + 1.1.5.RELEASE diff --git a/spring-native/pom.xml b/spring-native/pom.xml index 6940ee462b..55f17c833f 100644 --- a/spring-native/pom.xml +++ b/spring-native/pom.xml @@ -72,9 +72,6 @@ paketobuildpacks/builder:tiny 2.7.1 0.12.1 - 1.8 - 1.8 - 1.8 2.17.1 diff --git a/vaadin/pom.xml b/vaadin/pom.xml index 6976ff2a6a..82963f9e7f 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -76,6 +76,10 @@ + + org.apache.maven.plugins + maven-compiler-plugin + org.apache.maven.plugins maven-war-plugin @@ -184,8 +188,6 @@ 8.8.5 8.8.5 9.3.9.v20160517 - 1.8 - 1.8 local mytheme 3.0.0 From 0965a001227b4b8dfd67837558826f82cf578317 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Fri, 3 Feb 2023 18:22:38 +0200 Subject: [PATCH 031/113] JAVA-17762 Align module names, folder names and artifact id - Week 6 - 2023 (#13411) Co-authored-by: timis1 --- kubernetes-modules/kubernetes-spring/pom.xml | 7 +++---- .../spring-cloud-archaius-additionalsources/pom.xml | 2 +- spring-kafka-2/pom.xml | 4 ++-- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/kubernetes-modules/kubernetes-spring/pom.xml b/kubernetes-modules/kubernetes-spring/pom.xml index 01064fa384..05532ab0b0 100644 --- a/kubernetes-modules/kubernetes-spring/pom.xml +++ b/kubernetes-modules/kubernetes-spring/pom.xml @@ -3,11 +3,10 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - com.example - demo + kubernetes-spring 0.0.1-SNAPSHOT - demo - Demo project for Spring Boot + kubernetes-spring + Intro to Kubernetes with Spring boot com.baeldung diff --git a/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/pom.xml b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/pom.xml index f523e79bac..eee751b6a4 100644 --- a/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/pom.xml +++ b/spring-cloud-modules/spring-cloud-archaius/spring-cloud-archaius-additionalsources/pom.xml @@ -3,7 +3,7 @@ xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-cloud-archaius-additional-sources-simple + spring-cloud-archaius-additionalsources 1.0.0-SNAPSHOT spring-cloud-archaius-additionalsources jar diff --git a/spring-kafka-2/pom.xml b/spring-kafka-2/pom.xml index d51c2e300f..76a82f6000 100644 --- a/spring-kafka-2/pom.xml +++ b/spring-kafka-2/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - spring-kafka - spring-kafka + spring-kafka-2 + spring-kafka-2 Intro to Kafka with Spring From a46d70d0cdd7e026247e460b308c59652d9f6772 Mon Sep 17 00:00:00 2001 From: Anastasios Ioannidis <121166333+anastasiosioannidis@users.noreply.github.com> Date: Fri, 3 Feb 2023 19:47:48 +0200 Subject: [PATCH 032/113] JAVA-15980 Upgrade AWS Kinesis (#13294) * JAVA-15980 Upgrade AWS Kinesis * JAVA-15980 Minor readability improvement --- .../spring-cloud-stream-kinesis/pom.xml | 8 ++-- .../com/baeldung/binder/ConsumerBinder.java | 22 +++++------ .../binder/KinesisBinderApplication.java | 6 +-- .../com/baeldung/binder/ProducerBinder.java | 26 ++++++------- .../kclkpl/KinesisKCLApplication.java | 39 ++++++++++--------- .../kclkpl/KinesisKPLApplication.java | 17 ++++---- .../src/main/resources/application.properties | 12 +++--- .../src/test/resources/application.properties | 12 +++--- 8 files changed, 71 insertions(+), 71 deletions(-) diff --git a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml index 397f06399f..9d0d91b2c0 100644 --- a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml +++ b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/pom.xml @@ -36,7 +36,7 @@ com.amazonaws amazon-kinesis-client - 1.11.2 + 1.14.9 org.springframework.cloud @@ -46,9 +46,9 @@ - 1.11.632 - 2.0.2.RELEASE - 2.2.1.RELEASE + 1.12.380 + 2.2.0 + 4.0.0 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/binder/ConsumerBinder.java b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/binder/ConsumerBinder.java index 38ad634086..1fedec83ad 100644 --- a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/binder/ConsumerBinder.java +++ b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/binder/ConsumerBinder.java @@ -1,16 +1,16 @@ package com.baeldung.binder; -import org.springframework.cloud.stream.annotation.EnableBinding; -import org.springframework.cloud.stream.annotation.StreamListener; -import org.springframework.cloud.stream.messaging.Sink; -import org.springframework.stereotype.Component; +import java.util.function.Consumer; -@Component -@EnableBinding(Sink.class) +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration public class ConsumerBinder { - - @StreamListener(Sink.INPUT) - public void consume(String ip) { - System.out.println(ip); - } + @Bean + Consumer input() { + return str -> { + System.out.println(str); + }; + } } \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/binder/KinesisBinderApplication.java b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/binder/KinesisBinderApplication.java index e4f6916ed9..1cf31f9928 100644 --- a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/binder/KinesisBinderApplication.java +++ b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/binder/KinesisBinderApplication.java @@ -6,7 +6,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class KinesisBinderApplication { - public static void main(String[] args) { - SpringApplication.run(KinesisBinderApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(KinesisBinderApplication.class, args); + } } \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/binder/ProducerBinder.java b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/binder/ProducerBinder.java index 468f2886de..1486459a1e 100644 --- a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/binder/ProducerBinder.java +++ b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/binder/ProducerBinder.java @@ -1,24 +1,20 @@ package com.baeldung.binder; +import java.util.function.Supplier; import java.util.stream.IntStream; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.stream.annotation.EnableBinding; -import org.springframework.cloud.stream.messaging.Source; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; import org.springframework.messaging.support.MessageBuilder; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; -@Component -@EnableBinding(Source.class) -public class ProducerBinder { +@Configuration +class ProducerBinder { - @Autowired - private Source source; - - @Scheduled(fixedDelay = 3000L) - private void produce() { - IntStream.range(1, 200).mapToObj(ipSuffix -> "192.168.0." + ipSuffix) - .forEach(entry -> source.output().send(MessageBuilder.withPayload(entry).build())); + @Bean + public Supplier output() { + return () -> IntStream.range(1, 200) + .mapToObj(ipSuffix -> "192.168.0." + ipSuffix) + .map(entry -> MessageBuilder.withPayload(entry) + .build()); } } \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/kclkpl/KinesisKCLApplication.java b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/kclkpl/KinesisKCLApplication.java index 01c5af596d..1ab205d3aa 100644 --- a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/kclkpl/KinesisKCLApplication.java +++ b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/kclkpl/KinesisKCLApplication.java @@ -1,11 +1,14 @@ package com.baeldung.kclkpl; +import static com.amazonaws.services.kinesis.clientlibrary.lib.worker.KinesisClientLibConfiguration.*; + import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Regions; @@ -17,32 +20,30 @@ public class KinesisKCLApplication implements ApplicationRunner { @Value("${aws.access.key}") private String accessKey; - + @Value("${aws.secret.key}") private String secretKey; - + @Value("${ips.stream}") private String IPS_STREAM; - + public static void main(String[] args) { SpringApplication.run(KinesisKCLApplication.class, args); } - @Override - public void run(ApplicationArguments args) throws Exception { - BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); - KinesisClientLibConfiguration consumerConfig = new KinesisClientLibConfiguration( - "KinesisKCLConsumer", - IPS_STREAM, - new AWSStaticCredentialsProvider(awsCredentials), - "KinesisKCLConsumer") - .withRegionName(Regions.EU_CENTRAL_1.getName()); + @Override + public void run(ApplicationArguments args) throws Exception { + BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); - new Worker.Builder() - .recordProcessorFactory(new IpProcessorFactory()) - .config(consumerConfig) - .build() - .run(); - } - + KinesisClientLibConfiguration consumerConfig = new KinesisClientLibConfiguration("KinesisKCLConsumer", IPS_STREAM, "", "", DEFAULT_INITIAL_POSITION_IN_STREAM, new AWSStaticCredentialsProvider(awsCredentials), + new AWSStaticCredentialsProvider(awsCredentials), new AWSStaticCredentialsProvider(awsCredentials), DEFAULT_FAILOVER_TIME_MILLIS, "KinesisKCLConsumer", DEFAULT_MAX_RECORDS, DEFAULT_IDLETIME_BETWEEN_READS_MILLIS, + DEFAULT_DONT_CALL_PROCESS_RECORDS_FOR_EMPTY_RECORD_LIST, DEFAULT_PARENT_SHARD_POLL_INTERVAL_MILLIS, DEFAULT_SHARD_SYNC_INTERVAL_MILLIS, DEFAULT_CLEANUP_LEASES_UPON_SHARDS_COMPLETION, new ClientConfiguration(), new ClientConfiguration(), + new ClientConfiguration(), DEFAULT_TASK_BACKOFF_TIME_MILLIS, DEFAULT_METRICS_BUFFER_TIME_MILLIS, DEFAULT_METRICS_MAX_QUEUE_SIZE, DEFAULT_VALIDATE_SEQUENCE_NUMBER_BEFORE_CHECKPOINTING, Regions.EU_CENTRAL_1.getName(), DEFAULT_SHUTDOWN_GRACE_MILLIS, + DEFAULT_DDB_BILLING_MODE, null, 0, 0, 0); + + new Worker.Builder().recordProcessorFactory(new IpProcessorFactory()) + .config(consumerConfig) + .build() + .run(); + } } \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/kclkpl/KinesisKPLApplication.java b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/kclkpl/KinesisKPLApplication.java index 4ff7cf8087..1b2d9bed3f 100644 --- a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/kclkpl/KinesisKPLApplication.java +++ b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/java/com/baeldung/kclkpl/KinesisKPLApplication.java @@ -16,23 +16,22 @@ public class KinesisKPLApplication { @Value("${aws.access.key}") private String accessKey; - + @Value("${aws.secret.key}") private String secretKey; - + public static void main(String[] args) { SpringApplication.run(KinesisKPLApplication.class, args); } @Bean public KinesisProducer kinesisProducer() { - BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); - KinesisProducerConfiguration producerConfig = new KinesisProducerConfiguration() - .setCredentialsProvider(new AWSStaticCredentialsProvider(awsCredentials)) - .setVerifyCertificate(false) - .setRegion(Regions.EU_CENTRAL_1.getName()); + BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); + KinesisProducerConfiguration producerConfig = new KinesisProducerConfiguration().setCredentialsProvider(new AWSStaticCredentialsProvider(awsCredentials)) + .setVerifyCertificate(false) + .setRegion(Regions.EU_CENTRAL_1.getName()); - return new KinesisProducer(producerConfig); + return new KinesisProducer(producerConfig); } - + } \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/resources/application.properties index 777abef1cc..fddea95d45 100644 --- a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/resources/application.properties +++ b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/main/resources/application.properties @@ -12,9 +12,11 @@ cloud.aws.credentials.secret-key=my-aws-secret-key cloud.aws.region.static=eu-central-1 cloud.aws.stack.auto=false -spring.cloud.stream.bindings.input.destination=live-ips -spring.cloud.stream.bindings.input.group=live-ips-group -spring.cloud.stream.bindings.input.content-type=text/plain +spring.cloud.stream.bindings.input-in-0.destination=live-ips +spring.cloud.stream.bindings.input-in-0.group=live-ips-group +spring.cloud.stream.bindings.input-in-0.content-type=text/plain +spring.cloud.stream.function.definition = input -spring.cloud.stream.bindings.output.destination=myStream -spring.cloud.stream.bindings.output.content-type=text/plain \ No newline at end of file +spring.cloud.stream.bindings.output-out-0.destination=myStream +spring.cloud.stream.bindings.output-out-0.content-type=text/plain +spring.cloud.stream.poller.fixed-delay = 3000 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/test/resources/application.properties b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/test/resources/application.properties index 777abef1cc..fddea95d45 100644 --- a/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/test/resources/application.properties +++ b/spring-cloud-modules/spring-cloud-stream/spring-cloud-stream-kinesis/src/test/resources/application.properties @@ -12,9 +12,11 @@ cloud.aws.credentials.secret-key=my-aws-secret-key cloud.aws.region.static=eu-central-1 cloud.aws.stack.auto=false -spring.cloud.stream.bindings.input.destination=live-ips -spring.cloud.stream.bindings.input.group=live-ips-group -spring.cloud.stream.bindings.input.content-type=text/plain +spring.cloud.stream.bindings.input-in-0.destination=live-ips +spring.cloud.stream.bindings.input-in-0.group=live-ips-group +spring.cloud.stream.bindings.input-in-0.content-type=text/plain +spring.cloud.stream.function.definition = input -spring.cloud.stream.bindings.output.destination=myStream -spring.cloud.stream.bindings.output.content-type=text/plain \ No newline at end of file +spring.cloud.stream.bindings.output-out-0.destination=myStream +spring.cloud.stream.bindings.output-out-0.content-type=text/plain +spring.cloud.stream.poller.fixed-delay = 3000 \ No newline at end of file From 9bdd03fba474f73154d168e3a9f07a9d7eaef9ca Mon Sep 17 00:00:00 2001 From: jsgrah-spring Date: Fri, 3 Feb 2023 18:49:23 +0100 Subject: [PATCH 033/113] Generate the firebase-service-account.json file, add file to class-path and make application run again. (#13337) * JAVA-16938, Fix gcp-firebase module. * JAVA-16938, Add the firebase-service-account.json file to the classpath. --------- Co-authored-by: jogra --- .../src/main/resources/application.properties | 4 ++-- .../src/main/resources/firebase-service-account.json | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 gcp-firebase/src/main/resources/firebase-service-account.json diff --git a/gcp-firebase/src/main/resources/application.properties b/gcp-firebase/src/main/resources/application.properties index aacbde0d92..494aeb2444 100644 --- a/gcp-firebase/src/main/resources/application.properties +++ b/gcp-firebase/src/main/resources/application.properties @@ -1,2 +1,2 @@ -# Service account location. Can be a filesystem path or a classpath resource -gcp.firebase.service-account=file:firebase-service-account.json \ No newline at end of file +# Service account location. Can be a filesystem path or a classpath resource. NB: Generate and use your own firebase-service-account.json file. +gcp.firebase.service-account=classpath:firebase-service-account.json \ No newline at end of file diff --git a/gcp-firebase/src/main/resources/firebase-service-account.json b/gcp-firebase/src/main/resources/firebase-service-account.json new file mode 100644 index 0000000000..ed5afa9f13 --- /dev/null +++ b/gcp-firebase/src/main/resources/firebase-service-account.json @@ -0,0 +1,12 @@ +{ + "type": "service_account", + "project_id": "tutorials-2cdfb", + "private_key_id": "d9f6a684d6814f85ed2d0490585eb7bf590f983a", + "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDdJWTeGT2eBFo+\nXxzT9xFJYPtyawTAj0K1rVUNlWNUwj3zszK6P2sAsrpI2Rz1klwQ9aDz9i3+Opxv\n7UZ3pOzur6S58JnoswtNs6BZ9P7oeggLJJC6MPjioxwh8jLLIGMgdVtC2/iPYW3r\nGzurWlwkM8M8DyCgNq7KKJcx44pGcyy16ZGCYiijuTEmK6R+WHJTTyICzRFu3Org\nuHGlZUs/G4E76p10HanoFX2AIS/fDEEMP2DXBB73yoCal5GuvMY9yZWxnvV65Y5z\nGveY3NDB9EESbO2AAhDvHekWT17uWhymtO5N3gM8da48J9d51tVzi0D/NIPZnF0u\nTS64uxK3AgMBAAECggEAYuEQa7oPcfLyQscWRbRH1250n2E4e7zSkBcTW4J7Km+7\ncZajTOGEP4iqgF4Lc8XgQnkBYXOmdvDP97+47VAh3EtOtRDeUEyV9kUlonNH8rx1\nkj3kNEwnTHav4oG/slEl4WJ3zro6NinTEvdXQ7OgVVOLrPP6m4g3uQ5TJCxgLEUI\nTd3Hs3cg3P71mzEqfBF4NmGVmC1ea5lXFELd6giJJMvL7g+O2w22/fquGWOrreAM\ncj/G2Xv9/vmzeb9yzbgGxqCJyY6vspmd90fQLUu7bxkEY5/PPc6Zk8qay4AdEn47\nkL6hnJiR8H1wMCzV2RTUKE7ospriNVdBilXgxm9IMQKBgQD1TmF0Bg85zvXmEKBa\nLBhbc3xTtM7DOgKs+pI12sYDKwgL/QKEI/TKkYXua0aVGiQWc2Bk2/0sYhO6aB2f\n6AN1ZUrf4PRM8c53jebChc7beVLSjWI8Tx+kE+0t8864OwvELYZUzP35oSx3RdJD\nE/CvqBM7NQfJwx2Mw2VJK/YRGQKBgQDmyWLm/IWitehkITw6xMQpkkFs2m4Joq3A\nJvAyri58TRkw/7rqWaIxb5Wcy/7BOvjDN8PZNTHh4ZvhQiHpn7NGUks2/ULnWxUB\nWAA9YbeO9PNHJfZ6PjD2FSvwOXHj+vVkWt2GCXT8pDGYM2ImqXon85Oe3OH/h+N5\nktO9taesTwKBgQCSdPGKK/P7N61oZpTWQW1pbFHWSCUKOiBO1mtk6/E9AvwS7EQM\nUMteBfRInJPPgYP6Q3hRv2YwkX3l1TOavRMTjB5f/BbfuZ7jkj0r9mfCcXUZcIAu\nMa9abus0fFP3eolT3zpMdvdLiwbZTz5x/f29YkPZHZhAxdVmrWJThYOsQQKBgBDu\nZVsc25D8V3hBF/IXzWxfVn1t6PS8ApM+SBDvxmlIHrkBiez3dna6APfn32C9utJX\nnP6qcGZp7s2v1F0XYkeecfYuzmG6xOe8VQgryxOp1M87ccG2HlFvbDHLhRd8qdQa\n9nWG7BY81Yac/m5nsJaNwB6/hbUBeybIJtCcKxjxAoGBAJ3y+QSFb4AYmxLFtmMA\nklOvlT+r70w4RV/z4SEO1gjWEh9IozNSXknl5Q/8Zh9IVm3+/qYap//IzEv9JUc3\nv4+HlpZu0trxTpvRWWjPqVr3ssxRdiFLC0LCLEk4rzqWLBVyzJm8uHVIF9Inv8PE\naudInvdbnfAWi60+1Wi8u0Co\n-----END PRIVATE KEY-----\n", + "client_email": "firebase-adminsdk-2afzd@tutorials-2cdfb.iam.gserviceaccount.com", + "client_id": "111111112074248894669", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://oauth2.googleapis.com/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-2afzd%40tutorials-2cdfb.iam.gserviceaccount.com" +} From 4a1e20c4a89427893f987bcc1223f47083449f26 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Fri, 3 Feb 2023 23:20:38 +0530 Subject: [PATCH 034/113] JAVA-17200 Fix references to parents - Week 50 - 2022 (moved-3) (#13322) --- spring-boot-modules/spring-boot-mvc-birt/pom.xml | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/spring-boot-modules/spring-boot-mvc-birt/pom.xml b/spring-boot-modules/spring-boot-mvc-birt/pom.xml index badf77735f..274932f06c 100644 --- a/spring-boot-modules/spring-boot-mvc-birt/pom.xml +++ b/spring-boot-modules/spring-boot-mvc-birt/pom.xml @@ -9,13 +9,11 @@ jar Module For Spring Boot Integration with BIRT - - - org.springframework.boot - spring-boot-starter-parent - 2.1.1.RELEASE - + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 From 6e786945f92e0bd25cb65fa1aa6250d0201ca747 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Fri, 3 Feb 2023 23:23:47 +0530 Subject: [PATCH 035/113] JAVA-54 Create parents profile for tutorials repo (#13360) --- README.md | 5 ++++- pom.xml | 12 ++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index aecd561645..3c31b7fba1 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,9 @@ Next, they are segregated further on the basis of the tests that we want to exec Additionally, there are 2 profiles dedicated for JDK9 and above builds. -Therefore, we have a total of 8 profiles: +We also have a parents profile to build only parent modules. + +Therefore, we have a total of 9 profiles: | Profile | Includes | Type of test enabled | | -------------------------- | --------------------------- | -------------------- | @@ -45,6 +47,7 @@ Therefore, we have a total of 8 profiles: | integration-heavy | Heavy/long running projects | *IntegrationTest | | default-jdk9-and-above | JDK9 and above projects | *UnitTest | | integration-jdk9-and-above | JDK9 and above projects | *IntegrationTest | +| parents | Set of parent modules | None | Building the project ==================== diff --git a/pom.xml b/pom.xml index 77eb94f035..431d712c6b 100644 --- a/pom.xml +++ b/pom.xml @@ -1283,6 +1283,18 @@ 11 + + + parents + + parent-boot-1 + parent-boot-2 + parent-spring-4 + parent-spring-5 + parent-java + + + From abb739d3250a0d72aa1b032452419b21e2791292 Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Sat, 4 Feb 2023 07:50:37 +0100 Subject: [PATCH 036/113] BAEL-5866 Reading PDF File using Java (#13403) --- pdf/sample.pdf | Bin 0 -> 14049 bytes .../pdfreadertest/ReadPdfFileUnitTest.java | 52 ++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 pdf/sample.pdf create mode 100644 pdf/src/test/java/com/baeldung/pdfreadertest/ReadPdfFileUnitTest.java diff --git a/pdf/sample.pdf b/pdf/sample.pdf new file mode 100644 index 0000000000000000000000000000000000000000..805a21e6e029c58916e8e5b48fd445353c760375 GIT binary patch literal 14049 zcma)j1yEc~vvwem1Pkr~7PlaaJHg$9yR*0~?iSoVxCaR?!5xCTYY4UkcjsT;&%b-? z)_-=Z&Y7O>p6Qpcc1OO44gyjHC@^+3khSvX5V*i(tILI0dU4%*8+7N6iYHDm} zVv5KlYier_wg9j&a|;LnoWPEzhBk<98Bwv?(t$v<;Pu+@ML)<2H4M5|mA6{W>w5TH z)VW8Igok=~AxkRR?%UJ^k#|+|uP3xzw9U4P|8wZ>64&j1)4t}7e#>(4%Oi>)hUYA*=B1TQiJ~|)x8a-tP7kZ_w ziiE{&i1NhjkYIN|Ng8;6{JZZXzOIjc>r2M|9^2n@$MUbVe0H}t1u!WZnnSapZ0cm^ z>}YK21c06x^jM5lOu+!{zfOedv#A>xz$9e@RTTdFUF7d~DP2S+F*mS;3K*K%7gGsV zz{}|DQ;B9${W0T~M0xdF79p+XKI3xJcG1?olwstv6QC&0_W zDI+qefE}HU!HR~Ce+ikP#q!r9faCA({~piF@E?Wt&v=|(+&M#6ht`G+$ixYt{Svma z?!T&o^S{kR48exhcIGe3m_xJhU#oEaOZ{(k0|c-DfvhahApeir0s^^M+5f$|4!scE zK8rP9sqbd2wIqzqAwVd+r!t}URRlu>(J4|wwAdz8D}DHs`^j0%6nlA;C#--%BXG9;2AxeHNWRslEina)bMh?Qfq=?YJAnu49_qs z$J)=y7jx}S0Ey9^1Ur|Jsz1|A^?y>Yv~D(1yNliA37G{+!UEf1n*Ug&MJP6?$*>1gpVos;Oa zQcro(fl4#m^&eKzTdFRairz(}-Tj_puV)_x)Zcz>fG-#WrL$+xG}W5b#Wm-EPLm3r z6saJal~#ndgdF_MTlB_)`OMEdfivdrKU`&9PVW26=a&ZY;Ag?@;>23y4q=h#>BxeH zTRo!|G`8ZiY#3bcIr9;I;LG(#Wt@F#Ahxrac~s_n730y9+nQ!3Q!Ps^<)K-;N1=({ zw(#dGTZ2v^V5vj1v7tB|g}I=%IG{C<-DD*PlUyv^LiJ|wMsj?hXXud`=aG?|orob_ zy4C`wUXjpdXZ*L6ZTfAX+O;22gN}YG2u@eJX78}o-Y&u?8rOz2aZGU+)nSf4 z+GQ+z_DgFUP?>Rj;64Q*EWA~dgIm;{p~gd=mp=d!nTD~6li^wG>#L1zv3tu7eO@7^fxGag(8$y z-90570U@vytH^DWRw3UmX_MYM)np4vHgMs{9my5cYzV&v;>?*9GyvLy&GM5oNcf+} zt?r5HgcH^Lw8hq%e&#+EbCi8%OwCg@z&!ZXa3LX$zpn`x$_UZgC9_f5BEkuCVS*nM zl}C(D<)hW$dB}@56p08yCT6R$_+%*5xh^O;o|2xBnFJX<`7y1ku4Ng{+N7_XM=rp~ z(N9cdTB|iel`mAOViKmLS6E!Cgks9^B~f<#XWXsMHCxxj%NY z>bE2*C;AyQtIzZzsxrF`>Ktl0Ki)?)t*8hLXJktdnIYxj^a_V%&Am_N$_NWh)Zngr z9b_SrFFcqPKBOq90BgpEr9+HisMKEN zouzG5ry5mhT3Tz@La`y%pXX)IH1_5ndMCA3+J8m&xfMrOgH=gPcdGQR8BIGFQT2)V zA+y_#b691NAu6SeG{HQ`-1dGu3NLl*3Qg_@RU0ce_YZAe>A@t+`vM*Xk8d-O61!4K zNNDjD!u-J=?&teUxxw*2RRcjS_2hIs7}ZN25@wkSn83Kq0ZXckWA%RREqr*_cO|2A zTFSd!yePkzt=`phq6%^7Tp}w3n;G%#1j}wm9bV;DE#ID#X3ifeEq9PbcIuV+(p{naeNC*G!~ug|0PV4n%!6@gXpexNCyihna#6H-w(N) zyoEr#+~&dXpf`yVL#NJ$x`p^-@`!idm!u_e#o%lisnih_wJaI#XSe*fKCLR{lL(~7 zJGZ`*E)qK1E4idQH`If*-4J$6e)iwRvn5G~QE~0x(`F=)icz_ z`Rv;eruToqJcHNh6t-LY<5DdxjA<%bvxP%K*29OX(w5nKqtE?0#k69~rpL4-SQDZ6mDmA^d zJnB7F`bq8ZP?fm8w5__WL`IvtCx40muw|R4siLjE=5*!66{Jw%@TGKa?l3tVt-tTKXB^4@0%I?2I@1l_lW)Ic6#=Gep=s6w5wh?EUN5bU? zY0h|E--fA$e-^_FT3hLpT!`GYj{MqEP&Mi^M%7gmWFutw8`nJiOv<^<`;%<>o!3p` z(fglxjzY>?C|-iOM1ck!1>RGvTD+ zq0Xhr90u9#*$u|1_9)8{?CT=f7ijKjNOEO)qDA?h5Ss(LdT)y|#HHOwLcY#}Rud%`mjn*c>hAYMl5?F6I=o4| zgD{nGzUO2c+WBy|m1hdcuv)yaF&$n&IG82`MJX55S)GIM4)X+S33~gd*qcR)bTtfp z#Zjw7=e`q73KR*_AeZeUHpkhDMevqr?=z+R;V@nu?S0xaDxav`9o|~|6}Hx*tiGFU#QiZoZ}s->&rMsc5U?W zDU?UP_SIR=n?(jDwW-9u=I&a~4HWaKO2{iBQQr6Y>m7M^8jMHAQnQzJWU45_Gu#<;?^Qqzt?W>Fk@Ml9+sVSVWEz*t%Q#9<$2@_=cvTJmP6wtOSAtHRPIFON&M4|!` z@d<>vZ=ks2)hnxwivJ=W?*E+?=}DLVr6p|Cz{#P~fPOLRfXaonCG$~d<$7bap=!N) zz(KGptM}2|CCIy1z*Jw--bm^Tr)S~EK_=|qa>Ip|pbR#c>klRHu4OY+41Moxl3XNP z3OTpA7U_3~<<5j}^=^T;nztyo+G5IQSRKlFvPwHNoV52zfkUL*o|!W0CFy0$-#pch zXK*3Zf0*Xi^Vch$MSc5oIA;jV@RIS@m@UMa7WTzjuPX#3K6Lm9Y8OPPS0qOp=ur%Q zZ=SVg@sMSbi^u)x`m+*ZR;yAov}SmC#^>IC<)=gGP2N~VJHCtZ8=Jf(@(ZlP|$Ef1iA(x3g8LdjliB{I;o?Mk=B9&6XE5{;L=;i5NX4F zVA=&&&)LkaS4me1ZWbRMiRCF_EMu=WWu2*0cSJ@8we9cRF$CP`;R`%1(i-ANv5HGI z?PC~SxNp)m%;dev()(O_^GP{?PK~ zTGrC<%BoqVL*|+%$~cUxv6P?i*Y@$0sfLrlr^i9A;3wn}myY-lwK9X9V7JYAesbE- zdz__V3aw}k)B(OqRq+7#<2l9w!m%C#_BU3W#9xaa1BQSun04uO>}| zE-gK6<9}SCWF`Ys#~Jcr1ocm0vz*bv&Gjr#1pI*WDa-*Zqp|+%l=dW~J69GUsa*b? zOGXSO4GU@7KmVN8VBcb-S6#h}hqmgYOy)yTedv<|BsU9egt3y!zq1c33#LUFjx_b~erJ z*LMH4>b=)QM9n3wx}4beeiH5p1>G?3*_pL){>@RUU)0H9^|RoV^ci*M#{|bV+ZoH| zPDkGh%IQ_@u=;E!+$ZzVQE3T?5?DyxQlGu7F&^#ItPJnV-cvhrFH_aZMSE#w<7OzY ze#L8Dr3I4ur30v@YvWU*@30d8p#QSFz^_)tc*2c|fWXp2AHxhEQiiuC;0}mxu ziu(1Xjq&*SpC^Q=JUlmlu=FyWV0udFJL}j{&J(@|QUi@>Q{;)l+?Ilqc=IZG>Kms7 zr)~$k6?9mO^&{1ue*%5?2^Q5e*R*LzkV0rf^CDcQDQ?e+94pG|J_-rQN1Y)oQTR$q z01y`qtI5?6L1H?Adv&(A3(-SE-3GYA`o8EcX1iENI|!MBw80%IF;X#|)Vj~X^V2W{RnBB{c&X|E3x_-(f**)Jvo zSF%=ZuR(`F!I(XnZOYB2zBv2Z)^Dt%rc5#-&4>t}OnNy04KTWm{>PvEkg1d5^NQXF z1;49&7qVBeoe3cZiVwR|T+y#YGU`TG=tpO1L%;Hf@yVIPwI4I6_4U5+4ab_}pMCt@ z0UwK-+b;Gn4*tX|8vJwbT5QkN78Rz2^li|i*@nkYvx-6WToR{=(&epT-dbJz8gAb3 zz~DlKUw-|H2M0ut%1HB%IcXy+=;-2N-4+cP}+T@?hDtsg}x zRb5d)><}&cIeqG3#zm%-q2F7OnhKdeM{LMMegKW{Bs>OfrnQtN zkcJOcd%}0Nk1&r)kF;&_vu`hiyuY_At(WST=vS_nbAF$%_=%) zQopD3rlH9?i7(Js_{|dO_t;A`cyB%;7u9xT7NUG0k*)*&`Zx^2S0cw(r}^)kC-UN$ z2yXKXqrR|zJ*M^NE5w<42Z}1#A1}`E{IV<9rvlK3*`m?NpJgUdY;2RDSdUXUH(!Y2oez&PQ4X zdgNx9>gwug{^_>q+G0B;Ek1^|z?;E2uZo30N3vkiP$CAP~&U&8cUQX#Puz3 z+VgWT%@=B#CQS#h4Eex8VnSDbEw~t>!o(on|B!qd?LLCd@)Up5C5Oqzi85_R@Y9z- zE~HKvT&JHE-e*Y1gufS1C)^-{bWxA|<_7 zXFoB9TTJINTr%RwJMpLnZ~mpLkjVyZ@#Pw{xEhCVjnycy(}Bq>%VR9dKUlQo(@+X2 zjUo&ZFyQvNYsTU9J~A`mW!v6!tX`QmA09&*?x$>!rfqNw&v%uXU2T+GKOsrDG=T`15hl!C8s|w#Yd- zk#rC8u|(Xyq1J>v;Fw3|$dP}v-PB0RSl`v`gKH9H)wFeD_azhguk}TmjAz{gtZwdi zBn22dVmHfU@q}(qZ%-bWa-YAfh-W?flwyzD807~&w*PeMI2uX!*YcfBb49Uyq}&eE z@|{d`{V>Lf$Y|liP^{aU*_m`Jr7;ctYRCUowi=(JntQ7-Z7K}sLB*w(~t(Fu6@ zIdiZc<&PcaeG~cm^fTIxCNl|jN%*3!(_t^YIZB<<|7_T<>1I|uy6cYI|M;Uiu2Qkf z+Psh`ukNasf{rl0srN&S(z(Nxw?0PB!NXdyz?c+0b%d?1zs+rb4w=--<_7kc&&{w!upY8gjp6C$%)L0%)CYTS)`P-56v!;eJM&wylm2% zjo?zej|P7bZ@rKRvNiK1C0`;|$%QMRe1Zf3r~#gH<|}Hrr=9p}pDR*&-IAah<8FX-xx>*|T`zi|k;?bV+)q{yQr6S!lABK4$5T@9G)@L!uTPy^G9uzHgPwqZLUwYVsQ{E;eG1x7J(9T5(a* zZk@G<0M2o7+XfL6Lh_m}xz!|WB3oCk=~`>7aky)DHIuKHjP$QnbIP@d0qKe2_<7~X zv{B}Pfe{)i>>F^x|F7b1{}*1E{tmr)0a?S61yZed@# zX|{a}sU|ry2|4dXB6Fu8Kf8J2t<)rcLP}eVE^;;JIA6zO^Pn>qA`r1k9+N}-o{?Kh z#JV2!a094y5I@%;<`_k6`;(@M{uNT9$ouu{vydaJg6-L7u%gp;L38xZMtS&Hk%3BK zaY>%fKp_2))!mHq@@?~w`a@v1+DZ42yDsY7L*N!c)&roj?904r&mRxwo1AZDX5H`9 zRJ7*}3(zmOQ@->N#rH+tPVC86lKiS_e2<%8tl=?rIYy1$U1NGW8&aNyPD&U=y`8e1 za!N5GpM}-uD~2H@-Rz^$d@gmRNHO@{DbgJ7mZro}ukY430*66s#B>mY#Qrp%!caR> zDqWzO>T}=ojxGjW2{Jq({XRZPG-X^_E2D*Pk%@2EjB-t$iSA%g{2^sCrOduzw0D2o zI)j{R;}7*8^G%#hjV+gazowc80x8p1e4U16Hsq{<6+?(hyBI+?1G9ZHIHwVcU1X9! zc-ArW-F4H_zg91AcMOgcbA`TTdBuXBmoEsTAL8}u79(#$uCoPz`pLyUB787{clX zpU?maRg9Z448MLgMNkJR%&-hb>hoxtVI;RxtnMb;-t~V&$J6~oikaqb=8scjVLm9W zmLq3?wdgnb>A-`Q0FRtG`Jj_);~Gl=*a;U7&qG6;`tBh*o(5(i2E%_4HZ!rnJA&1R zg;~{rfZLx@8m6?!FGEe$WWgNTF;_OpTv= z;&*Sc+r-xg3QeCnI$zz^O@IF6-YGov_C1=0sL!Dcfh5cZz(26$6;}{qJ=3?;H?Kmb zK5a1jQ?k8tLq9oY%Xsrz2K0_uQpDf1Q-v+y3(Rl{oQ4oC486Z^J{=vrnhF}1@&*mv z^iz1fBV5&&A%Ej^$B30D$IZqdzIRT8$pS;Jf;PkeO{;3=hqps#&zQsh*9wJ z*cuYQ{VqQvWr+W-SAbynKg>5|E5DY5(-Tjq!(_{(dQAvItO_fFHGd_TYgYPttN_%h z2}ZEzI59rhWP~3pe6zvlpE3$=q)d@cX*DAb`#3phdtMv_kL7LSc34~J>Wo9)1 zLLY@;#Q71l1Di6%x1q|WfA3d;4`pRb@VX{WU19b9)A{H46t;{Z-7QwB_ry zPZ55cQ$`zdb)vk|oYTr1bj^rvNV+IGD15?=Q|z6~dprg$o$Ph8ys}mx?h}`0Vz-b^ z=Q?H2n7L_`&g{vkPG0ymF-{oHiP5E&3nwl3)^uB#rvSCzC7yd~1#9#tDPY1A^}07V zR$38!*9a?;jjuT;i8@C+J0>3Mh;In*@K0cxF>katce?SJvl5%p?=pH-Xp;eU4zi0*De#{hiJ}IR2%P?kXNLxU%O7))iv%pc)Yp^ z>SVlQu;=9e)+VKZ=oQ`on_U#**HOF<@+}g4=k=ulrUin&K>|@aMDbAD$le2PIAOsG zpn7HM<-FgBsC#{baR_&We#3G&rI+7!!F7V|0sAAS*{^cS_7HGbOzr;`j<}%MuX1vF z3C1Jy>6MoVKnunzp}GF?0_PFkO>$%Tf_j7ZBIAngQEa2-g71Xi1I8^?Z{}(e-2=fb z@d}#r;m&JNxswS(WP_Sn)bXkVe6eyiIg{0)3+qwj)2k^B9tP zMV5)~mMrk(A#>F*!aR(FEqjwkN7)f4`it90TVb^wF?8dC96EUS*Pv?Sq98hg_5&~CDf|20^ z-3DpbzYVklrq`i+O5V6=ge&f#NRAr3XwuL-&sY6}*%86|uh~44Br( z&3J0wxR{6T3%YCeE=VPUysw=7ofUL7=sut^V)>8cxPj&Bg^kR0dTb=kku(xJY?=>(G3>p7CTS z|4h;Yxqh;9xYK?P;qt!k;C_6DEtUx-F=yJ_3G7O+I8vGF0q7^p5wW2VD2sL(XvW1o zQ*sC}wEfI@kekU6!WtpcsKd@@sAhDZ!Q=?EM(Wo@Bf+afPs8?{P%?Q>w|-IU>wR`H zn7Ux}EJeq!Y5DvO(1{aXDK4O<+QsL%)0rpq8j%R$^i5j++V3444$fM6{iEv?TJe4`tbhfls-KF`K z&CP|Mkh` zTsW_>jqbVq(b>19F>3Sul#j zVo&1yXH_?zK(;}hQ_WR<*pj`h;-dNO91c5Au>$s= zer*W7HlBJ;*dBRTcwms9@Tdsp|pkuOOYhBR=NKV#-~M#jpu13Ei~H zlsuD36m5OBS?Oy`9D{%4>QYAe&d<3G3qQ3bug*_D1X7J3Cq;QitMHm>ydS4cp6<>% z{}F~VI2aiN>2?zzz>(2Z4yWDt{INQ|Ptr>gGeSn@&>VGR-|Q*Ck9A?Zpb@`Zymrul z`;w6kC9Y;)-2Vx z)Ua${a?HGJ-YUx+R;f@+xlyOJiaMliyt6}DQL``pr8lhW;7Ylg?iJ%Cay9-)2#bnO z!ohFt&UH(=d#p?>zq-F}xM1kjy^_?*dSbMp{kt)lwPd|CfA`KDeg|j8O!*5JZbAKz ziV<})d^7yruUiDuc=JCG2s)IHGxkYHVy#f>`$0IGz*x-&4do9{D~TV}{c{(L_9xDd zkc*TLs&dEtXvL~~gFNT(t=KeD`!q7JBQ%wjm6sHa1n>Dej3%0pMU@VachZ!VBdHSb zqcgrHn^EvPDeE}4vNA4b{~n31&r2+?lQma!=t47hNSSNy0RhW&wPctD4A{P@Mf4qt z+L}8`OMe}-K8nAB!_1&%F1S&N5_jz+A$fO$bn)i3f)oPQCx+07(V;O$#%RhxBM!o- zH`7&7cMR}&wPPEduus~Fxn%FmcHV}=!qX$o;r{%MScJ=lQ-`>1(NzL#+(q3VBZv8M zOm{GunldSV(N#!hLd%NZAnChy$ooI>jO%d%9sGm4_szeyPJOO^OI_6#0|%Mo#(cm& z$zh#(HCprQjXajOPVW*t#3JJ)XB_XH1oSZ$6<9p41tkLcOM63?4VX%HF*zI!F$X%f zShFi1rkV}BTpD`RzV-{DywZ`XPF9ZVQXi*w3(&TkAWRMUMPg=S<~FyFxrwQ%gOfdA z#Q1Dr68HuOA;R#s6CHHgo~2#md3AL#yw^mwPN2^n>7B`DFG*bcVOR|_-p1kau5VlN zDw0&}R@P8iuax|pY!%PWEN*w_I6FRle5H7#T>v=!=km=;)}L{Lf?1msEVKSaqbQG5 z$2a9%f8qtSaU@4L#NBV7_j81KEB3&y8z!+#vq8Jg%+n-W;H-Rw&4&t3N40sRFY^gs z_nDo_dSFR-h$6$HlBmjz*cHWWH98Q&oj=KKDtx0=IP3fL$7cnOVHSIMv6~o|P0Wxe zjJk5(I z5=Nx(YOX3W2sJNOi|)8K-nfWrSo9ldJ~7qDM<-F@Q^&hOkG2j$eLL@aFEX@<=oqH< zV|KO!dj3J~1OA!gm8e>o>*)P`GC|h^^!6vQs3+4Q7TuPbsgBk4Lr%Cy`bUggq9%m) z!REn!srD9>FL7^*?%t-CjjD`X(`Y+!-lMEOsR&4^O3C?REbB(NuxV)KMXNBWn5W}@ zn=ehbNVuyqZ2T3hBU1!q9M-}~$5D@q{klyfBPH|Q{ueMJJ_X=0nlx~Brc=`=mJBXi z>f3=c#v~x3Ct4<|8LnO<>a;a8F|M#Q0hCSOl`p1mR(O$SwK21F%Nb4}JbT3P@;*5;)2qk2lQ^1`+^=gKD( z5&P<3l)Bh@2J23?Z`b=h=?M!k!C@yyvgKNuYcRmm_iyKFMKjF}WPQUbO%P6*C7F^d zKX_kH+C70se^{{7E}9zyZzmz|&D#riKl^%1)pk^z#ZLst?0nX}csw7k-LLLwu`{Vz zoxXeYyjCynb;CI_458DC7#Q`2Y&UL98rS_k6Xgz?b}Vh>+nih!m+*qs%>NaDMHxU- z?HVTi4lb;Ot6KWudKaUidzJV1W?V#!qpU2lk%@zcF|tV&A;oKj9fk9sj9KG3V31un zHJbY^f&gJ6Yy|xKt#f}Tf(@aSvQMPl->Z{Ok9%x)GB}H=%6mZ+qAYg8vCl#AoMbxr zaq1W&8;sVR-@e2OQHkUm78=$H0ar>M#37$e^papI`^}B0Tz7BW)CtxSBu*RbJ)auh z<$YMe!rqof^1SstIj>qKSqN$1;G3V=pvSTilerEnYTjPzBRyHrsL$0Ut5 zkgkqs9MTbJ{<%lj$d2rYfIG~Hu@lzx7?E-3Q`G!p_`@`2F{N(2wLy)P9W(y-<{+iJ z<%0UV**TZ{(wVmfHc~B{Yq4w5J_9~lcgoQbHf(GJ+NUm!X-^hzw0DVJ-+Jk# z-w9yYB0X-o+^a*Qac{y8ykXr%&5RSYJG;IB7n}e5bpiq1qhR zDAP`3!Eb{inU7ZxrOqMctiI16bm$L{Hb&LN4YTiIF=5sD#~mwd6ntSMLJjv-d48aj zmPSX_;R;FS^3d(EGV-_4P1=Sx=Mgq&K9Z0TMvkD@W9XSTiV+N!AHZ{HEUq3-nlM}q?HwaA9AH^ z^%_qee|oxM(&uXV%3n}>ZAHv>N(EY=kHF>BC-Pke_OCrf;$I2y)iD}Np1e5_Vd}2I zj>4w*fBeYT;;KR>PgUY2Fra-o(izD&gw_5I*fxt;=K|6{*owd+%Rbto5?xy#JlDL1 z+o8uM3voR)FK=Eq9%Kb2t^kWa5K)BdAu=oxoKfszzImqfwMq+c9AkH54AP zUCW{OQP9CH@@Hpnfe8jDu$t^tJacK#SycXbi^|qLV7FEalPK;oRNYUjj}ETES)f{= zn)mc`UdB&qJ&-CoY9JI>hF#q&zdRyTANDa-BYh!t;p-0p2UZq>a&FL$^FuILAa<+PceV48 z)~lbE0Ub&7MzIGcJQLljtkOJS!@+{~L+|)U^d$2Yt1LxK;kfxbNxx0m!QR{+|DImKc zwzgF>!<|iW7xu>w-`<_AY#A|897rVxFmepJRj^khk|2^aB>u+2`MdxVT`!$KRa&kt z9Ikh}LLh21(L6|}Iesoqs0JQ`YyYZv)%#WP@CHOQSEoe8XgU)Fa_*omn;Z4j8~6PZ zlhoYadIXYAMv}^PYdQ&f4602*+^vXdMN57b`p7;1Hgc~leo*H*?Wo;WOH3SFs`Qy7o+J68D>QEf}r6dRe(^>-I*D!Uf~-Oth+tlJ`i|IP#R`%yGWQuVPG2nTP{1R=Hje1S(cJj}0a6bzYvQ z9O+j-FL4j+r*YXoh01Yq=n7V9t+hK`Ui}#>U#Z!d{L|4^S`PkQlj8B-?r9oQAN9az z71+ZMqd#ocGIogJ7??qRQPG?Fv5Qz!iV=r=fkJ!_7$9e)^XryQPJGKsh%EGh9j}LI z5_|mmRRxV+Y=p05b!g-WBQ^IOKfJtDo~*s}%#ZTqa%@dUwFc5bx*nNpe+>fprSUV< zCa!J#?!{Y%w3^+fs$R5blQHHRi5vRfI1i}8s4AZ>#sV&?YoEncbD&t@1@*V_& zM`RLmGKRwJ0bJZb#ur#S7b4S(s}~Ui3y_16m6?m3`vsD3YNG~)>@za6vIE(nW+I06 zlBOVY3ow9#gM|^u%*_h5l!5~3LB>M1FANSSZ2x6n!hhlY8Q3|v7+Kk&N&p5{W)4OU zHf9c1C;@|+831I4j-gG80W?BTVu~r0(W2l8C98mJ%>gw3FoOzJobBzcO6K=(vC4FLtb!r|RL?V zoMP=4tE2ysEhn&{Blxde0a-a&SrI8I#T3N Date: Sat, 4 Feb 2023 16:40:35 +0100 Subject: [PATCH 037/113] BAEL-6198: junit5 @Nested tests --- .../com/baeldung/junit5/nested/Article.java | 19 ++++ .../baeldung/junit5/nested/Membership.java | 16 ++++ .../baeldung/junit5/nested/Publication.java | 32 +++++++ .../java/com/baeldung/junit5/nested/User.java | 19 ++++ .../baeldung/junit5/nested/NestedTest.java | 41 ++++++++ .../junit5/nested/OnlinePublicationTest.java | 93 +++++++++++++++++++ 6 files changed, 220 insertions(+) create mode 100644 testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Article.java create mode 100644 testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Membership.java create mode 100644 testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Publication.java create mode 100644 testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/User.java create mode 100644 testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/NestedTest.java create mode 100644 testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/OnlinePublicationTest.java diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Article.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Article.java new file mode 100644 index 0000000000..6beac24827 --- /dev/null +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Article.java @@ -0,0 +1,19 @@ +package com.baeldung.junit5.nested; + +public class Article { + private String name; + private Membership articleLevel; + + public Article(String name, Membership articleLevel) { + this.name = name; + this.articleLevel = articleLevel; + } + + public String getName() { + return name; + } + + public Membership getArticleLevel() { + return articleLevel; + } +} \ No newline at end of file diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Membership.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Membership.java new file mode 100644 index 0000000000..de8e6f1fc8 --- /dev/null +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Membership.java @@ -0,0 +1,16 @@ +package com.baeldung.junit5.nested; + +public enum Membership { + FREE(0), SILVER(10), GOLD(20); + + private final int level; + + Membership(int level) { + this.level = level; + } + + public int compare(Membership other) { + return level - other.level; + } + +} \ No newline at end of file diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Publication.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Publication.java new file mode 100644 index 0000000000..998419acc9 --- /dev/null +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Publication.java @@ -0,0 +1,32 @@ +package com.baeldung.junit5.nested; + +import java.util.List; +import java.util.stream.Collectors; + +public class Publication { + private final List
articles; + + public Publication(List
articles) { + this.articles = articles; + } + + public List getReadableArticles(User user) { + return articles.stream() + .filter(a -> a.getArticleLevel() + .compare(user.getMembership()) <= 0) + .map(Article::getName) + .collect(Collectors.toList()); + } + + public List getLockedArticles(User user) { + return articles.stream() + .filter(a -> a.getArticleLevel() + .compare(user.getMembership()) > 0) + .map(Article::getName) + .collect(Collectors.toList()); + } + + public List
getArticles() { + return articles; + } +} \ No newline at end of file diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/User.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/User.java new file mode 100644 index 0000000000..3e9d7ebeff --- /dev/null +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/User.java @@ -0,0 +1,19 @@ +package com.baeldung.junit5.nested; + +public class User { + private String name; + private Membership membership; + + public User(String name, Membership membership) { + this.name = name; + this.membership = membership; + } + + public String getName() { + return name; + } + + public Membership getMembership() { + return membership; + } +} \ No newline at end of file diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/NestedTest.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/NestedTest.java new file mode 100644 index 0000000000..47a7879d17 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/NestedTest.java @@ -0,0 +1,41 @@ +package com.baeldung.junit5.nested; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +public class NestedTest { + + @BeforeEach + void beforeEach() { + System.out.println("NestedTest.beforeEach()"); + } + + @Nested + class FirstNestedClass { + @BeforeEach + void beforeEach() { + System.out.println("FirstNestedClass.beforeEach()"); + } + + @Test + void test() { + System.out.println("FirstNestedClass.test()"); + } + } + + + @Nested + class SecondNestedClass { + @BeforeEach + void beforeEach() { + System.out.println("SecondNestedClass.beforeEach()"); + } + + @Test + void test() { + System.out.println("SecondNestedClass.test()"); + } + } + +} diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/OnlinePublicationTest.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/OnlinePublicationTest.java new file mode 100644 index 0000000000..faae1d2916 --- /dev/null +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/OnlinePublicationTest.java @@ -0,0 +1,93 @@ +package com.baeldung.junit5.nested; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +@DisplayName("given a article publication with three articles") +class OnlinePublicationTest { + private Publication publication; + + @BeforeEach + void setupArticlesAndPublication() { + Article freeArticle = new Article("free article", Membership.FREE); + Article silverArticle = new Article("silver level article", Membership.SILVER); + Article goldArticle = new Article("gold level article", Membership.GOLD); + publication = new Publication(Arrays.asList(freeArticle, silverArticle, goldArticle)); + } + + @Test + @DisplayName("then 3 articles are available") + void shouldHaveThreeArticlesInTotal() { + List
allArticles = publication.getArticles(); + assertThat(allArticles).hasSize(3); + } + + @Nested + @DisplayName("when a user with a 'free' membership logs in") + class UserWithAFreeMembership { + User freeFreya = new User("Freya", Membership.FREE); + + @Test + @DisplayName("then he should be able to read the 'free' articles") + void shouldOnlyReadFreeArticles() { + List articles = publication.getReadableArticles(freeFreya); + assertThat(articles).containsExactly("free article"); + } + + @Test + @DisplayName("then he shouldn't be able to read the 'silver' and 'gold' articles") + void shouldSeeSilverAndGoldLevelArticlesAsLocked() { + List articles = publication.getLockedArticles(freeFreya); + assertThat(articles).containsExactlyInAnyOrder("silver level article", "gold level article"); + } + } + + @Nested + @DisplayName("when a user with a 'silver' membership logs in") + class UserWithSilverMembership { + User silverSilvester = new User("Silvester", Membership.SILVER); + + @Test + @DisplayName("then he should be able to read the 'free' and 'silver' level articles") + void shouldOnlyReadFreeAndSilverLevelArticles() { + List articles = publication.getReadableArticles(silverSilvester); + assertThat(articles).containsExactlyInAnyOrder("free article", "silver level article"); + } + + @Test + @DisplayName("then he should see the 'gold' level articles as locked") + void shouldSeeGoldLevelArticlesAsLocked() { + List articles = publication.getLockedArticles(silverSilvester); + assertThat(articles).containsExactlyInAnyOrder("gold level article"); + } + } + + @Nested + @DisplayName("when a user with a 'gold' membership logs in") + class UserWithGoldMembership { + User goldenGeorge = new User("George", Membership.GOLD); + + @Test + @DisplayName("then he should be able to read all the articles") + void shouldSeeAllArticles() { + List articles = publication.getReadableArticles(goldenGeorge); + assertThat(articles).containsExactlyInAnyOrder("free article", "silver level article", "gold level article"); + } + + @Test + @DisplayName("then he should not see any article as locked") + void shouldNotHaveHiddenArticles() { + List articles = publication.getLockedArticles(goldenGeorge); + assertThat(articles).isEmpty(); + } + + } + +} \ No newline at end of file From 432a20881edffa6d2316b6793860fe335a9eabb2 Mon Sep 17 00:00:00 2001 From: emanueltrandafir1993 Date: Sat, 4 Feb 2023 16:49:19 +0100 Subject: [PATCH 038/113] BAEL-6198: renaming --- .../junit5/nested/{NestedTest.java => NestedUnitTest.java} | 4 ++-- ...inePublicationTest.java => OnlinePublicationUnitTest.java} | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/{NestedTest.java => NestedUnitTest.java} (89%) rename testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/{OnlinePublicationTest.java => OnlinePublicationUnitTest.java} (99%) diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/NestedTest.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/NestedUnitTest.java similarity index 89% rename from testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/NestedTest.java rename to testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/NestedUnitTest.java index 47a7879d17..e30094cc9d 100644 --- a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/NestedTest.java +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/NestedUnitTest.java @@ -4,11 +4,11 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -public class NestedTest { +public class NestedUnitTest { @BeforeEach void beforeEach() { - System.out.println("NestedTest.beforeEach()"); + System.out.println("NestedUnitTest.beforeEach()"); } @Nested diff --git a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/OnlinePublicationTest.java b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/OnlinePublicationUnitTest.java similarity index 99% rename from testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/OnlinePublicationTest.java rename to testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/OnlinePublicationUnitTest.java index faae1d2916..bf3f15ff4e 100644 --- a/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/OnlinePublicationTest.java +++ b/testing-modules/junit5-annotations/src/test/java/com/baeldung/junit5/nested/OnlinePublicationUnitTest.java @@ -11,7 +11,7 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; @DisplayName("given a article publication with three articles") -class OnlinePublicationTest { +class OnlinePublicationUnitTest { private Publication publication; @BeforeEach From 9b0ae991f79ff64b2ee5b9e242d97ab54d93fa7a Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Sat, 4 Feb 2023 17:12:16 +0100 Subject: [PATCH 039/113] [instanceOf-stream] Checking instanceof in Java Stream (#13419) --- .../baeldung/keyword/InstanceOfUnitTest.java | 58 +++++++++++-------- 1 file changed, 35 insertions(+), 23 deletions(-) diff --git a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java index 0e082b69d3..6ba8ed024c 100644 --- a/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java +++ b/core-java-modules/core-java-lang-operators/src/test/java/com/baeldung/keyword/InstanceOfUnitTest.java @@ -1,55 +1,67 @@ package com.baeldung.keyword; -import org.junit.Assert; import org.junit.jupiter.api.Test; -import com.baeldung.keyword.Circle; -import com.baeldung.keyword.Ring; -import com.baeldung.keyword.Round; -import com.baeldung.keyword.Shape; -import com.baeldung.keyword.Triangle; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.*; public class InstanceOfUnitTest { @Test - public void giveWhenInstanceIsCorrect_thenReturnTrue() { + void giveWhenInstanceIsCorrect_thenReturnTrue() { Ring ring = new Ring(); - Assert.assertTrue("ring is instance of Round ", ring instanceof Round); + assertTrue(ring instanceof Round); } @Test - public void giveWhenObjectIsInstanceOfType_thenReturnTrue() { + void giveWhenObjectIsInstanceOfType_thenReturnTrue() { Circle circle = new Circle(); - Assert.assertTrue("circle is instance of Circle ", circle instanceof Circle); + assertTrue(circle instanceof Circle); } - + @Test - public void giveWhenInstanceIsOfSubtype_thenReturnTrue() { + void giveWhenInstanceIsOfSubtype_thenReturnTrue() { Circle circle = new Circle(); - Assert.assertTrue("circle is instance of Round", circle instanceof Round); + assertTrue(circle instanceof Round); } @Test - public void giveWhenTypeIsInterface_thenReturnTrue() { + void giveWhenTypeIsInterface_thenReturnTrue() { Circle circle = new Circle(); - Assert.assertTrue("circle is instance of Shape", circle instanceof Shape); + assertTrue(circle instanceof Shape); } - + @Test - public void giveWhenTypeIsOfObjectType_thenReturnTrue() { + void giveWhenTypeIsOfObjectType_thenReturnTrue() { Thread thread = new Thread(); - Assert.assertTrue("thread is instance of Object", thread instanceof Object); + assertTrue(thread instanceof Object); } @Test - public void giveWhenInstanceValueIsNull_thenReturnFalse() { + void giveWhenInstanceValueIsNull_thenReturnFalse() { Circle circle = null; - Assert.assertFalse("circle is instance of Round", circle instanceof Round); + assertFalse(circle instanceof Round); } @Test - public void giveWhenComparingClassInDiffHierarchy_thenCompilationError() { - // Assert.assertFalse("circle is instance of Triangle", circle instanceof Triangle); + void giveWhenComparingClassInDiffHierarchy_thenCompilationError() { + //assertFalse( circle instanceof Triangle); } -} + + @Test + void giveWhenStream_whenCastWithoutInstanceOfChk_thenGetException() { + Stream roundStream = Stream.of(new Ring(), new Ring(), new Circle()); + assertThrows(ClassCastException.class, () -> roundStream.map(it -> (Ring) it).collect(Collectors.toList())); + } + + @Test + void giveWhenStream_whenCastAfterInstanceOfChk_thenGetExpectedResult() { + Stream roundStream = Stream.of(new Ring(), new Ring(), new Circle()); + List ringList = roundStream.filter(it -> it instanceof Ring).map(it -> (Ring) it).collect(Collectors.toList()); + assertEquals(2, ringList.size()); + } +} \ No newline at end of file From 47e3b7967a78a4d32f92c7a85756fd79ab6426e9 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Sat, 4 Feb 2023 17:19:19 +0100 Subject: [PATCH 040/113] [x-asserts-in-one] Single Assert Call for Multiple Properties in JUnit5 (#13413) --- testing-modules/junit-5-advanced/pom.xml | 11 ++- .../MultiAssertionsInOneUnitTest.java | 94 +++++++++++++++++++ 2 files changed, 103 insertions(+), 2 deletions(-) create mode 100644 testing-modules/junit-5-advanced/src/test/java/com/baeldung/multiassertions/MultiAssertionsInOneUnitTest.java diff --git a/testing-modules/junit-5-advanced/pom.xml b/testing-modules/junit-5-advanced/pom.xml index f3e8d3f9a3..bfc490b03e 100644 --- a/testing-modules/junit-5-advanced/pom.xml +++ b/testing-modules/junit-5-advanced/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 junit-5-advanced 1.0-SNAPSHOT @@ -27,6 +27,12 @@ ${jmockit.version} test + + org.assertj + assertj-core + ${assertj.version} + test + @@ -46,6 +52,7 @@ 1.49 + 3.24.2 \ No newline at end of file diff --git a/testing-modules/junit-5-advanced/src/test/java/com/baeldung/multiassertions/MultiAssertionsInOneUnitTest.java b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/multiassertions/MultiAssertionsInOneUnitTest.java new file mode 100644 index 0000000000..6fec9015cf --- /dev/null +++ b/testing-modules/junit-5-advanced/src/test/java/com/baeldung/multiassertions/MultiAssertionsInOneUnitTest.java @@ -0,0 +1,94 @@ +package com.baeldung.multiassertions; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.from; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.math.BigDecimal; +import org.junit.jupiter.api.Test; + +public class MultiAssertionsInOneUnitTest { + private static final Product EXPECTED = new Product(42L, "LG Monitor", "32 inches, 4K Resolution, Ideal for programmer", true, new BigDecimal("429.99"), 77); + private static final Product TO_BE_TESTED = new Product(-1L, "LG Monitor", "dummy value: whatever", true, new BigDecimal("429.99"), 77); + + @Test + void givenAProductObject_whenUsingAssertAll_thenAssertMultiPropertiesInOneCall() { + //@formatter:off + assertAll("Verify Product properties", + () -> assertEquals(EXPECTED.getName(), TO_BE_TESTED.getName()), + () -> assertEquals(EXPECTED.isOnSale(), TO_BE_TESTED.isOnSale()), + () -> assertEquals(EXPECTED.getStockQuantity(), TO_BE_TESTED.getStockQuantity()), + () -> assertEquals(EXPECTED.getPrice(), TO_BE_TESTED.getPrice())); + //@formatter:on + } + + @Test + void givenAProductObject_whenUsingAssertJExtracting_thenAssertMultiPropertiesInOneCall() { + //@formatter:off + assertThat(TO_BE_TESTED) + .extracting("name", "onSale", "stockQuantity", "price") + .containsExactly(EXPECTED.getName(), EXPECTED.isOnSale(), EXPECTED.getStockQuantity(), EXPECTED.getPrice()); + + assertThat(TO_BE_TESTED) + .extracting(Product::getName, Product::isOnSale, Product::getStockQuantity,Product::getPrice) + .containsExactly(EXPECTED.getName(), EXPECTED.isOnSale(), EXPECTED.getStockQuantity(), EXPECTED.getPrice()); + //@formatter:on + } + + @Test + void givenAProductObject_whenUsingAssertJReturns_thenAssertMultiPropertiesInOneCall() { + //@formatter:off + assertThat(TO_BE_TESTED) + .returns(EXPECTED.getName(),from(Product::getName)) + .returns(EXPECTED.isOnSale(), from(Product::isOnSale)) + .returns(EXPECTED.getStockQuantity(), from(Product::getStockQuantity)) + .returns(EXPECTED.getPrice(), from(Product::getPrice)) + + .doesNotReturn(EXPECTED.getId(), from(Product::getId)) + .doesNotReturn(EXPECTED.getDescription(), from(Product::getDescription)); + //@formatter:on + } +} + +class Product { + private Long id; + private String name; + private String description; + private boolean onSale; + private BigDecimal price; + private int stockQuantity; + + public Product(Long id, String name, String description, boolean onSale, BigDecimal price, int stockQuantity) { + this.id = id; + this.name = name; + this.description = description; + this.onSale = onSale; + this.price = price; + this.stockQuantity = stockQuantity; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getDescription() { + return description; + } + + public boolean isOnSale() { + return onSale; + } + + public BigDecimal getPrice() { + return price; + } + + public int getStockQuantity() { + return stockQuantity; + } +} \ No newline at end of file From 87c22e5be4d63cfcd6898bf4943c28ce1337803d Mon Sep 17 00:00:00 2001 From: Muhammad Asif Date: Sat, 4 Feb 2023 21:25:23 +0500 Subject: [PATCH 041/113] BAEL-5990 is implemented to generate JMeter dashboard reports (#13345) * BAEL-5990 is implemented to generate JMeter dashboard reports * BAEL-5990 made a fix to use Random nextInt() method with single arg * BAEL-5990 updated code to use Arrays.asList rather than List.of * BAEL-5990 Replaced tabs with space * BAEL-5990 Removed unnecessary exception in the method declaration * BAEL-5990 Updated class name --- jmeter/pom.xml | 86 ++++++++++++ .../dashboard/DashboardApplication.java | 15 +++ .../dashboard/controllers/Dashboard.java | 42 ++++++ .../com/baeldung/dashboard/models/Quotes.java | 13 ++ .../resources/dashboard/ReportsDashboard.csv | 16 +++ .../resources/dashboard/ReportsDashboard.jmx | 127 ++++++++++++++++++ jmeter/src/main/resources/static/index.html | 15 +++ .../main/resources/templates/greeting.html | 10 ++ .../src/main/resources/templates/quote.html | 11 ++ jmeter/src/main/resources/templates/time.html | 10 ++ 10 files changed, 345 insertions(+) create mode 100644 jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java create mode 100644 jmeter/src/main/java/com/baeldung/dashboard/controllers/Dashboard.java create mode 100644 jmeter/src/main/java/com/baeldung/dashboard/models/Quotes.java create mode 100644 jmeter/src/main/resources/dashboard/ReportsDashboard.csv create mode 100644 jmeter/src/main/resources/dashboard/ReportsDashboard.jmx create mode 100644 jmeter/src/main/resources/static/index.html create mode 100644 jmeter/src/main/resources/templates/greeting.html create mode 100644 jmeter/src/main/resources/templates/quote.html create mode 100644 jmeter/src/main/resources/templates/time.html diff --git a/jmeter/pom.xml b/jmeter/pom.xml index b2e4197dfc..c4b15405ec 100644 --- a/jmeter/pom.xml +++ b/jmeter/pom.xml @@ -68,5 +68,91 @@ 2.6.0 + + + + dashboard + + + env + dash + + + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-web + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + launch-web-app + + start + + + com.baeldung.dashboard.DashboardApplication + + + + + + com.lazerycode.jmeter + jmeter-maven-plugin + 3.7.0 + + + + configuration + + configure + + + + + jmeter-tests + + jmeter + results + + + + + ${project.basedir}/src/main/resources/dashboard + ${project.basedir}/src/main/resources/dashboard + true + true + false + + + + org.springframework.boot + spring-boot-maven-plugin + + + stop-web-app + + stop + + + + + + + + + 5.5 + + + \ No newline at end of file diff --git a/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java b/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java new file mode 100644 index 0000000000..a531b97be1 --- /dev/null +++ b/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.dashboard; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration; +import org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration; +import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; + +@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, MongoAutoConfiguration.class, MongoRepositoriesAutoConfiguration.class, MongoDataAutoConfiguration.class }) +public class DashboardApplication { + public static void main(String[] args) throws Exception { + SpringApplication.run(DashboardApplication.class, args); + } +} diff --git a/jmeter/src/main/java/com/baeldung/dashboard/controllers/Dashboard.java b/jmeter/src/main/java/com/baeldung/dashboard/controllers/Dashboard.java new file mode 100644 index 0000000000..8c749b21d8 --- /dev/null +++ b/jmeter/src/main/java/com/baeldung/dashboard/controllers/Dashboard.java @@ -0,0 +1,42 @@ +package com.baeldung.dashboard.controllers; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Random; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; + +import com.baeldung.dashboard.models.Quotes; + +@Controller +public class Dashboard { + + @GetMapping("/greeting") + public String getGreeting(Model model) { + model.addAttribute("host", System.getProperty("os.name")); + return "greeting"; + } + + @GetMapping("/quote") + public String getQuote(Model model) throws InterruptedException { + Random r = new Random(); + int day = r.nextInt(7); + String quote = Quotes.list.get(day); + + int wait = r.nextInt(6); + Thread.currentThread().sleep(wait); + model.addAttribute("quote", quote); + + return "quote"; + } + + @GetMapping("/time") + public String getTime(Model model) { + DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm:ss a"); + LocalDateTime now = LocalDateTime.now(); + model.addAttribute("time", fmt.format(now)); + return "time"; + } +} diff --git a/jmeter/src/main/java/com/baeldung/dashboard/models/Quotes.java b/jmeter/src/main/java/com/baeldung/dashboard/models/Quotes.java new file mode 100644 index 0000000000..7c8e6a732d --- /dev/null +++ b/jmeter/src/main/java/com/baeldung/dashboard/models/Quotes.java @@ -0,0 +1,13 @@ +package com.baeldung.dashboard.models; + +import java.util.Arrays; +import java.util.List; + +public class Quotes { + public static final List list = Arrays.asList("The greatest glory in living lies not in never falling, but in rising every time we fall. -Nelson Mandela\r\n", + "The way to get started is to quit talking and begin doing. -Walt Disney\r\n", + "Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma – which is living with the results of other people's thinking. -Steve Jobs\r\n", + "If life were predictable it would cease to be life, and be without flavor. -Eleanor Roosevelt\r\n", + "If you look at what you have in life, you'll always have more. If you look at what you don't have in life, you'll never have enough. -Oprah Winfrey\r\n", + "If you set your goals ridiculously high and it's a failure, you will fail above everyone else's success. -James Cameron\r\n", "Life is what happens when you're busy making other plans. -John Lennon"); +} diff --git a/jmeter/src/main/resources/dashboard/ReportsDashboard.csv b/jmeter/src/main/resources/dashboard/ReportsDashboard.csv new file mode 100644 index 0000000000..046666ca2b --- /dev/null +++ b/jmeter/src/main/resources/dashboard/ReportsDashboard.csv @@ -0,0 +1,16 @@ +timeStamp,elapsed,label,responseCode,responseMessage,threadName,dataType,success,failureMessage,bytes,sentBytes,grpThreads,allThreads,URL,Latency,IdleTime,Connect +1674622105952,714,HTTP Request (/greeting),200,,Thread Group 1-4,text,true,,430,126,5,5,http://localhost:8080/greeting,705,0,7 +1674622105450,1216,HTTP Request (/greeting),200,,Thread Group 1-1,text,true,,430,126,5,5,http://localhost:8080/greeting,1207,0,54 +1674622105468,1198,HTTP Request (/greeting),200,,Thread Group 1-2,text,true,,430,126,5,5,http://localhost:8080/greeting,1189,0,36 +1674622106064,602,HTTP Request (/greeting),200,,Thread Group 1-5,text,true,,430,126,5,5,http://localhost:8080/greeting,593,0,2 +1674622105800,866,HTTP Request (/greeting),200,,Thread Group 1-3,text,true,,430,126,5,5,http://localhost:8080/greeting,857,0,1 +1674622106669,13,HTTP Request (/quote),200,,Thread Group 1-4,text,true,,515,123,5,5,http://localhost:8080/quote,12,0,0 +1674622106669,16,HTTP Request (/quote),200,,Thread Group 1-2,text,true,,548,123,5,5,http://localhost:8080/quote,16,0,0 +1674622106671,18,HTTP Request (/quote),200,,Thread Group 1-1,text,true,,629,123,5,5,http://localhost:8080/quote,18,0,0 +1674622106669,24,HTTP Request (/quote),200,,Thread Group 1-5,text,true,,602,123,5,5,http://localhost:8080/quote,24,0,0 +1674622106669,29,HTTP Request (/quote),200,,Thread Group 1-3,text,true,,515,123,5,5,http://localhost:8080/quote,29,0,0 +1674622106690,18,HTTP Request (/time),200,,Thread Group 1-1,text,true,,432,122,5,5,http://localhost:8080/time,18,0,0 +1674622106699,9,HTTP Request (/time),200,,Thread Group 1-3,text,true,,432,122,5,5,http://localhost:8080/time,9,0,0 +1674622106683,26,HTTP Request (/time),200,,Thread Group 1-4,text,true,,432,122,5,5,http://localhost:8080/time,25,0,0 +1674622106688,25,HTTP Request (/time),200,,Thread Group 1-2,text,true,,432,122,2,2,http://localhost:8080/time,25,0,0 +1674622106695,18,HTTP Request (/time),200,,Thread Group 1-5,text,true,,432,122,2,2,http://localhost:8080/time,17,0,0 diff --git a/jmeter/src/main/resources/dashboard/ReportsDashboard.jmx b/jmeter/src/main/resources/dashboard/ReportsDashboard.jmx new file mode 100644 index 0000000000..081920c671 --- /dev/null +++ b/jmeter/src/main/resources/dashboard/ReportsDashboard.jmx @@ -0,0 +1,127 @@ + + + + + + false + true + false + + + + + + + + Test Greetings Page + continue + + false + 1 + + 5 + 1 + false + + + true + + + + + + + localhost + 8080 + + + /greeting + GET + true + false + true + false + + + + + + + + + + localhost + 8080 + + + /quote + GET + true + false + true + false + + + + + + + + + + localhost + 8080 + + + /time + GET + true + false + true + false + + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + true + false + false + false + true + 0 + true + true + true + true + true + true + + + dashapp + + + + + + diff --git a/jmeter/src/main/resources/static/index.html b/jmeter/src/main/resources/static/index.html new file mode 100644 index 0000000000..fe2e1bf095 --- /dev/null +++ b/jmeter/src/main/resources/static/index.html @@ -0,0 +1,15 @@ + + + + + Jmeter Dashboard Test APP + + + + +

Get your Quote here

+

Get your Time here

+

Get your greeting here

+ + + \ No newline at end of file diff --git a/jmeter/src/main/resources/templates/greeting.html b/jmeter/src/main/resources/templates/greeting.html new file mode 100644 index 0000000000..3b023db6b1 --- /dev/null +++ b/jmeter/src/main/resources/templates/greeting.html @@ -0,0 +1,10 @@ + + + + Jmeter Dashboard Test APP + + + +

+ + \ No newline at end of file diff --git a/jmeter/src/main/resources/templates/quote.html b/jmeter/src/main/resources/templates/quote.html new file mode 100644 index 0000000000..8d943c2a3d --- /dev/null +++ b/jmeter/src/main/resources/templates/quote.html @@ -0,0 +1,11 @@ + + + + Jmeter Dashboard Test APP + + + +

+

+ + \ No newline at end of file diff --git a/jmeter/src/main/resources/templates/time.html b/jmeter/src/main/resources/templates/time.html new file mode 100644 index 0000000000..d068bbe050 --- /dev/null +++ b/jmeter/src/main/resources/templates/time.html @@ -0,0 +1,10 @@ + + + + Jmeter Dashboard Test APP + + + +

+ + \ No newline at end of file From ebd6a0e73a585ff792093fd0cb57d0d42e5578e7 Mon Sep 17 00:00:00 2001 From: vunamtien Date: Tue, 7 Feb 2023 01:54:29 +0700 Subject: [PATCH 042/113] BAEL-6049-validate-ipv4-address (#13287) * validate ipv4 * add unit test * add more unit tests * add more unit tests * add more unit test --------- Co-authored-by: tienvn4 --- .../urlvalidation/IPv4Validation.java | 27 ++++ .../IPv4ValidationUnitTest.java | 121 ++++++++++++++++++ 2 files changed, 148 insertions(+) create mode 100644 core-java-modules/core-java-networking-4/src/main/java/com/baeldung/urlvalidation/IPv4Validation.java create mode 100644 core-java-modules/core-java-networking-4/src/test/java/com/baeldung/ipv4validation/IPv4ValidationUnitTest.java diff --git a/core-java-modules/core-java-networking-4/src/main/java/com/baeldung/urlvalidation/IPv4Validation.java b/core-java-modules/core-java-networking-4/src/main/java/com/baeldung/urlvalidation/IPv4Validation.java new file mode 100644 index 0000000000..5d72873745 --- /dev/null +++ b/core-java-modules/core-java-networking-4/src/main/java/com/baeldung/urlvalidation/IPv4Validation.java @@ -0,0 +1,27 @@ +package com.baeldung.urlvalidation; + +import com.google.common.net.InetAddresses; +import org.apache.commons.validator.routines.InetAddressValidator; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class IPv4Validation { + + public static boolean validateWithApacheCommons(String ip) { + InetAddressValidator validator = InetAddressValidator.getInstance(); + return validator.isValid(ip); + } + + public static boolean validateWithGuava(String ip) { + return InetAddresses.isInetAddress(ip); + } + + public static boolean validateWithRegex(String ip) { + String regex = "^((25[0-5]|(2[0-4]|1\\d|[1-9]|)\\d)\\.?\\b){4}$"; + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(ip); + return matcher.matches(); + } + +} diff --git a/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/ipv4validation/IPv4ValidationUnitTest.java b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/ipv4validation/IPv4ValidationUnitTest.java new file mode 100644 index 0000000000..367d70117a --- /dev/null +++ b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/ipv4validation/IPv4ValidationUnitTest.java @@ -0,0 +1,121 @@ +package com.baeldung.ipv4validation; + +import org.junit.Test; + +import static com.baeldung.urlvalidation.IPv4Validation.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class IPv4ValidationUnitTest { + + @Test + public void givenValidIPv4_whenValidate_thenReturnsTrue() { + String ip = "192.168.0.1"; + assertTrue(validateWithApacheCommons(ip)); + assertTrue(validateWithGuava(ip)); + assertTrue(validateWithRegex(ip)); + } + + @Test + public void givenIPv4WithThreeOctets_whenValidate_thenReturnsFalse() { + String ip = "192.168.0"; + assertFalse(validateWithApacheCommons(ip)); + assertFalse(validateWithGuava(ip)); + assertFalse(validateWithRegex(ip)); + } + + @Test + public void givenIPv4WithLeadingZero_whenValidate_thenReturnsFalse() { + String ip = "192.168.0.01"; + assertFalse(validateWithApacheCommons(ip)); + assertFalse(validateWithGuava(ip)); + assertFalse(validateWithRegex(ip)); + } + + @Test + public void givenIPv4WithInvalidCharacter_whenValidate_thenReturnsFalse() { + String ip = "a.168.0.01"; + assertFalse(validateWithApacheCommons(ip)); + assertFalse(validateWithGuava(ip)); + assertFalse(validateWithRegex(ip)); + } + + @Test + public void givenIPv4HaveValueAbove255_whenValidate_thenReturnsFalse() { + String ip = "192.168.256.1"; + assertFalse(validateWithApacheCommons(ip)); + assertFalse(validateWithGuava(ip)); + assertFalse(validateWithRegex(ip)); + } + + @Test + public void givenValidIPv4WithTwoDigitOctet_whenValidate_thenReturnsTrue() { + String ip = "192.168.42.1"; + assertTrue(validateWithApacheCommons(ip)); + assertTrue(validateWithGuava(ip)); + assertTrue(validateWithRegex(ip)); + } + @Test + public void givenValidIPv4WithNumberInRange200And249_whenValidate_thenReturnsTrue() { + String ip = "192.168.42.222"; + assertTrue(validateWithApacheCommons(ip)); + assertTrue(validateWithGuava(ip)); + assertTrue(validateWithRegex(ip)); + } + + @Test + public void givenIPv4WithFourDigitOctet_whenValidate_thenReturnsFalse() { + String ip = "1921.168.42.222"; + assertFalse(validateWithApacheCommons(ip)); + assertFalse(validateWithGuava(ip)); + assertFalse(validateWithRegex(ip)); + } + + @Test + public void givenIPv4WithFiveOctets_whenValidate_thenReturnsFalse() { + String ip = "192.168.42.222.10"; + assertFalse(validateWithApacheCommons(ip)); + assertFalse(validateWithGuava(ip)); + assertFalse(validateWithRegex(ip)); + } + + @Test + public void givenIPv4WithTwoConsecutiveDots_whenValidate_thenReturnsFalse() { + String ip = "192.168..1"; + assertFalse(validateWithApacheCommons(ip)); + assertFalse(validateWithGuava(ip)); + assertFalse(validateWithRegex(ip)); + } + + @Test + public void givenOnlyDots_whenValidate_thenReturnsFalse() { + String ip = "..."; + assertFalse(validateWithApacheCommons(ip)); + assertFalse(validateWithGuava(ip)); + assertFalse(validateWithRegex(ip)); + } + + @Test + public void givenBlankString_whenValidate_thenReturnsFalse() { + String ip = " "; + assertFalse(validateWithApacheCommons(ip)); + assertFalse(validateWithGuava(ip)); + assertFalse(validateWithRegex(ip)); + } + + @Test + public void givenIPv4StartWithDot_whenValidate_thenReturnsFalse() { + String ip = ".192.168.0.1"; + assertFalse(validateWithApacheCommons(ip)); + assertFalse(validateWithGuava(ip)); + assertFalse(validateWithRegex(ip)); + } + @Test + public void givenIPv4EndWithDot_whenValidate_thenReturnsFalse() { + String ip = "192.168.0.1."; + assertFalse(validateWithApacheCommons(ip)); + assertFalse(validateWithGuava(ip)); + assertFalse(validateWithRegex(ip)); + } + +} From ff6a1e404e92c96580572690ab01caa096f8f9f4 Mon Sep 17 00:00:00 2001 From: Saikat Chakraborty <40471715+saikatcse03@users.noreply.github.com> Date: Tue, 7 Feb 2023 00:31:12 +0530 Subject: [PATCH 043/113] Bael 5961: OpenTelemetry integration with Spring Boot application (#13252) * Open telemetry in spring boot * Removed unused field * Test add and seperate packages * Refactored code * Version moved to property * Removed unused logback files * update version in docker file * corrected spacing * COde review refactoring * COde review refactoring * COde review refactoring * corrected property * PostContruct add on repo setup * corrected var names * change to junit 5 and other improvements * Port reverted back * Code review implement * Logger update * Logger var update --------- Co-authored-by: Saikat --- spring-cloud-modules/pom.xml | 1 + .../docker-compose.yml | 30 +++++ .../otel-config.yml | 23 ++++ .../spring-cloud-open-telemetry/pom.xml | 22 ++++ .../spring-cloud-open-telemetry1/Dockerfile | 7 ++ .../spring-cloud-open-telemetry1/pom.xml | 116 ++++++++++++++++++ .../opentelemetry/ProductApplication.java | 12 ++ .../opentelemetry/api/client/PriceClient.java | 34 +++++ .../configuration/RestConfiguration.java | 15 +++ .../controller/ProductController.java | 36 ++++++ .../exception/ProductControllerAdvice.java | 22 ++++ .../exception/ProductNotFoundException.java | 7 ++ .../baeldung/opentelemetry/model/Price.java | 39 ++++++ .../baeldung/opentelemetry/model/Product.java | 27 ++++ .../repository/ProductRepository.java | 55 +++++++++ .../src/main/resources/application.properties | 5 + .../opentelemetry/SpringContextTest.java | 16 +++ .../controller/ProductControllerUnitTest.java | 92 ++++++++++++++ .../spring-cloud-open-telemetry2/Dockerfile | 7 ++ .../spring-cloud-open-telemetry2/pom.xml | 115 +++++++++++++++++ .../opentelemetry/PriceApplication.java | 12 ++ .../controller/PriceController.java | 29 +++++ .../exception/PriceNotFoundException.java | 7 ++ .../exception/ProductControllerAdvice.java | 16 +++ .../baeldung/opentelemetry/model/Price.java | 27 ++++ .../repository/PriceRepository.java | 53 ++++++++ .../src/main/resources/application.properties | 4 + .../opentelemetry/SpringContextTest.java | 16 +++ .../controller/PriceControllerUnitTest.java | 57 +++++++++ 29 files changed, 902 insertions(+) create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/docker-compose.yml create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/otel-config.yml create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/pom.xml create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/Dockerfile create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/pom.xml create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/ProductApplication.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/api/client/PriceClient.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/configuration/RestConfiguration.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/controller/ProductController.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/exception/ProductControllerAdvice.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/exception/ProductNotFoundException.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/model/Price.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/model/Product.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/repository/ProductRepository.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/resources/application.properties create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/test/java/com/baeldung/opentelemetry/SpringContextTest.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/test/java/com/baeldung/opentelemetry/controller/ProductControllerUnitTest.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/Dockerfile create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/pom.xml create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/PriceApplication.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/controller/PriceController.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/exception/PriceNotFoundException.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/exception/ProductControllerAdvice.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/model/Price.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/repository/PriceRepository.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/resources/application.properties create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/test/java/com/baeldung/opentelemetry/SpringContextTest.java create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/test/java/com/baeldung/opentelemetry/controller/PriceControllerUnitTest.java diff --git a/spring-cloud-modules/pom.xml b/spring-cloud-modules/pom.xml index 68aa4cd2e5..43e2687d74 100644 --- a/spring-cloud-modules/pom.xml +++ b/spring-cloud-modules/pom.xml @@ -55,6 +55,7 @@ spring-cloud-data-flow spring-cloud-sleuth spring-cloud-openfeign-2 + spring-cloud-open-telemetry diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/docker-compose.yml b/spring-cloud-modules/spring-cloud-open-telemetry/docker-compose.yml new file mode 100644 index 0000000000..8a6833095c --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/docker-compose.yml @@ -0,0 +1,30 @@ +version: "4.0" + +services: + product-service: + platform: linux/x86_64 + build: spring-cloud-open-telemetry1/ + ports: + - "8080:8080" + + price-service: + platform: linux/x86_64 + build: spring-cloud-open-telemetry2/ + ports: + - "8081" + + jaeger-service: + image: jaegertracing/all-in-one:latest + ports: + - "16686:16686" + - "14250" + + collector: + image: otel/opentelemetry-collector:0.47.0 + command: [ "--config=/etc/otel-collector-config.yml" ] + volumes: + - ./otel-config.yml:/etc/otel-collector-config.yml + ports: + - "4317:4317" + depends_on: + - jaeger-service \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/otel-config.yml b/spring-cloud-modules/spring-cloud-open-telemetry/otel-config.yml new file mode 100644 index 0000000000..886c10a1c3 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/otel-config.yml @@ -0,0 +1,23 @@ +receivers: + otlp: + protocols: + grpc: + http: + +processors: + batch: + +exporters: + logging: + logLevel: debug + jaeger: + endpoint: jaeger-service:14250 + tls: + insecure: true + +service: + pipelines: + traces: + receivers: [ otlp ] + processors: [ batch ] + exporters: [ logging, jaeger ] diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/pom.xml b/spring-cloud-modules/spring-cloud-open-telemetry/pom.xml new file mode 100644 index 0000000000..69b3a1a478 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/pom.xml @@ -0,0 +1,22 @@ + + 4.0.0 + com.baeldung.spring.cloud + spring-cloud-open-telemetry + 1.0.0-SNAPSHOT + spring-cloud-open-telemetry + pom + + + com.baeldung.spring.cloud + spring-cloud-modules + 1.0.0-SNAPSHOT + + + + spring-cloud-open-telemetry1 + spring-cloud-open-telemetry2 + + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/Dockerfile b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/Dockerfile new file mode 100644 index 0000000000..8bae52cec4 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/Dockerfile @@ -0,0 +1,7 @@ +FROM adoptopenjdk/openjdk11:alpine + +COPY target/spring-cloud-open-telemetry1-1.0.0-SNAPSHOT.jar spring-cloud-open-telemetry.jar + +EXPOSE 8081 + +ENTRYPOINT ["java","-jar","/spring-cloud-open-telemetry.jar"] \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/pom.xml b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/pom.xml new file mode 100644 index 0000000000..5011590e73 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/pom.xml @@ -0,0 +1,116 @@ + + + 4.0.0 + spring-cloud-open-telemetry1 + com.baeldung.spring.cloud + 1.0.0-SNAPSHOT + spring-cloud-open-telemetry1 + jar + + + com.baeldung.spring.cloud + spring-cloud-open-telemetry + 1.0.0-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot-dependencies.version} + pom + import + + + org.springframework.cloud + spring-cloud-dependencies + ${release.train.version} + pom + import + + + org.springframework.cloud + spring-cloud-sleuth-otel-dependencies + ${spring-cloud-sleuth-otel.version} + import + pom + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-sleuth + + + org.springframework.cloud + spring-cloud-sleuth-brave + + + + + org.springframework.cloud + spring-cloud-sleuth-otel-autoconfigure + + + io.opentelemetry + opentelemetry-exporter-otlp-trace + + + io.grpc + grpc-okhttp + ${grpc-okhttp.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + + + spring-milestones + https://repo.spring.io/milestone + + + + + spring-milestones + https://repo.spring.io/milestone + + + + + 2.5.7 + 2020.0.4 + 1.0.0-M12 + 1.42.1 + + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/ProductApplication.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/ProductApplication.java new file mode 100644 index 0000000000..8427603340 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/ProductApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.opentelemetry; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ProductApplication { + + public static void main(String[] args) { + SpringApplication.run(ProductApplication.class, args); + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/api/client/PriceClient.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/api/client/PriceClient.java new file mode 100644 index 0000000000..d8b43b61a5 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/api/client/PriceClient.java @@ -0,0 +1,34 @@ +package com.baeldung.opentelemetry.api.client; + +import com.baeldung.opentelemetry.model.Price; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.client.RestTemplate; + +@Component +public class PriceClient { + + private static final Logger LOGGER = LoggerFactory.getLogger(PriceClient.class); + + private final RestTemplate restTemplate; + + @Autowired + public PriceClient(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + } + + @Value("${priceClient.baseUrl}") + private String baseUrl; + + public Price getPrice(@PathVariable("id") long productId){ + LOGGER.info("Fetching Price Details With Product Id {}", productId); + String url = String.format("%s/price/%d", baseUrl, productId); + ResponseEntity price = restTemplate.getForEntity(url, Price.class); + return price.getBody(); + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/configuration/RestConfiguration.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/configuration/RestConfiguration.java new file mode 100644 index 0000000000..5d8ba4beac --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/configuration/RestConfiguration.java @@ -0,0 +1,15 @@ +package com.baeldung.opentelemetry.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class RestConfiguration { + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } + +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/controller/ProductController.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/controller/ProductController.java new file mode 100644 index 0000000000..5586f5e9d0 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/controller/ProductController.java @@ -0,0 +1,36 @@ +package com.baeldung.opentelemetry.controller; + +import com.baeldung.opentelemetry.api.client.PriceClient; +import com.baeldung.opentelemetry.model.Product; +import com.baeldung.opentelemetry.repository.ProductRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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 ProductController { + + private static final Logger LOGGER = LoggerFactory.getLogger(ProductController.class); + + private final PriceClient priceClient; + + private final ProductRepository productRepository; + + @Autowired + public ProductController(PriceClient priceClient, ProductRepository productRepository) { + this.priceClient = priceClient; + this.productRepository = productRepository; + } + + @GetMapping(path = "/product/{id}") + public Product getProductDetails(@PathVariable("id") long productId){ + LOGGER.info("Getting Product and Price Details With Product Id {}", productId); + Product product = productRepository.getProduct(productId); + product.setPrice(priceClient.getPrice(productId)); + + return product; + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/exception/ProductControllerAdvice.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/exception/ProductControllerAdvice.java new file mode 100644 index 0000000000..0ab031f517 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/exception/ProductControllerAdvice.java @@ -0,0 +1,22 @@ +package com.baeldung.opentelemetry.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.client.HttpServerErrorException; + + +@RestControllerAdvice +public class ProductControllerAdvice { + + @ExceptionHandler(ProductNotFoundException.class) + public ResponseEntity handleProductNotFoundException(ProductNotFoundException exception) { + return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND); + } + + @ExceptionHandler(HttpServerErrorException.ServiceUnavailable.class) + public ResponseEntity handleException(HttpServerErrorException.ServiceUnavailable exception) { + return new ResponseEntity<>(exception.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/exception/ProductNotFoundException.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/exception/ProductNotFoundException.java new file mode 100644 index 0000000000..9b698d5416 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/exception/ProductNotFoundException.java @@ -0,0 +1,7 @@ +package com.baeldung.opentelemetry.exception; + +public class ProductNotFoundException extends RuntimeException { + public ProductNotFoundException(String productNotFound) { + super(productNotFound); + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/model/Price.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/model/Price.java new file mode 100644 index 0000000000..dccaf978fd --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/model/Price.java @@ -0,0 +1,39 @@ +package com.baeldung.opentelemetry.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Price { + + @JsonProperty("productId") + private long productId; + + @JsonProperty("price_amount") + private double priceAmount; + + @JsonProperty("discount") + private double discount; + + public long getProductId() { + return productId; + } + + public void setProductId(long productId) { + this.productId = productId; + } + + public double getPriceAmount() { + return priceAmount; + } + + public void setPriceAmount(double priceAmount) { + this.priceAmount = priceAmount; + } + + public double getDiscount() { + return discount; + } + + public void setDiscount(double discount) { + this.discount = discount; + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/model/Product.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/model/Product.java new file mode 100644 index 0000000000..2a3a279dd8 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/model/Product.java @@ -0,0 +1,27 @@ +package com.baeldung.opentelemetry.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Product { + + @JsonProperty("id") + private long id; + + @JsonProperty("name") + private String name; + + @JsonProperty("price") + private Price price; + + public void setId(long id) { + this.id = id; + } + + public void setName(String name) { + this.name = name; + } + + public void setPrice(Price price) { + this.price = price; + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/repository/ProductRepository.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/repository/ProductRepository.java new file mode 100644 index 0000000000..07f94f626e --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/java/com/baeldung/opentelemetry/repository/ProductRepository.java @@ -0,0 +1,55 @@ +package com.baeldung.opentelemetry.repository; + +import com.baeldung.opentelemetry.exception.ProductNotFoundException; +import com.baeldung.opentelemetry.model.Product; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.HashMap; +import java.util.Map; + +@Component +public class ProductRepository { + + private static final Logger LOGGER = LoggerFactory.getLogger(ProductRepository.class); + + private final Map productMap = new HashMap<>(); + + public Product getProduct(Long productId){ + LOGGER.info("Getting Product from Product Repo With Product Id {}", productId); + + if(!productMap.containsKey(productId)){ + LOGGER.error("Product Not Found for Product Id {}", productId); + throw new ProductNotFoundException("Product Not Found"); + } + + return productMap.get(productId); + } + + @PostConstruct + private void setupRepo() { + Product product1 = getProduct(100001, "apple"); + productMap.put(100001L, product1); + + Product product2 = getProduct(100002, "pears"); + productMap.put(100002L, product2); + + Product product3 = getProduct(100003, "banana"); + productMap.put(100003L, product3); + + Product product4 = getProduct(100004, "mango"); + productMap.put(100004L, product4); + + Product product5 = getProduct(100005, "test"); + productMap.put(100005L, product5); + } + + private static Product getProduct(int id, String name) { + Product product = new Product(); + product.setId(id); + product.setName(name); + return product; + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/resources/application.properties new file mode 100644 index 0000000000..1645b6144d --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/main/resources/application.properties @@ -0,0 +1,5 @@ +server.port= 8080 +spring.application.name=product-service +priceClient.baseUrl=http://price-service:8081 +spring.sleuth.otel.config.trace-id-ratio-based=1.0 +spring.sleuth.otel.exporter.otlp.endpoint=http://collector:4317 \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/test/java/com/baeldung/opentelemetry/SpringContextTest.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/test/java/com/baeldung/opentelemetry/SpringContextTest.java new file mode 100644 index 0000000000..4f4a918cb4 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/test/java/com/baeldung/opentelemetry/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.opentelemetry; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = ProductApplication.class) +class SpringContextTest { + + @Test + void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/test/java/com/baeldung/opentelemetry/controller/ProductControllerUnitTest.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/test/java/com/baeldung/opentelemetry/controller/ProductControllerUnitTest.java new file mode 100644 index 0000000000..fcb3e23752 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry1/src/test/java/com/baeldung/opentelemetry/controller/ProductControllerUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.opentelemetry.controller; + +import com.baeldung.opentelemetry.api.client.PriceClient; +import com.baeldung.opentelemetry.exception.ProductNotFoundException; +import com.baeldung.opentelemetry.model.Price; +import com.baeldung.opentelemetry.model.Product; +import com.baeldung.opentelemetry.repository.ProductRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; + +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.client.HttpServerErrorException; + + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@ExtendWith(SpringExtension.class) +@WebMvcTest(ProductController.class) +class ProductControllerUnitTest { + + @MockBean + private PriceClient priceCLient; + + @MockBean + private ProductRepository productRepository; + + @Autowired + private MockMvc mockMvc; + + + @Test + void givenProductandPriceDataAvailable_whenGetProductCalled_thenReturnProductDetails() throws Exception { + long productId = 100000L; + + Price price = createPrice(productId); + Product product = createProduct(productId); + product.setPrice(price); + + when(productRepository.getProduct(productId)).thenReturn(product); + when(priceCLient.getPrice(productId)).thenReturn(price); + + mockMvc.perform(get("/product/" + productId)) + .andExpect(status().is(HttpStatus.OK.value())); + } + + @Test + void givenProductNotFound_whenGetProductCalled_thenReturnInternalServerError() throws Exception { + long productId = 100000L; + Price price = createPrice(productId); + + when(productRepository.getProduct(productId)).thenThrow(ProductNotFoundException.class); + when(priceCLient.getPrice(productId)).thenReturn(price); + + mockMvc.perform(get("/product/" + productId)) + .andExpect(status().is(HttpStatus.NOT_FOUND.value())); + } + + @Test + void givenPriceServiceNotAvailable_whenGetProductCalled_thenReturnInternalServerError() throws Exception { + long productId = 100000L; + Product product = createProduct(productId); + + when(productRepository.getProduct(productId)).thenReturn(product); + when(priceCLient.getPrice(productId)).thenThrow(HttpServerErrorException.ServiceUnavailable.class); + + mockMvc.perform(get("/product/" + productId)) + .andExpect(status().is(HttpStatus.INTERNAL_SERVER_ERROR.value())); + } + + private static Product createProduct(long productId) { + Product product = new Product(); + product.setId(productId); + product.setName("test"); + return product; + } + + private static Price createPrice(long productId) { + Price price = new Price(); + price.setProductId(productId); + price.setPriceAmount(12.00); + price.setDiscount(2.5); + return price; + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/Dockerfile b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/Dockerfile new file mode 100644 index 0000000000..fb0e3b3263 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/Dockerfile @@ -0,0 +1,7 @@ +FROM adoptopenjdk/openjdk11:alpine + +COPY target/spring-cloud-open-telemetry2-1.0.0-SNAPSHOT.jar spring-cloud-open-telemetry.jar + +EXPOSE 8081 + +ENTRYPOINT ["java","-jar","/spring-cloud-open-telemetry.jar"] \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/pom.xml b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/pom.xml new file mode 100644 index 0000000000..2d7ac8204e --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/pom.xml @@ -0,0 +1,115 @@ + + + 4.0.0 + spring-cloud-open-telemetry2 + com.baeldung.spring.cloud + 1.0.0-SNAPSHOT + spring-cloud-open-telemetry2 + jar + + + com.baeldung.spring.cloud + spring-cloud-open-telemetry + 1.0.0-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot-dependencies.version} + pom + import + + + org.springframework.cloud + spring-cloud-dependencies + ${release.train.version} + pom + import + + + org.springframework.cloud + spring-cloud-sleuth-otel-dependencies + ${spring-cloud-sleuth-otel.version} + import + pom + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.cloud + spring-cloud-starter-sleuth + + + org.springframework.cloud + spring-cloud-sleuth-brave + + + + + org.springframework.cloud + spring-cloud-sleuth-otel-autoconfigure + + + io.opentelemetry + opentelemetry-exporter-otlp-trace + + + io.grpc + grpc-okhttp + ${grpc-okhttp.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit-jupiter.version} + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + + + spring-milestones + https://repo.spring.io/milestone + + + + + spring-milestones + https://repo.spring.io/milestone + + + + + 2.5.7 + 2020.0.4 + 1.0.0-M12 + 1.42.1 + + + \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/PriceApplication.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/PriceApplication.java new file mode 100644 index 0000000000..75db68c624 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/PriceApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.opentelemetry; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PriceApplication { + + public static void main(String[] args) { + SpringApplication.run(PriceApplication.class, args); + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/controller/PriceController.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/controller/PriceController.java new file mode 100644 index 0000000000..6142d4da10 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/controller/PriceController.java @@ -0,0 +1,29 @@ +package com.baeldung.opentelemetry.controller; + +import com.baeldung.opentelemetry.model.Price; +import com.baeldung.opentelemetry.repository.PriceRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +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 PriceController { + + private static final Logger LOGGER = LoggerFactory.getLogger(PriceController.class); + + private final PriceRepository priceRepository; + + @Autowired + public PriceController(PriceRepository priceRepository) { + this.priceRepository = priceRepository; + } + + @GetMapping(path = "/price/{id}") + public Price getPrice(@PathVariable("id") long productId) { + LOGGER.info("Getting Price details for Product Id {}", productId); + return priceRepository.getPrice(productId); + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/exception/PriceNotFoundException.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/exception/PriceNotFoundException.java new file mode 100644 index 0000000000..6e1c5e0b5e --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/exception/PriceNotFoundException.java @@ -0,0 +1,7 @@ +package com.baeldung.opentelemetry.exception; + +public class PriceNotFoundException extends RuntimeException { + public PriceNotFoundException(String priceNotFound) { + super(priceNotFound); + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/exception/ProductControllerAdvice.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/exception/ProductControllerAdvice.java new file mode 100644 index 0000000000..fe7789ecf5 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/exception/ProductControllerAdvice.java @@ -0,0 +1,16 @@ +package com.baeldung.opentelemetry.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class ProductControllerAdvice { + + @ExceptionHandler(PriceNotFoundException.class) + public ResponseEntity handlePriceNotFoundException(PriceNotFoundException exception) { + return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND); + } + +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/model/Price.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/model/Price.java new file mode 100644 index 0000000000..0e30c4e25b --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/model/Price.java @@ -0,0 +1,27 @@ +package com.baeldung.opentelemetry.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Price { + + @JsonProperty("productId") + private long productId; + + @JsonProperty("price_amount") + private double priceAmount; + + @JsonProperty("discount") + private double discount; + + public void setDiscount(double discount) { + this.discount = discount; + } + + public void setProductId(long productId) { + this.productId = productId; + } + + public void setPriceAmount(double priceAmount) { + this.priceAmount = priceAmount; + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/repository/PriceRepository.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/repository/PriceRepository.java new file mode 100644 index 0000000000..63af7548d9 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/java/com/baeldung/opentelemetry/repository/PriceRepository.java @@ -0,0 +1,53 @@ +package com.baeldung.opentelemetry.repository; + +import com.baeldung.opentelemetry.model.Price; +import com.baeldung.opentelemetry.exception.PriceNotFoundException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.HashMap; +import java.util.Map; + +@Component +public class PriceRepository { + + private static final Logger LOGGER = LoggerFactory.getLogger(PriceRepository.class); + + private final Map priceMap = new HashMap<>(); + + public Price getPrice(Long productId){ + LOGGER.info("Getting Price from Price Repo With Product Id {}", productId); + + if(!priceMap.containsKey(productId)){ + LOGGER.error("Price Not Found for Product Id {}", productId); + throw new PriceNotFoundException("Product Not Found"); + } + + return priceMap.get(productId); + } + + @PostConstruct + private void setupRepo(){ + Price price1 = getPrice(100001L, 12.5, 2.5); + priceMap.put(100001L, price1); + + Price price2 = getPrice(100002L, 10.5, 2.1); + priceMap.put(100002L, price2); + + Price price3 = getPrice(100003L, 18.5, 2.0); + priceMap.put(100003L, price3); + + Price price4 = getPrice(100004L, 18.5, 2.0); + priceMap.put(100004L, price4); + } + + private static Price getPrice(long productId, double priceAmount, double discount) { + Price price = new Price(); + price.setProductId(productId); + price.setPriceAmount(priceAmount); + price.setDiscount(discount); + return price; + } +} \ No newline at end of file diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/resources/application.properties b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/resources/application.properties new file mode 100644 index 0000000000..03b80ae271 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.port= 8081 +spring.application.name=price-service +spring.sleuth.otel.config.trace-id-ratio-based=1.0 +spring.sleuth.otel.exporter.otlp.endpoint=http://collector:4317 diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/test/java/com/baeldung/opentelemetry/SpringContextTest.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/test/java/com/baeldung/opentelemetry/SpringContextTest.java new file mode 100644 index 0000000000..524cc30567 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/test/java/com/baeldung/opentelemetry/SpringContextTest.java @@ -0,0 +1,16 @@ +package com.baeldung.opentelemetry; + +import org.junit.jupiter.api.Test; + +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@SpringBootTest(classes = PriceApplication.class) +class SpringContextTest { + + @Test + void whenSpringContextIsBootstrapped_thenNoException() { + } +} diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/test/java/com/baeldung/opentelemetry/controller/PriceControllerUnitTest.java b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/test/java/com/baeldung/opentelemetry/controller/PriceControllerUnitTest.java new file mode 100644 index 0000000000..7fd87c99d1 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/spring-cloud-open-telemetry2/src/test/java/com/baeldung/opentelemetry/controller/PriceControllerUnitTest.java @@ -0,0 +1,57 @@ +package com.baeldung.opentelemetry.controller; + + +import com.baeldung.opentelemetry.exception.PriceNotFoundException; +import com.baeldung.opentelemetry.model.Price; +import com.baeldung.opentelemetry.repository.PriceRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.servlet.MockMvc; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@ExtendWith(SpringExtension.class) +@WebMvcTest(PriceController.class) +class PriceControllerUnitTest { + + @MockBean + private PriceRepository priceRepository; + + @Autowired + private MockMvc mockMvc; + + @Test + void givenProductandPriceAvailable_whenGetProductCalled_thenReturnProductDetails() throws Exception { + long productId = 100000L; + Price price = new Price(); + price.setProductId(productId); + price.setPriceAmount(12.00); + price.setDiscount(2.5); + + when(priceRepository.getPrice(productId)).thenReturn(price); + + mockMvc.perform(get("/price/" + productId)) + .andExpect(status().is(HttpStatus.OK.value())); + } + + + @Test + void givenProductNotFound_whenGetProductCalled_thenReturnInternalServerError() throws Exception { + long productId = 100000L; + + when(priceRepository.getPrice(productId)).thenThrow(PriceNotFoundException.class); + + mockMvc.perform(get("/price/" + productId)) + .andExpect(status().is(HttpStatus.NOT_FOUND.value())); + } + +} From 2c0c3b269e5d6993811351a9b87f6bf892c11f76 Mon Sep 17 00:00:00 2001 From: Muhammad Asif Date: Tue, 7 Feb 2023 05:23:47 +0500 Subject: [PATCH 044/113] BAEL-5990 Added JMeter-Dashboard profile to isolate (#13435) * BAEL-5990 is implemented to generate JMeter dashboard reports * BAEL-5990 made a fix to use Random nextInt() method with single arg * BAEL-5990 updated code to use Arrays.asList rather than List.of * BAEL-5990 Replaced tabs with space * BAEL-5990 Removed unnecessary exception in the method declaration * BAEL-5990 Updated class name * BAEL-5990 Added JMeterDashboard profile to exclude DashboardApplication scan in other cases --- jmeter/pom.xml | 5 +++++ .../java/com/baeldung/dashboard/DashboardApplication.java | 2 ++ 2 files changed, 7 insertions(+) diff --git a/jmeter/pom.xml b/jmeter/pom.xml index c4b15405ec..c4d09b9106 100644 --- a/jmeter/pom.xml +++ b/jmeter/pom.xml @@ -104,6 +104,11 @@ + + + JMeter-Dashboard + + com.lazerycode.jmeter diff --git a/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java b/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java index a531b97be1..6d62ad7e15 100644 --- a/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java +++ b/jmeter/src/main/java/com/baeldung/dashboard/DashboardApplication.java @@ -6,7 +6,9 @@ import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfigurat import org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration; import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; +import org.springframework.context.annotation.Profile; +@Profile("JMeter-Dashboard") @SpringBootApplication(exclude = { SecurityAutoConfiguration.class, MongoAutoConfiguration.class, MongoRepositoriesAutoConfiguration.class, MongoDataAutoConfiguration.class }) public class DashboardApplication { public static void main(String[] args) throws Exception { From d47969ce2d3a9c225bc5b751baf248b4639f6a4a Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Tue, 7 Feb 2023 14:42:21 +0000 Subject: [PATCH 045/113] =?UTF-8?q?[JAVA-18123]=20Upgraded=20algorithms-mo?= =?UTF-8?q?dules=20to=20java=2011=20+=20Upgraded=20unit=20t=E2=80=A6=20(#1?= =?UTF-8?q?3437)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [JAVA-18123] Upgraded algorithms-modules to java 11 + Upgraded unit tests to junit5 * [JAVA-18123] Clean up properties --------- Co-authored-by: panagiotiskakos --- ...ColonyOptimizationLongRunningUnitTest.java | 16 +++--- ...ryGeneticAlgorithmLongRunningUnitTest.java | 13 +++-- ...SimulatedAnnealingLongRunningUnitTest.java | 12 ++-- .../HillClimbingAlgorithmUnitTest.java | 20 ++++--- ...FiniteStateMachineLongRunningUnitTest.java | 28 ++++++---- .../kthlargest/FindKthLargestUnitTest.java | 22 ++++---- .../algorithms/minimax/MinimaxUnitTest.java | 19 ++++--- .../DijkstraAlgorithmLongRunningUnitTest.java | 6 +- .../RouteFinderIntegrationTest.java | 13 +++-- .../EditDistanceDataProvider.java | 21 ------- .../editdistance/EditDistanceUnitTest.java | 45 ++++++++------- .../CycleDetectionBruteForceUnitTest.java | 25 +++------ ...tectionByFastAndSlowIteratorsUnitTest.java | 25 +++------ .../CycleDetectionByHashingUnitTest.java | 26 ++++----- .../linkedlist/CycleDetectionTestBase.java | 2 +- .../CycleRemovalBruteForceUnitTest.java | 29 ++++------ ...cleRemovalByCountingLoopNodesUnitTest.java | 27 ++++----- ...movalWithoutCountingLoopNodesUnitTest.java | 29 ++++------ .../NumberWordConverterUnitTest.java | 34 ++++++------ .../jgrapht/CompleteGraphUnitTest.java | 12 ++-- .../jgrapht/DirectedGraphUnitTest.java | 26 +++++---- .../jgrapht/EulerianCircuitUnitTest.java | 12 ++-- .../jgrapht/GraphImageGenerationUnitTest.java | 18 +++--- .../analysis/AnalysisRunnerLiveTest.java | 20 +++---- .../SortedListCheckerUnitTest.java | 36 ++++++------ .../LeaveRequestStateUnitTest.java | 22 ++++---- .../GraphCycleDetectionUnitTest.java | 10 ++-- .../PrintTriangleExamplesUnitTest.java | 33 +++++------ .../RomanArabicConverterUnitTest.java | 9 +-- .../LinkedListFindMiddleUnitTest.java | 6 +- .../RotateArrayUnitTest.java | 8 +-- .../twopointertechnique/TwoSumUnitTest.java | 17 +++--- .../com/baeldung/counter/CounterUnitTest.java | 16 +++--- .../baeldung/folding/FoldingHashUnitTest.java | 22 ++++---- .../MiddleElementLookupUnitTest.java | 19 ++++--- .../algorithms-miscellaneous-5/pom.xml | 17 ++++++ .../conversion/HexStringConverter.java | 6 +- .../BalancedBinaryTreeUnitTest.java | 17 +++--- .../binarygap/BinaryGapUnitTest.java | 14 +++-- .../combinatorics/CombinatoricsUnitTest.java | 23 ++++---- .../ByteArrayConverterUnitTest.java | 44 ++++++++------- .../MedianOfIntegerStreamUnitTest.java | 12 ++-- .../algorithms/knapsack/KnapsackUnitTest.java | 8 +-- .../SortedArraysUnitTest.java | 6 +- .../algorithms/prim/PrimUnitTest.java | 7 ++- .../RelativelyPrimeUnitTest.java | 18 +++--- .../reversingtree/TreeReverserUnitTest.java | 6 +- .../BalancedBracketsUsingDequeUnitTest.java | 31 ++++++----- .../BalancedBracketsUsingStringUnitTest.java | 31 ++++++----- .../algorithms/boruvka/BoruvkaUnitTest.java | 10 ++-- .../GradientDescentUnitTest.java | 8 +-- .../greedy/GreedyAlgorithmUnitTest.java | 17 +++--- .../algorithms/kruskal/KruskalUnitTest.java | 20 ++++--- .../LinkedListReversalUnitTest.java | 12 ++-- .../minheapmerge/MinHeapUnitTest.java | 8 +-- .../TopKElementsFinderUnitTest.java | 16 +++--- .../algorithms/luhn/LuhnCheckerUnitTest.java | 55 ++++++++++--------- .../binarysearch/BinarySearchUnitTest.java | 24 ++++---- .../algorithms/dfs/BinaryTreeUnitTest.java | 30 +++++----- .../algorithms/dfs/GraphUnitTest.java | 8 +-- .../InterpolationSearchUnitTest.java | 13 +++-- .../kthsmallest/KthSmallestUnitTest.java | 12 ++-- .../algorithms/mcts/MCTSUnitTest.java | 25 +++++---- .../quadtree/QuadTreeSearchUnitTest.java | 25 +++++---- .../suffixtree/SuffixTreeUnitTest.java | 35 ++++++------ .../TextSearchAlgorithmsUnitTest.java | 19 ++++--- .../NaturalOrderComparatorsUnitTest.java | 18 +++--- .../gravitysort/GravitySortUnitTest.java | 11 ++-- .../inoutsort/InOutSortUnitTest.java | 15 +++-- .../BentleyMcilroyPartitioningUnitTest.java | 11 ++-- .../DNFThreeWayQuickSortUnitTest.java | 11 ++-- .../bubblesort/BubbleSortUnitTest.java | 6 +- .../IntegerBucketSorterUnitTest.java | 16 +++--- .../algorithms/heapsort/HeapUnitTest.java | 10 ++-- .../insertionsort/InsertionSortUnitTest.java | 16 +++--- .../mergesort/MergeSortUnitTest.java | 10 ++-- .../quicksort/QuickSortUnitTest.java | 12 ++-- .../quicksort/ThreeWayQuickSortUnitTest.java | 9 +-- .../radixsort/RadixSortUnitTest.java | 8 +-- .../selectionsort/SelectionSortUnitTest.java | 15 +++-- .../shellsort/ShellSortUnitTest.java | 12 ++-- pom.xml | 6 +- 82 files changed, 740 insertions(+), 721 deletions(-) delete mode 100644 algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java diff --git a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java b/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java index 2ac7adc3aa..f828d148ba 100644 --- a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java +++ b/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java @@ -1,22 +1,24 @@ package com.baeldung.algorithms; -import org.junit.Assert; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; import com.baeldung.algorithms.ga.ant_colony.AntColonyOptimization; -public class AntColonyOptimizationLongRunningUnitTest { +class AntColonyOptimizationLongRunningUnitTest { @Test - public void testGenerateRandomMatrix() { + void testGenerateRandomMatrix() { AntColonyOptimization antTSP = new AntColonyOptimization(5); - Assert.assertNotNull(antTSP.generateRandomMatrix(5)); + assertNotNull(antTSP.generateRandomMatrix(5)); } @Test - public void testStartAntOptimization() { + void testStartAntOptimization() { AntColonyOptimization antTSP = new AntColonyOptimization(5); - Assert.assertNotNull(antTSP.solve()); + assertNotNull(antTSP.solve()); } } diff --git a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java b/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java index e819da4b36..a2f869e171 100644 --- a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java +++ b/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java @@ -1,16 +1,19 @@ package com.baeldung.algorithms; -import org.junit.Assert; -import org.junit.Test; + + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; import com.baeldung.algorithms.ga.binary.SimpleGeneticAlgorithm; -public class BinaryGeneticAlgorithmLongRunningUnitTest { +class BinaryGeneticAlgorithmLongRunningUnitTest { @Test - public void testGA() { + void testGA() { SimpleGeneticAlgorithm ga = new SimpleGeneticAlgorithm(); - Assert.assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111")); + assertTrue(ga.runAlgorithm(50, "1011000100000100010000100000100111001000000100000100000000001111")); } } diff --git a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java b/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java index 2ce7d75e43..461e3e9128 100644 --- a/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java +++ b/algorithms-modules/algorithms-genetic/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java @@ -1,15 +1,17 @@ package com.baeldung.algorithms; -import org.junit.Assert; -import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; import com.baeldung.algorithms.ga.annealing.SimulatedAnnealing; -public class SimulatedAnnealingLongRunningUnitTest { +class SimulatedAnnealingLongRunningUnitTest { @Test - public void testSimulateAnnealing() { - Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0); + void testSimulateAnnealing() { + assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0); } } diff --git a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java index e817d195b3..4e8f927750 100644 --- a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java @@ -1,23 +1,25 @@ package com.baeldung.algorithms; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import com.baeldung.algorithms.hillclimbing.HillClimbing; import com.baeldung.algorithms.hillclimbing.State; -import org.junit.Before; -import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.Stack; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -public class HillClimbingAlgorithmUnitTest { +class HillClimbingAlgorithmUnitTest { private Stack initStack; private Stack goalStack; - @Before + @BeforeEach public void initStacks() { String blockArr[] = { "B", "C", "D", "A" }; String goalBlockArr[] = { "A", "B", "C", "D" }; @@ -30,7 +32,7 @@ public class HillClimbingAlgorithmUnitTest { } @Test - public void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() { + void givenInitAndGoalState_whenGetPathWithHillClimbing_thenPathFound() { HillClimbing hillClimbing = new HillClimbing(); List path; @@ -46,7 +48,7 @@ public class HillClimbingAlgorithmUnitTest { } @Test - public void givenCurrentState_whenFindNextState_thenBetterHeuristics() { + void givenCurrentState_whenFindNextState_thenBetterHeuristics() { HillClimbing hillClimbing = new HillClimbing(); List> initList = new ArrayList<>(); initList.add(initStack); diff --git a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java index fddccfcd9f..f3e896541d 100644 --- a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java @@ -1,14 +1,16 @@ package com.baeldung.algorithms; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + import com.baeldung.algorithms.automata.*; -import org.junit.Test; -import static org.junit.Assert.assertTrue; - -public final class RtFiniteStateMachineLongRunningUnitTest { +class RtFiniteStateMachineLongRunningUnitTest { @Test - public void acceptsSimplePair() { + void acceptsSimplePair() { String json = "{\"key\":\"value\"}"; FiniteStateMachine machine = this.buildJsonStateMachine(); for (int i = 0; i < json.length(); i++) { @@ -18,7 +20,7 @@ public final class RtFiniteStateMachineLongRunningUnitTest { } @Test - public void acceptsMorePairs() { + void acceptsMorePairs() { String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; FiniteStateMachine machine = this.buildJsonStateMachine(); for (int i = 0; i < json.length(); i++) { @@ -27,13 +29,15 @@ public final class RtFiniteStateMachineLongRunningUnitTest { assertTrue(machine.canStop()); } - @Test(expected = IllegalArgumentException.class) - public void missingColon() { + @Test + void missingColon() { String json = "{\"key\"\"value\"}"; - FiniteStateMachine machine = this.buildJsonStateMachine(); - for (int i = 0; i < json.length(); i++) { - machine = machine.switchState(String.valueOf(json.charAt(i))); - } + assertThrows(IllegalArgumentException.class, () -> { + FiniteStateMachine machine = this.buildJsonStateMachine(); + for (int i = 0; i < json.length(); i++) { + machine = machine.switchState(String.valueOf(json.charAt(i))); + } + }); } /** diff --git a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java index 6fbb7c163a..e877d9945a 100644 --- a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/kthlargest/FindKthLargestUnitTest.java @@ -1,54 +1,54 @@ package com.baeldung.algorithms.kthlargest; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class FindKthLargestUnitTest { +class FindKthLargestUnitTest { private FindKthLargest findKthLargest; private Integer[] arr = { 3, 7, 1, 2, 8, 10, 4, 5, 6, 9 }; - @Before + @BeforeEach public void setup() { findKthLargest = new FindKthLargest(); } @Test - public void givenIntArray_whenFindKthLargestBySorting_thenGetResult() { + void givenIntArray_whenFindKthLargestBySorting_thenGetResult() { int k = 3; assertThat(findKthLargest.findKthLargestBySorting(arr, k)).isEqualTo(8); } @Test - public void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() { + void givenIntArray_whenFindKthLargestBySortingDesc_thenGetResult() { int k = 3; assertThat(findKthLargest.findKthLargestBySortingDesc(arr, k)).isEqualTo(8); } @Test - public void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() { + void givenIntArray_whenFindKthLargestByQuickSelect_thenGetResult() { int k = 3; int kthLargest = arr.length - k; assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8); } @Test - public void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() { + void givenIntArray_whenFindKthElementByQuickSelectIterative_thenGetResult() { int k = 3; int kthLargest = arr.length - k; assertThat(findKthLargest.findKthElementByQuickSelectWithIterativePartition(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8); } @Test - public void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() { + void givenIntArray_whenFindKthSmallestByQuickSelect_thenGetResult() { int k = 3; assertThat(findKthLargest.findKthElementByQuickSelect(arr, 0, arr.length - 1, k - 1)).isEqualTo(3); } @Test - public void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() { + void givenIntArray_whenFindKthLargestByRandomizedQuickSelect_thenGetResult() { int k = 3; int kthLargest = arr.length - k; assertThat(findKthLargest.findKthElementByRandomizedQuickSelect(arr, 0, arr.length - 1, kthLargest)).isEqualTo(8); diff --git a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java index 59f0fcf053..e36e3651de 100644 --- a/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java @@ -1,23 +1,24 @@ package com.baeldung.algorithms.minimax; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.Assert.*; -import com.baeldung.algorithms.minimax.MiniMax; -import com.baeldung.algorithms.minimax.Tree; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class MinimaxUnitTest { +class MinimaxUnitTest { private Tree gameTree; private MiniMax miniMax; - @Before + @BeforeEach public void initMiniMaxUtility() { miniMax = new MiniMax(); } @Test - public void givenMiniMax_whenConstructTree_thenNotNullTree() { + void givenMiniMax_whenConstructTree_thenNotNullTree() { assertNull(gameTree); miniMax.constructTree(6); gameTree = miniMax.getTree(); @@ -25,7 +26,7 @@ public class MinimaxUnitTest { } @Test - public void givenMiniMax_whenCheckWin_thenComputeOptimal() { + void givenMiniMax_whenCheckWin_thenComputeOptimal() { miniMax.constructTree(6); boolean result = miniMax.checkWin(); assertTrue(result); diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java index bbc4d4f398..7e80d335be 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java @@ -1,6 +1,6 @@ package com.baeldung.algorithms; -import org.junit.Test; + import com.baeldung.algorithms.ga.dijkstra.Dijkstra; import com.baeldung.algorithms.ga.dijkstra.Graph; @@ -11,7 +11,9 @@ import java.util.List; import static org.junit.Assert.assertTrue; -public class DijkstraAlgorithmLongRunningUnitTest { +import org.junit.jupiter.api.Test; + +class DijkstraAlgorithmLongRunningUnitTest { @Test public void whenSPPSolved_thenCorrect() { diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/astar/underground/RouteFinderIntegrationTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/astar/underground/RouteFinderIntegrationTest.java index aba7f149da..ba492b33cf 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/astar/underground/RouteFinderIntegrationTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/astar/underground/RouteFinderIntegrationTest.java @@ -1,5 +1,6 @@ package com.baeldung.algorithms.astar.underground; + import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; @@ -10,22 +11,22 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import com.baeldung.algorithms.astar.Graph; import com.baeldung.algorithms.astar.RouteFinder; import lombok.extern.slf4j.Slf4j; -import org.junit.Before; -import org.junit.Test; - @Slf4j -public class RouteFinderIntegrationTest { +class RouteFinderIntegrationTest { private Graph underground; private RouteFinder routeFinder; - @Before + @BeforeEach public void setUp() throws Exception { Set stations = new HashSet<>(); Map> connections = new HashMap<>(); @@ -641,7 +642,7 @@ public class RouteFinderIntegrationTest { } @Test - public void findRoute() { + void findRoute() { List route = routeFinder.findRoute(underground.getNode("74"), underground.getNode("7")); assertThat(route).size().isPositive(); diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java deleted file mode 100644 index d11da61191..0000000000 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceDataProvider.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.algorithms.editdistance; - -import org.junit.runners.Parameterized.Parameters; - -import java.util.Arrays; -import java.util.Collection; - -public class EditDistanceDataProvider { - - @Parameters - public static Collection getLists() { - return Arrays.asList(new Object[][] { - { "", "", 0 }, - { "ago", "", 3 }, - { "", "do", 2 }, - { "abc", "adc", 1 }, - { "peek", "pesek", 1 }, - { "sunday", "saturday", 3 } - }); - } -} diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java index 3dd63e86ab..044c8fc268 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/editdistance/EditDistanceUnitTest.java @@ -1,32 +1,39 @@ package com.baeldung.algorithms.editdistance; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -@RunWith(Parameterized.class) -public class EditDistanceUnitTest extends EditDistanceDataProvider { +import java.util.stream.Stream; - private String x; - private String y; - private int result; - public EditDistanceUnitTest(String a, String b, int res) { - super(); - x = a; - y = b; - result = res; - } +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; - @Test - public void testEditDistance_RecursiveImplementation() { +import org.junit.jupiter.params.provider.MethodSource; + +class EditDistanceUnitTest { + + @ParameterizedTest + @MethodSource("provideArguments") + void testEditDistance_RecursiveImplementation(String x, String y, int result) { assertEquals(result, EditDistanceRecursive.calculate(x, y)); } - @Test - public void testEditDistance_givenDynamicProgrammingImplementation() { + @ParameterizedTest + @MethodSource("provideArguments") + void testEditDistance_givenDynamicProgrammingImplementation(String x, String y, int result) { assertEquals(result, EditDistanceDynamicProgramming.calculate(x, y)); } + + + static Stream provideArguments() { + return Stream.of(new Object[][] { + { "", "", 0 }, + { "ago", "", 3 }, + { "", "do", 2 }, + { "abc", "adc", 1 }, + { "peek", "pesek", 1 }, + { "sunday", "saturday", 3 } + }).map(Arguments::of); + } } diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java index 33889fbec6..a2bcb07ce3 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionBruteForceUnitTest.java @@ -1,23 +1,16 @@ package com.baeldung.algorithms.linkedlist; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.assertEquals; -@RunWith(value = Parameterized.class) -public class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase { - boolean cycleExists; - Node head; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - public CycleDetectionBruteForceUnitTest(Node head, boolean cycleExists) { - super(); - this.cycleExists = cycleExists; - this.head = head; - } +class CycleDetectionBruteForceUnitTest extends CycleDetectionTestBase { - @Test - public void givenList_detectLoop() { - Assert.assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists); + + @ParameterizedTest + @MethodSource("getLists") + void givenList_detectLoop(Node head, boolean cycleExists) { + assertEquals(cycleExists, CycleDetectionBruteForce.detectCycle(head).cycleExists); } } diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java index 1496840771..6acd8a2bef 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByFastAndSlowIteratorsUnitTest.java @@ -1,23 +1,16 @@ package com.baeldung.algorithms.linkedlist; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -@RunWith(value = Parameterized.class) -public class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase { - boolean cycleExists; - Node head; +import static org.junit.jupiter.api.Assertions.assertEquals; - public CycleDetectionByFastAndSlowIteratorsUnitTest(Node head, boolean cycleExists) { - super(); - this.cycleExists = cycleExists; - this.head = head; - } +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - @Test - public void givenList_detectLoop() { - Assert.assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); +class CycleDetectionByFastAndSlowIteratorsUnitTest extends CycleDetectionTestBase { + + @ParameterizedTest + @MethodSource("getLists") + void givenList_detectLoop(Node head, boolean cycleExists) { + assertEquals(cycleExists, CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); } } diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java index 136f55f834..905423e337 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionByHashingUnitTest.java @@ -1,23 +1,17 @@ package com.baeldung.algorithms.linkedlist; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -@RunWith(value = Parameterized.class) -public class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase { - boolean cycleExists; - Node head; +import static org.junit.jupiter.api.Assertions.assertEquals; - public CycleDetectionByHashingUnitTest(Node head, boolean cycleExists) { - super(); - this.cycleExists = cycleExists; - this.head = head; - } +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - @Test - public void givenList_detectLoop() { - Assert.assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists); + +class CycleDetectionByHashingUnitTest extends CycleDetectionTestBase { + + @ParameterizedTest + @MethodSource("getLists") + void givenList_detectLoop(Node head, boolean cycleExists) { + assertEquals(cycleExists, CycleDetectionByHashing.detectCycle(head).cycleExists); } } diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java index 1c6f56b20d..b4d0bf5459 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleDetectionTestBase.java @@ -7,7 +7,7 @@ import org.junit.runners.Parameterized.Parameters; public class CycleDetectionTestBase { - @Parameters + public static Collection getLists() { return Arrays.asList(new Object[][] { { createList(), false }, diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java index 36f08d2b76..6dc6ff9f58 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalBruteForceUnitTest.java @@ -1,24 +1,19 @@ package com.baeldung.algorithms.linkedlist; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -@RunWith(value = Parameterized.class) -public class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase { - boolean cycleExists; - Node head; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; - public CycleRemovalBruteForceUnitTest(Node head, boolean cycleExists) { - super(); - this.cycleExists = cycleExists; - this.head = head; - } +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - @Test - public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { - Assert.assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head)); - Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); + +class CycleRemovalBruteForceUnitTest extends CycleDetectionTestBase { + + @ParameterizedTest + @MethodSource("getLists") + void givenList_ifLoopExists_thenDetectAndRemoveLoop(Node head, boolean cycleExists) { + assertEquals(cycleExists, CycleRemovalBruteForce.detectAndRemoveCycle(head)); + assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); } } diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java index cc7589c53d..c82f175488 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalByCountingLoopNodesUnitTest.java @@ -1,24 +1,17 @@ package com.baeldung.algorithms.linkedlist; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; -@RunWith(value = Parameterized.class) -public class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase { - boolean cycleExists; - Node head; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - public CycleRemovalByCountingLoopNodesUnitTest(Node head, boolean cycleExists) { - super(); - this.cycleExists = cycleExists; - this.head = head; - } +class CycleRemovalByCountingLoopNodesUnitTest extends CycleDetectionTestBase { - @Test - public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { - Assert.assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head)); - Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); + @ParameterizedTest + @MethodSource("getLists") + void givenList_ifLoopExists_thenDetectAndRemoveLoop(Node head, boolean cycleExists) { + assertEquals(cycleExists, CycleRemovalByCountingLoopNodes.detectAndRemoveCycle(head)); + assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); } } diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java index 350e63dcc3..3ffb9ac639 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/linkedlist/CycleRemovalWithoutCountingLoopNodesUnitTest.java @@ -1,24 +1,19 @@ package com.baeldung.algorithms.linkedlist; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -@RunWith(value = Parameterized.class) -public class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase { - boolean cycleExists; - Node head; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; - public CycleRemovalWithoutCountingLoopNodesUnitTest(Node head, boolean cycleExists) { - super(); - this.cycleExists = cycleExists; - this.head = head; - } +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; - @Test - public void givenList_ifLoopExists_thenDetectAndRemoveLoop() { - Assert.assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head)); - Assert.assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); + +class CycleRemovalWithoutCountingLoopNodesUnitTest extends CycleDetectionTestBase { + + @ParameterizedTest + @MethodSource("getLists") + void givenList_ifLoopExists_thenDetectAndRemoveLoop(Node head, boolean cycleExists) { + assertEquals(cycleExists, CycleRemovalWithoutCountingLoopNodes.detectAndRemoveCycle(head)); + assertFalse(CycleDetectionByFastAndSlowIterators.detectCycle(head).cycleExists); } } \ No newline at end of file diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java index 26643e9c1e..1b94643e8a 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterUnitTest.java @@ -1,84 +1,84 @@ package com.baeldung.algorithms.moneywords; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.baeldung.algorithms.numberwordconverter.NumberWordConverter; -public class NumberWordConverterUnitTest { +class NumberWordConverterUnitTest { @Test - public void whenMoneyNegative_thenReturnInvalidInput() { + void whenMoneyNegative_thenReturnInvalidInput() { assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13)); } @Test - public void whenZeroDollarsGiven_thenReturnEmptyString() { + void whenZeroDollarsGiven_thenReturnEmptyString() { assertEquals("", NumberWordConverter.getMoneyIntoWords(0)); } @Test - public void whenOnlyDollarsGiven_thenReturnWords() { + void whenOnlyDollarsGiven_thenReturnWords() { assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1)); } @Test - public void whenOnlyCentsGiven_thenReturnWords() { + void whenOnlyCentsGiven_thenReturnWords() { assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6)); } @Test - public void whenAlmostAMillioDollarsGiven_thenReturnWords() { + void whenAlmostAMillioDollarsGiven_thenReturnWords() { String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars"; assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999)); } @Test - public void whenThirtyMillionDollarsGiven_thenReturnWords() { + void whenThirtyMillionDollarsGiven_thenReturnWords() { String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars"; assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978)); } @Test - public void whenTwoBillionDollarsGiven_thenReturnWords() { + void whenTwoBillionDollarsGiven_thenReturnWords() { String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars"; assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810)); } @Test - public void whenGivenDollarsAndCents_thenReturnWords() { + void whenGivenDollarsAndCents_thenReturnWords() { String expectedResult = "nine hundred twenty four dollars and sixty cents"; assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6)); } @Test - public void whenOneDollarAndNoCents_thenReturnDollarSingular() { + void whenOneDollarAndNoCents_thenReturnDollarSingular() { assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1)); } @Test - public void whenNoDollarsAndOneCent_thenReturnCentSingular() { + void whenNoDollarsAndOneCent_thenReturnCentSingular() { assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01)); } @Test - public void whenNoDollarsAndTwoCents_thenReturnCentsPlural() { + void whenNoDollarsAndTwoCents_thenReturnCentsPlural() { assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02)); } @Test - public void whenNoDollarsAndNinetyNineCents_thenReturnWords() { + void whenNoDollarsAndNinetyNineCents_thenReturnWords() { assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99)); } @Test - public void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() { + void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() { assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959)); } @Test - public void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() { + void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() { assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310")); } } diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java index 0b0d6ae822..c95f1bc6e8 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/CompleteGraphUnitTest.java @@ -1,6 +1,8 @@ package com.baeldung.jgrapht; -import static org.junit.Assert.assertEquals; + + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; @@ -9,15 +11,15 @@ import org.jgrapht.alg.HamiltonianCycle; import org.jgrapht.generate.CompleteGraphGenerator; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleWeightedGraph; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class CompleteGraphUnitTest { +class CompleteGraphUnitTest { static SimpleWeightedGraph completeGraph; static int size = 10; - @Before + @BeforeEach public void createCompleteGraph() { completeGraph = new SimpleWeightedGraph<>(DefaultEdge.class); CompleteGraphGenerator completeGenerator = new CompleteGraphGenerator(size); diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java index 3aebaf49a2..ad3433cc21 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/DirectedGraphUnitTest.java @@ -1,7 +1,9 @@ package com.baeldung.jgrapht; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; + + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; @@ -21,13 +23,13 @@ import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.DirectedSubgraph; import org.jgrapht.traverse.BreadthFirstIterator; import org.jgrapht.traverse.DepthFirstIterator; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class DirectedGraphUnitTest { +class DirectedGraphUnitTest { DirectedGraph directedGraph; - @Before + @BeforeEach public void createDirectedGraph() { directedGraph = new DefaultDirectedGraph(DefaultEdge.class); IntStream.range(1, 10).forEach(i -> { @@ -46,7 +48,7 @@ public class DirectedGraphUnitTest { } @Test - public void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() { + void givenDirectedGraph_whenGetStronglyConnectedSubgraphs_thenPathExistsBetweenStronglyconnectedVertices() { StrongConnectivityAlgorithm scAlg = new KosarajuStrongConnectivityInspector<>(directedGraph); List> stronglyConnectedSubgraphs = scAlg.stronglyConnectedSubgraphs(); List stronglyConnectedVertices = new ArrayList<>(stronglyConnectedSubgraphs.get(3).vertexSet()); @@ -60,7 +62,7 @@ public class DirectedGraphUnitTest { } @Test - public void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() { + void givenDirectedGraphWithCycle_whenCheckCycles_thenDetectCycles() { CycleDetector cycleDetector = new CycleDetector(directedGraph); assertTrue(cycleDetector.detectCycles()); Set cycleVertices = cycleDetector.findCycles(); @@ -68,26 +70,26 @@ public class DirectedGraphUnitTest { } @Test - public void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() { + void givenDirectedGraph_whenCreateInstanceDepthFirstIterator_thenGetIterator() { DepthFirstIterator depthFirstIterator = new DepthFirstIterator<>(directedGraph); assertNotNull(depthFirstIterator); } @Test - public void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() { + void givenDirectedGraph_whenCreateInstanceBreadthFirstIterator_thenGetIterator() { BreadthFirstIterator breadthFirstIterator = new BreadthFirstIterator<>(directedGraph); assertNotNull(breadthFirstIterator); } @Test - public void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() { + void givenDirectedGraph_whenGetDijkstraShortestPath_thenGetNotNullPath() { DijkstraShortestPath dijkstraShortestPath = new DijkstraShortestPath(directedGraph); List shortestPath = dijkstraShortestPath.getPath("v1", "v4").getVertexList(); assertNotNull(shortestPath); } @Test - public void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() { + void givenDirectedGraph_whenGetBellmanFordShortestPath_thenGetNotNullPath() { BellmanFordShortestPath bellmanFordShortestPath = new BellmanFordShortestPath(directedGraph); List shortestPath = bellmanFordShortestPath.getPath("v1", "v4").getVertexList(); assertNotNull(shortestPath); diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java index 8cf1b70898..e47f53da75 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/EulerianCircuitUnitTest.java @@ -1,7 +1,7 @@ package com.baeldung.jgrapht; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.stream.IntStream; @@ -9,13 +9,13 @@ import org.jgrapht.GraphPath; import org.jgrapht.alg.cycle.HierholzerEulerianCycle; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleWeightedGraph; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class EulerianCircuitUnitTest { +class EulerianCircuitUnitTest { SimpleWeightedGraph simpleGraph; - @Before + @BeforeEach public void createGraphWithEulerianCircuit() { simpleGraph = new SimpleWeightedGraph<>(DefaultEdge.class); IntStream.range(1, 6).forEach(i -> { diff --git a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java index a0d7523f48..7fb1b28cca 100644 --- a/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java @@ -1,6 +1,8 @@ package com.baeldung.jgrapht; -import static org.junit.Assert.assertTrue; + + +import static org.junit.jupiter.api.Assertions.assertTrue; import java.awt.Color; import java.awt.image.BufferedImage; @@ -12,18 +14,18 @@ import javax.imageio.ImageIO; import org.jgrapht.ext.JGraphXAdapter; import org.jgrapht.graph.DefaultDirectedGraph; import org.jgrapht.graph.DefaultEdge; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import com.mxgraph.layout.mxCircleLayout; import com.mxgraph.layout.mxIGraphLayout; import com.mxgraph.util.mxCellRenderer; -public class GraphImageGenerationUnitTest { +class GraphImageGenerationUnitTest { static DefaultDirectedGraph g; - @Before + @BeforeEach public void createGraph() throws IOException { File imgFile = new File("src/test/resources/graph1.png"); imgFile.createNewFile(); @@ -39,14 +41,14 @@ public class GraphImageGenerationUnitTest { g.addEdge(x3, x1); } - @After + @AfterEach public void cleanup() { File imgFile = new File("src/test/resources/graph1.png"); imgFile.deleteOnExit(); } @Test - public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException { + void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException { JGraphXAdapter graphAdapter = new JGraphXAdapter(g); mxIGraphLayout layout = new mxCircleLayout(graphAdapter); layout.execute(graphAdapter.getDefaultParent()); diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java index 1e9188f726..f3d9f7161a 100644 --- a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java +++ b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java @@ -1,14 +1,14 @@ package com.baeldung.algorithms.analysis; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class AnalysisRunnerLiveTest { +class AnalysisRunnerLiveTest { int n = 10; int total = 0; @Test - public void whenConstantComplexity_thenConstantRuntime() { + void whenConstantComplexity_thenConstantRuntime() { System.out.println("**** n = " + n + " ****"); System.out.println(); @@ -22,7 +22,7 @@ public class AnalysisRunnerLiveTest { } @Test - public void whenLogarithmicComplexity_thenLogarithmicRuntime() { + void whenLogarithmicComplexity_thenLogarithmicRuntime() { // Logarithmic Time System.out.println("**** Logarithmic Time ****"); for (int i = 1; i < n; i = i * 2) { @@ -34,7 +34,7 @@ public class AnalysisRunnerLiveTest { } @Test - public void whenLinearComplexity_thenLinearRuntime() { + void whenLinearComplexity_thenLinearRuntime() { // Linear Time System.out.println("**** Linear Time ****"); for (int i = 0; i < n; i++) { @@ -47,7 +47,7 @@ public class AnalysisRunnerLiveTest { } @Test - public void whenNLogNComplexity_thenNLogNRuntime() { + void whenNLogNComplexity_thenNLogNRuntime() { // N Log N Time System.out.println("**** nlogn Time ****"); total = 0; @@ -64,7 +64,7 @@ public class AnalysisRunnerLiveTest { } @Test - public void whenQuadraticComplexity_thenQuadraticRuntime() { + void whenQuadraticComplexity_thenQuadraticRuntime() { // Quadratic Time System.out.println("**** Quadratic Time ****"); total = 0; @@ -81,7 +81,7 @@ public class AnalysisRunnerLiveTest { } @Test - public void whenCubicComplexity_thenCubicRuntime() { + void whenCubicComplexity_thenCubicRuntime() { // Cubic Time System.out.println("**** Cubic Time ****"); total = 0; @@ -100,7 +100,7 @@ public class AnalysisRunnerLiveTest { } @Test - public void whenExponentialComplexity_thenExponentialRuntime() { + void whenExponentialComplexity_thenExponentialRuntime() { // Exponential Time System.out.println("**** Exponential Time ****"); total = 0; @@ -115,7 +115,7 @@ public class AnalysisRunnerLiveTest { } @Test - public void whenFactorialComplexity_thenFactorialRuntime() { + void whenFactorialComplexity_thenFactorialRuntime() { // Factorial Time System.out.println("**** Factorial Time ****"); total = 0; diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checksortedlist/SortedListCheckerUnitTest.java b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checksortedlist/SortedListCheckerUnitTest.java index 44c4388e6c..e865aa010a 100644 --- a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checksortedlist/SortedListCheckerUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checksortedlist/SortedListCheckerUnitTest.java @@ -11,10 +11,10 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class SortedListCheckerUnitTest { +class SortedListCheckerUnitTest { private List sortedListOfString; private List unsortedListOfString; @@ -23,7 +23,7 @@ public class SortedListCheckerUnitTest { private List employeesSortedByName; private List employeesNotSortedByName; - @Before + @BeforeEach public void setUp() { sortedListOfString = asList("Canada", "HK", "LA", "NJ", "NY"); unsortedListOfString = asList("LA", "HK", "NJ", "NY", "Canada"); @@ -34,72 +34,72 @@ public class SortedListCheckerUnitTest { } @Test - public void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() { + void givenSortedList_whenUsingIterativeApproach_thenReturnTrue() { assertThat(checkIfSortedUsingIterativeApproach(sortedListOfString)).isTrue(); } @Test - public void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() { + void givenSingleElementList_whenUsingIterativeApproach_thenReturnTrue() { assertThat(checkIfSortedUsingIterativeApproach(singletonList)).isTrue(); } @Test - public void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() { + void givenUnsortedList_whenUsingIterativeApproach_thenReturnFalse() { assertThat(checkIfSortedUsingIterativeApproach(unsortedListOfString)).isFalse(); } @Test - public void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() { + void givenSortedListOfEmployees_whenUsingIterativeApproach_thenReturnTrue() { assertThat(checkIfSortedUsingIterativeApproach(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue(); } @Test - public void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() { + void givenUnsortedListOfEmployees_whenUsingIterativeApproach_thenReturnFalse() { assertThat(checkIfSortedUsingIterativeApproach(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse(); } @Test - public void givenSortedList_whenUsingRecursion_thenReturnTrue() { + void givenSortedList_whenUsingRecursion_thenReturnTrue() { assertThat(checkIfSortedUsingRecursion(sortedListOfString)).isTrue(); } @Test - public void givenSingleElementList_whenUsingRecursion_thenReturnTrue() { + void givenSingleElementList_whenUsingRecursion_thenReturnTrue() { assertThat(checkIfSortedUsingRecursion(singletonList)).isTrue(); } @Test - public void givenUnsortedList_whenUsingRecursion_thenReturnFalse() { + void givenUnsortedList_whenUsingRecursion_thenReturnFalse() { assertThat(checkIfSortedUsingRecursion(unsortedListOfString)).isFalse(); } @Test - public void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() { + void givenSortedList_whenUsingGuavaOrdering_thenReturnTrue() { assertThat(checkIfSortedUsingOrderingClass(sortedListOfString)).isTrue(); } @Test - public void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() { + void givenUnsortedList_whenUsingGuavaOrdering_thenReturnFalse() { assertThat(checkIfSortedUsingOrderingClass(unsortedListOfString)).isFalse(); } @Test - public void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() { + void givenSortedListOfEmployees_whenUsingGuavaOrdering_thenReturnTrue() { assertThat(checkIfSortedUsingOrderingClass(employeesSortedByName, Comparator.comparing(Employee::getName))).isTrue(); } @Test - public void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() { + void givenUnsortedListOfEmployees_whenUsingGuavaOrdering_thenReturnFalse() { assertThat(checkIfSortedUsingOrderingClass(employeesNotSortedByName, Comparator.comparing(Employee::getName))).isFalse(); } @Test - public void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() { + void givenSortedList_whenUsingGuavaComparators_thenReturnTrue() { assertThat(checkIfSortedUsingComparators(sortedListOfString)).isTrue(); } @Test - public void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() { + void givenUnsortedList_whenUsingGuavaComparators_thenReturnFalse() { assertThat(checkIfSortedUsingComparators(unsortedListOfString)).isFalse(); } diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java index 61ed6b3aec..5b48c884e4 100644 --- a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java @@ -1,37 +1,37 @@ package com.baeldung.algorithms.enumstatemachine; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class LeaveRequestStateUnitTest { +class LeaveRequestStateUnitTest { @Test - public void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() { + void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() { LeaveRequestState state = LeaveRequestState.Escalated; - assertEquals(state.responsiblePerson(), "Team Leader"); + assertEquals( "Team Leader", state.responsiblePerson()); } @Test - public void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() { + void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() { LeaveRequestState state = LeaveRequestState.Approved; - assertEquals(state.responsiblePerson(), "Department Manager"); + assertEquals( "Department Manager" , state.responsiblePerson()); } @Test - public void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() { + void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() { LeaveRequestState state = LeaveRequestState.Submitted; state = state.nextState(); - assertEquals(state, LeaveRequestState.Escalated); + assertEquals(LeaveRequestState.Escalated, state); state = state.nextState(); - assertEquals(state, LeaveRequestState.Approved); + assertEquals(LeaveRequestState.Approved, state); state = state.nextState(); - assertEquals(state, LeaveRequestState.Approved); + assertEquals(LeaveRequestState.Approved, state); } } diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java index 8d464d7b97..c54483dbbb 100644 --- a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java @@ -1,14 +1,14 @@ package com.baeldung.algorithms.graphcycledetection; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.baeldung.algorithms.graphcycledetection.domain.Graph; import com.baeldung.algorithms.graphcycledetection.domain.Vertex; -public class GraphCycleDetectionUnitTest { +class GraphCycleDetectionUnitTest { @Test public void givenGraph_whenCycleExists_thenReturnTrue() { @@ -33,7 +33,7 @@ public class GraphCycleDetectionUnitTest { } @Test - public void givenGraph_whenNoCycleExists_thenReturnFalse() { + void givenGraph_whenNoCycleExists_thenReturnFalse() { Vertex vertexA = new Vertex("A"); Vertex vertexB = new Vertex("B"); diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamplesUnitTest.java b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamplesUnitTest.java index 97e99290c9..ad98d63388 100644 --- a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamplesUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/printtriangles/PrintTriangleExamplesUnitTest.java @@ -1,14 +1,11 @@ package com.baeldung.algorithms.printtriangles; -import junitparams.JUnitParamsRunner; -import junitparams.Parameters; -import org.junit.Test; -import org.junit.runner.RunWith; +import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(JUnitParamsRunner.class) -public class PrintTriangleExamplesUnitTest { +class PrintTriangleExamplesUnitTest { private static Object[][] rightTriangles() { String expected0 = ""; @@ -38,9 +35,9 @@ public class PrintTriangleExamplesUnitTest { }; } - @Test - @Parameters(method = "rightTriangles") - public void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { + @ParameterizedTest + @MethodSource("rightTriangles") + void whenPrintARightTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { String actual = PrintTriangleExamples.printARightTriangle(nrOfRows); assertEquals(expected, actual); @@ -74,24 +71,24 @@ public class PrintTriangleExamplesUnitTest { }; } - @Test - @Parameters(method = "isoscelesTriangles") - public void whenPrintAnIsoscelesTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { + @ParameterizedTest + @MethodSource("isoscelesTriangles") + void whenPrintAnIsoscelesTriangleIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { String actual = PrintTriangleExamples.printAnIsoscelesTriangle(nrOfRows); assertEquals(expected, actual); } - @Test - @Parameters(method = "isoscelesTriangles") + @ParameterizedTest + @MethodSource("isoscelesTriangles") public void whenPrintAnIsoscelesTriangleUsingStringUtilsIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingStringUtils(nrOfRows); assertEquals(expected, actual); } - - @Test - @Parameters(method = "isoscelesTriangles") + + @ParameterizedTest + @MethodSource("isoscelesTriangles") public void whenPrintAnIsoscelesTriangleUsingSubstringIsCalled_ThenTheCorrectStringIsReturned(int nrOfRows, String expected) { String actual = PrintTriangleExamples.printAnIsoscelesTriangleUsingSubstring(nrOfRows); diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java index 9043cfe9cc..4571a60509 100644 --- a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java @@ -1,13 +1,14 @@ package com.baeldung.algorithms.romannumerals; + import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class RomanArabicConverterUnitTest { +class RomanArabicConverterUnitTest { @Test - public void given2018Roman_WhenConvertingToArabic_ThenReturn2018() { + void given2018Roman_WhenConvertingToArabic_ThenReturn2018() { String roman2018 = "MMXVIII"; @@ -17,7 +18,7 @@ public class RomanArabicConverterUnitTest { } @Test - public void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() { + void given1999Arabic_WhenConvertingToRoman_ThenReturnMCMXCIX() { int arabic1999 = 1999; diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java index 422a53fa3e..5aaf1711b9 100644 --- a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java @@ -2,14 +2,14 @@ package com.baeldung.algorithms.twopointertechnique; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class LinkedListFindMiddleUnitTest { +class LinkedListFindMiddleUnitTest { LinkedListFindMiddle linkedListFindMiddle = new LinkedListFindMiddle(); @Test - public void givenLinkedListOfMyNodes_whenLinkedListFindMiddle_thenCorrect() { + void givenLinkedListOfMyNodes_whenLinkedListFindMiddle_thenCorrect() { MyNode head = createNodesList(8); diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java index da227ae751..defc956a68 100644 --- a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java @@ -1,10 +1,10 @@ package com.baeldung.algorithms.twopointertechnique; -import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class RotateArrayUnitTest { +class RotateArrayUnitTest { private RotateArray rotateArray = new RotateArray(); @@ -13,7 +13,7 @@ public class RotateArrayUnitTest { private int step; @Test - public void givenAnArrayOfIntegers_whenRotateKsteps_thenCorrect() { + void givenAnArrayOfIntegers_whenRotateKsteps_thenCorrect() { inputArray = new int[] { 1, 2, 3, 4, 5, 6, 7 }; step = 4; diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java index aa76f8e1cf..9b017a9d06 100644 --- a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java @@ -1,11 +1,12 @@ package com.baeldung.algorithms.twopointertechnique; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -public class TwoSumUnitTest { +class TwoSumUnitTest { private TwoSum twoSum = new TwoSum(); @@ -14,7 +15,7 @@ public class TwoSumUnitTest { private int targetValue; @Test - public void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairExists() { + void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairExists() { sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; @@ -24,7 +25,7 @@ public class TwoSumUnitTest { } @Test - public void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairDoesNotExists() { + void givenASortedArrayOfIntegers_whenTwoSumSlow_thenPairDoesNotExists() { sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; @@ -34,7 +35,7 @@ public class TwoSumUnitTest { } @Test - public void givenASortedArrayOfIntegers_whenTwoSum_thenPairExists() { + void givenASortedArrayOfIntegers_whenTwoSum_thenPairExists() { sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; @@ -44,7 +45,7 @@ public class TwoSumUnitTest { } @Test - public void givenASortedArrayOfIntegers_whenTwoSum_thenPairDoesNotExists() { + void givenASortedArrayOfIntegers_whenTwoSum_thenPairDoesNotExists() { sortedArray = new int[] { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/counter/CounterUnitTest.java b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/counter/CounterUnitTest.java index 4f914bd289..4a60bcb213 100644 --- a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/counter/CounterUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/counter/CounterUnitTest.java @@ -1,18 +1,18 @@ package com.baeldung.counter; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.*; - -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.baeldung.counter.CounterUtil.MutableInteger; -public class CounterUnitTest { +class CounterUnitTest { @Test - public void whenMapWithWrapperAsCounter_runsSuccessfully() { + void whenMapWithWrapperAsCounter_runsSuccessfully() { Map counterMap = new HashMap<>(); CounterUtil.counterWithWrapperObject(counterMap); @@ -23,7 +23,7 @@ public class CounterUnitTest { } @Test - public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() { + void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() { Map counterMap = new HashMap<>(); CounterUtil.counterWithLambdaAndWrapper(counterMap); @@ -34,7 +34,7 @@ public class CounterUnitTest { } @Test - public void whenMapWithMutableIntegerCounter_runsSuccessfully() { + void whenMapWithMutableIntegerCounter_runsSuccessfully() { Map counterMap = new HashMap<>(); CounterUtil.counterWithMutableInteger(counterMap); assertEquals(3, counterMap.get("China") @@ -44,7 +44,7 @@ public class CounterUnitTest { } @Test - public void whenMapWithPrimitiveArray_runsSuccessfully() { + void whenMapWithPrimitiveArray_runsSuccessfully() { Map counterMap = new HashMap<>(); CounterUtil.counterWithPrimitiveArray(counterMap); assertEquals(3, counterMap.get("China")[0]); diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java index 43e33d8378..4db4ebd337 100644 --- a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/folding/FoldingHashUnitTest.java @@ -1,22 +1,22 @@ package com.baeldung.folding; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class FoldingHashUnitTest { +class FoldingHashUnitTest { @Test - public void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception { + void givenStringJavaLanguage_whenSize2Capacity100000_then48933() throws Exception { final FoldingHash hasher = new FoldingHash(); final int value = hasher.hash("Java language", 2, 100_000); assertEquals(value, 48933); } @Test - public void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception { + void givenStringVaJaLanguage_whenSize2Capacity100000_thenSameAsJavaLanguage() throws Exception { final FoldingHash hasher = new FoldingHash(); final int java = hasher.hash("Java language", 2, 100_000); final int vaja = hasher.hash("vaJa language", 2, 100_000); @@ -24,28 +24,28 @@ public class FoldingHashUnitTest { } @Test - public void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception { + void givenSingleElementArray_whenOffset0Size2_thenSingleElement() throws Exception { final FoldingHash hasher = new FoldingHash(); final int[] value = hasher.extract(new int[] { 5 }, 0, 2); assertArrayEquals(new int[] { 5 }, value); } @Test - public void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception { + void givenFiveElementArray_whenOffset0Size3_thenFirstThreeElements() throws Exception { final FoldingHash hasher = new FoldingHash(); final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 0, 3); assertArrayEquals(new int[] { 1, 2, 3 }, value); } @Test - public void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception { + void givenFiveElementArray_whenOffset1Size2_thenTwoElements() throws Exception { final FoldingHash hasher = new FoldingHash(); final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 1, 2); assertArrayEquals(new int[] { 2, 3 }, value); } @Test - public void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception { + void givenFiveElementArray_whenOffset2SizeTooBig_thenElementsToTheEnd() throws Exception { final FoldingHash hasher = new FoldingHash(); final int[] value = hasher.extract(new int[] { 1, 2, 3, 4, 5 }, 2, 2000); assertArrayEquals(new int[] { 3, 4, 5 }, value); diff --git a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java b/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java index 2cda0ccb36..0759f2c020 100644 --- a/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-4/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java @@ -1,18 +1,19 @@ package com.baeldung.algorithms; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup; import com.baeldung.algorithms.middleelementlookup.Node; -import org.junit.Test; import java.util.LinkedList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import org.junit.jupiter.api.Test; -public class MiddleElementLookupUnitTest { +class MiddleElementLookupUnitTest { @Test - public void whenFindingMiddleLinkedList_thenMiddleFound() { + void whenFindingMiddleLinkedList_thenMiddleFound() { assertEquals("3", MiddleElementLookup .findMiddleElementLinkedList(createLinkedList(5)) .get()); @@ -22,7 +23,7 @@ public class MiddleElementLookupUnitTest { } @Test - public void whenFindingMiddleFromHead_thenMiddleFound() { + void whenFindingMiddleFromHead_thenMiddleFound() { assertEquals("3", MiddleElementLookup .findMiddleElementFromHead(createNodesList(5)) .get()); @@ -32,7 +33,7 @@ public class MiddleElementLookupUnitTest { } @Test - public void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() { + void whenFindingMiddleFromHead1PassRecursively_thenMiddleFound() { assertEquals("3", MiddleElementLookup .findMiddleElementFromHead1PassRecursively(createNodesList(5)) .get()); @@ -42,7 +43,7 @@ public class MiddleElementLookupUnitTest { } @Test - public void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() { + void whenFindingMiddleFromHead1PassIteratively_thenMiddleFound() { assertEquals("3", MiddleElementLookup .findMiddleElementFromHead1PassIteratively(createNodesList(5)) .get()); @@ -52,7 +53,7 @@ public class MiddleElementLookupUnitTest { } @Test - public void whenListEmptyOrNull_thenMiddleNotFound() { + void whenListEmptyOrNull_thenMiddleNotFound() { // null list assertFalse(MiddleElementLookup .findMiddleElementLinkedList(null) diff --git a/algorithms-modules/algorithms-miscellaneous-5/pom.xml b/algorithms-modules/algorithms-miscellaneous-5/pom.xml index 97c61cb88f..92b8e7d1f5 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/pom.xml +++ b/algorithms-modules/algorithms-miscellaneous-5/pom.xml @@ -34,6 +34,23 @@ guava ${guava.version} + + + jakarta.xml.bind + jakarta.xml.bind-api + ${xml-bind-api.version} + + + + org.glassfish.jaxb + jaxb-runtime + ${jaxb-runtime.version} + + + 4.0.0 + 4.0.0 + + \ No newline at end of file diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java b/algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java index d3e251d3fd..ae434d88ad 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java @@ -2,13 +2,15 @@ package com.baeldung.algorithms.conversion; import java.math.BigInteger; -import javax.xml.bind.DatatypeConverter; + import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import com.google.common.io.BaseEncoding; +import jakarta.xml.bind.DatatypeConverter; + public class HexStringConverter { /** @@ -90,7 +92,7 @@ public class HexStringConverter { return DatatypeConverter.parseHexBinary(hexString); } - public String encodeUsingApacheCommons(byte[] bytes) throws DecoderException { + public String encodeUsingApacheCommons(byte[] bytes) { return Hex.encodeHexString(bytes); } diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTreeUnitTest.java b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTreeUnitTest.java index 25f313f991..154bc80932 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTreeUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/balancedbinarytree/BalancedBinaryTreeUnitTest.java @@ -1,22 +1,23 @@ package com.baeldung.algorithms.balancedbinarytree; -import org.junit.Test; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class BalancedBinaryTreeUnitTest extends BinaryTreeDataProvider { +import org.junit.jupiter.api.Test; + +class BalancedBinaryTreeUnitTest extends BinaryTreeDataProvider { @Test - public void givenBalancedTrees_whenCallingIsBalanced_ShouldReturnTrue() { + void givenBalancedTrees_whenCallingIsBalanced_ShouldReturnTrue() { for (Tree tree : balancedTrees()) { - assertTrue(toString(tree) + " should be balanced", BalancedBinaryTree.isBalanced(tree)); + assertTrue(BalancedBinaryTree.isBalanced(tree), toString(tree) + " should be balanced"); } } @Test - public void givenUnbalancedTrees_whenCallingIsBalanced_ShouldReturnFalse() { + void givenUnbalancedTrees_whenCallingIsBalanced_ShouldReturnFalse() { for (Tree tree : unbalancedTrees()) { - assertFalse(toString(tree) + " should not be balanced", BalancedBinaryTree.isBalanced(tree)); + assertFalse(BalancedBinaryTree.isBalanced(tree), toString(tree) + " should not be balanced"); } } diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/binarygap/BinaryGapUnitTest.java b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/binarygap/BinaryGapUnitTest.java index 304d36e2bb..7404c9b5bd 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/binarygap/BinaryGapUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/binarygap/BinaryGapUnitTest.java @@ -5,27 +5,31 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -public class BinaryGapUnitTest { +class BinaryGapUnitTest { - @Test public void givenNoOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { + @Test + void givenNoOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { int result = calculateBinaryGap(63); assertEquals(0, result); } - @Test public void givenTrailingZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { + @Test + void givenTrailingZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { int result = calculateBinaryGap(40); assertEquals(1, result); } - @Test public void givenSingleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { + @Test + void givenSingleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { int result = calculateBinaryGap(9); assertEquals(2, result); } - @Test public void givenMultipleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { + @Test + void givenMultipleOccurrenceOfBoundedZeros_whenCalculateBinaryGap_thenOutputCorrectResult() { int result = calculateBinaryGap(145); assertEquals(3, result); diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/combinatorics/CombinatoricsUnitTest.java b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/combinatorics/CombinatoricsUnitTest.java index 95ffdec239..9f82c444cb 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/combinatorics/CombinatoricsUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/combinatorics/CombinatoricsUnitTest.java @@ -1,17 +1,18 @@ package com.baeldung.algorithms.combinatorics; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + import java.util.Arrays; import java.util.HashSet; import java.util.List; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import org.junit.jupiter.api.Test; -public class CombinatoricsUnitTest { +class CombinatoricsUnitTest { @Test - public void givenEmptySequence_whenCallingPermutations_ShouldReturnEmptyList() { + void givenEmptySequence_whenCallingPermutations_ShouldReturnEmptyList() { List sequence = Arrays.asList(); List> permutations = Combinatorics.permutations(sequence); @@ -20,7 +21,7 @@ public class CombinatoricsUnitTest { } @Test - public void givenOneElementSequence_whenCallingPermutations_ShouldReturnPermutations() { + void givenOneElementSequence_whenCallingPermutations_ShouldReturnPermutations() { List sequence = Arrays.asList(1); List> permutations = Combinatorics.permutations(sequence); @@ -31,7 +32,7 @@ public class CombinatoricsUnitTest { } @Test - public void givenFourElementsSequence_whenCallingPermutations_ShouldReturnPermutations() { + void givenFourElementsSequence_whenCallingPermutations_ShouldReturnPermutations() { List sequence = Arrays.asList(1, 2, 3, 4); List> permutations = Combinatorics.permutations(sequence); @@ -41,7 +42,7 @@ public class CombinatoricsUnitTest { } @Test - public void givenTwoElements_whenCalling3Combinations_ShouldReturnEmptyList() { + void givenTwoElements_whenCalling3Combinations_ShouldReturnEmptyList() { List set = Arrays.asList(1, 2); List> combinations = Combinatorics.combinations(set, 3); @@ -50,7 +51,7 @@ public class CombinatoricsUnitTest { } @Test - public void givenThreeElements_whenCalling3Combinations_ShouldReturnOneCombination() { + void givenThreeElements_whenCalling3Combinations_ShouldReturnOneCombination() { List set = Arrays.asList(1, 2, 3); List> combinations = Combinatorics.combinations(set, 3); @@ -60,7 +61,7 @@ public class CombinatoricsUnitTest { } @Test - public void givenFourElements_whenCalling2Combinations_ShouldReturnCombinations() { + void givenFourElements_whenCalling2Combinations_ShouldReturnCombinations() { List set = Arrays.asList(1, 2, 3, 4); List> combinations = Combinatorics.combinations(set, 2); @@ -70,7 +71,7 @@ public class CombinatoricsUnitTest { } @Test - public void givenFourElements_whenCallingPowerSet_ShouldReturn15Sets() { + void givenFourElements_whenCallingPowerSet_ShouldReturn15Sets() { List sequence = Arrays.asList('a', 'b', 'c', 'd'); List> combinations = Combinatorics.powerSet(sequence); diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java index be61802705..bb344e8b30 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java @@ -1,27 +1,27 @@ package com.baeldung.algorithms.conversion; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.apache.commons.codec.DecoderException; import org.hamcrest.text.IsEqualIgnoringCase; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import com.baeldung.algorithms.conversion.HexStringConverter; -public class ByteArrayConverterUnitTest { +class ByteArrayConverterUnitTest { private HexStringConverter hexStringConverter; - @Before + @BeforeEach public void setup() { hexStringConverter = new HexStringConverter(); } @Test - public void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() { + void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); if(hexString.charAt(0) == '0') { @@ -32,7 +32,7 @@ public class ByteArrayConverterUnitTest { } @Test - public void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() { + void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes); @@ -40,7 +40,7 @@ public class ByteArrayConverterUnitTest { } @Test - public void shouldDecodeHexStringToByteArrayUsingBigInteger() { + void shouldDecodeHexStringToByteArrayUsingBigInteger() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); byte[] output = hexStringConverter.decodeUsingBigInteger(hexString); @@ -48,7 +48,7 @@ public class ByteArrayConverterUnitTest { } @Test - public void shouldEncodeByteArrayToHexStringUsingCharacterConversion() { + void shouldEncodeByteArrayToHexStringUsingCharacterConversion() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); String output = hexStringConverter.encodeHexString(bytes); @@ -56,20 +56,22 @@ public class ByteArrayConverterUnitTest { } @Test - public void shouldDecodeHexStringToByteArrayUsingCharacterConversion() { + void shouldDecodeHexStringToByteArrayUsingCharacterConversion() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); byte[] output = hexStringConverter.decodeHexString(hexString); assertArrayEquals(bytes, output); } - @Test(expected=IllegalArgumentException.class) - public void shouldDecodeHexToByteWithInvalidHexCharacter() { - hexStringConverter.hexToByte("fg"); + @Test + void shouldDecodeHexToByteWithInvalidHexCharacter() { + assertThrows(IllegalArgumentException.class, () -> { + hexStringConverter.hexToByte("fg"); + }); } @Test - public void shouldEncodeByteArrayToHexStringDataTypeConverter() { + void shouldEncodeByteArrayToHexStringDataTypeConverter() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); String output = hexStringConverter.encodeUsingDataTypeConverter(bytes); @@ -77,7 +79,7 @@ public class ByteArrayConverterUnitTest { } @Test - public void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() { + void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString); @@ -85,7 +87,7 @@ public class ByteArrayConverterUnitTest { } @Test - public void shouldEncodeByteArrayToHexStringUsingGuava() { + void shouldEncodeByteArrayToHexStringUsingGuava() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); String output = hexStringConverter.encodeUsingGuava(bytes); @@ -93,7 +95,7 @@ public class ByteArrayConverterUnitTest { } @Test - public void shouldDecodeHexStringToByteArrayUsingGuava() { + void shouldDecodeHexStringToByteArrayUsingGuava() { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); byte[] output = hexStringConverter.decodeUsingGuava(hexString); @@ -101,7 +103,7 @@ public class ByteArrayConverterUnitTest { } @Test - public void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException { + void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); String output = hexStringConverter.encodeUsingApacheCommons(bytes); @@ -109,7 +111,7 @@ public class ByteArrayConverterUnitTest { } @Test - public void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException { + void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException { byte[] bytes = getSampleBytes(); String hexString = getSampleHexString(); byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString); diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStreamUnitTest.java b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStreamUnitTest.java index bcea4ebba8..b37ef5af7d 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStreamUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/integerstreammedian/MedianOfIntegerStreamUnitTest.java @@ -1,16 +1,18 @@ package com.baeldung.algorithms.integerstreammedian; -import org.junit.Test; + + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.LinkedHashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; -public class MedianOfIntegerStreamUnitTest { +class MedianOfIntegerStreamUnitTest { @Test - public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach1() { + void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach1() { MedianOfIntegerStream mis = new MedianOfIntegerStream(); for (Map.Entry e : testcaseFixture().entrySet()) { mis.add(e.getKey()); @@ -19,7 +21,7 @@ public class MedianOfIntegerStreamUnitTest { } @Test - public void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach2() { + void givenStreamOfIntegers_whenAnElementIsRead_thenMedianChangesWithApproach2() { MedianOfIntegerStream2 mis = new MedianOfIntegerStream2(); for (Map.Entry e : testcaseFixture().entrySet()) { mis.add(e.getKey()); diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/knapsack/KnapsackUnitTest.java b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/knapsack/KnapsackUnitTest.java index b168e6b1eb..f6d802f50b 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/knapsack/KnapsackUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/knapsack/KnapsackUnitTest.java @@ -4,10 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -public class KnapsackUnitTest { +class KnapsackUnitTest { @Test - public void givenWeightsandValues_whenCalculateMax_thenOutputCorrectResult() { + void givenWeightsandValues_whenCalculateMax_thenOutputCorrectResult() { final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 }; final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 }; final int n = 10; @@ -19,7 +19,7 @@ public class KnapsackUnitTest { } @Test - public void givenZeroItems_whenCalculateMax_thenOutputZero() { + void givenZeroItems_whenCalculateMax_thenOutputZero() { final int[] w = new int[] {}; final int[] v = new int[] {}; final int n = 0; @@ -31,7 +31,7 @@ public class KnapsackUnitTest { } @Test - public void givenZeroWeightLimit_whenCalculateMax_thenOutputZero() { + void givenZeroWeightLimit_whenCalculateMax_thenOutputZero() { final int[] w = new int[] { 23, 26, 20, 18, 32, 27, 29, 26, 30, 27 }; final int[] v = new int[] { 505, 352, 458, 220, 354, 414, 498, 545, 473, 543 }; final int n = 10; diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/mergesortedarrays/SortedArraysUnitTest.java b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/mergesortedarrays/SortedArraysUnitTest.java index 76eeb7b116..ca6824fd15 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/mergesortedarrays/SortedArraysUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/mergesortedarrays/SortedArraysUnitTest.java @@ -5,10 +5,10 @@ import org.junit.jupiter.api.Test; import com.baeldung.algorithms.mergesortedarrays.SortedArrays; -public class SortedArraysUnitTest { +class SortedArraysUnitTest { @Test - public void givenTwoSortedArrays_whenMerged_thenReturnMergedSortedArray() { + void givenTwoSortedArrays_whenMerged_thenReturnMergedSortedArray() { int[] foo = { 3, 7 }; int[] bar = { 4, 8, 11 }; @@ -18,7 +18,7 @@ public class SortedArraysUnitTest { } @Test - public void givenTwoSortedArraysWithDuplicates_whenMerged_thenReturnMergedSortedArray() { + void givenTwoSortedArraysWithDuplicates_whenMerged_thenReturnMergedSortedArray() { int[] foo = { 3, 3, 7 }; int[] bar = { 4, 8, 8, 11 }; diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/prim/PrimUnitTest.java b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/prim/PrimUnitTest.java index fac3b3a81f..a5eb6f4d89 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/prim/PrimUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/prim/PrimUnitTest.java @@ -1,14 +1,15 @@ package com.baeldung.algorithms.prim; -import org.junit.Test; import java.util.ArrayList; import java.util.List; -public class PrimUnitTest { +import org.junit.jupiter.api.Test; + +class PrimUnitTest { @Test - public void givenAGraph_whenPrimRuns_thenPrintMST() { + void givenAGraph_whenPrimRuns_thenPrintMST() { Prim prim = new Prim(createGraph()); System.out.println(prim.originalGraphToString()); System.out.println("----------------"); diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/relativelyprime/RelativelyPrimeUnitTest.java b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/relativelyprime/RelativelyPrimeUnitTest.java index 84bb2620af..8218649e98 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/relativelyprime/RelativelyPrimeUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/relativelyprime/RelativelyPrimeUnitTest.java @@ -1,49 +1,49 @@ package com.baeldung.algorithms.relativelyprime; -import org.junit.Test; - import static com.baeldung.algorithms.relativelyprime.RelativelyPrime.*; import static org.assertj.core.api.Assertions.assertThat; -public class RelativelyPrimeUnitTest { +import org.junit.jupiter.api.Test; + +class RelativelyPrimeUnitTest { @Test - public void givenNonRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnFalse() { + void givenNonRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnFalse() { boolean result = iterativeRelativelyPrime(45, 35); assertThat(result).isFalse(); } @Test - public void givenRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnTrue() { + void givenRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnTrue() { boolean result = iterativeRelativelyPrime(500, 501); assertThat(result).isTrue(); } @Test - public void givenNonRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnFalse() { + void givenNonRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnFalse() { boolean result = recursiveRelativelyPrime(45, 35); assertThat(result).isFalse(); } @Test - public void givenRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnTrue() { + void givenRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnTrue() { boolean result = recursiveRelativelyPrime(500, 501); assertThat(result).isTrue(); } @Test - public void givenNonRelativelyPrimeNumbers_whenCheckingUsingBigIntegers_shouldReturnFalse() { + void givenNonRelativelyPrimeNumbers_whenCheckingUsingBigIntegers_shouldReturnFalse() { boolean result = bigIntegerRelativelyPrime(45, 35); assertThat(result).isFalse(); } @Test - public void givenRelativelyPrimeNumbers_whenCheckingBigIntegers_shouldReturnTrue() { + void givenRelativelyPrimeNumbers_whenCheckingBigIntegers_shouldReturnTrue() { boolean result = bigIntegerRelativelyPrime(500, 501); assertThat(result).isTrue(); diff --git a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java index 44fac57361..2366a897c6 100644 --- a/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-5/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java @@ -4,10 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; -public class TreeReverserUnitTest { +class TreeReverserUnitTest { @Test - public void givenTreeWhenReversingRecursivelyThenReversed() { + void givenTreeWhenReversingRecursivelyThenReversed() { TreeReverser reverser = new TreeReverser(); TreeNode treeNode = createBinaryTree(); @@ -19,7 +19,7 @@ public class TreeReverserUnitTest { } @Test - public void givenTreeWhenReversingIterativelyThenReversed() { + void givenTreeWhenReversingIterativelyThenReversed() { TreeReverser reverser = new TreeReverser(); TreeNode treeNode = createBinaryTree(); diff --git a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java index 4c0a56dabc..b7a6a6470e 100644 --- a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingDequeUnitTest.java @@ -1,80 +1,81 @@ package com.baeldung.algorithms.balancedbrackets; -import org.junit.Before; -import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; -public class BalancedBracketsUsingDequeUnitTest { +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class BalancedBracketsUsingDequeUnitTest { private BalancedBracketsUsingDeque balancedBracketsUsingDeque; - @Before + @BeforeEach public void setup() { balancedBracketsUsingDeque = new BalancedBracketsUsingDeque(); } @Test - public void givenNullInput_whenCheckingForBalance_shouldReturnFalse() { + void givenNullInput_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced(null); assertThat(result).isFalse(); } @Test - public void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() { + void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingDeque.isBalanced(""); assertThat(result).isTrue(); } @Test - public void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() { + void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced("abc[](){}"); assertThat(result).isFalse(); } @Test - public void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() { + void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}"); assertThat(result).isFalse(); } @Test - public void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() { + void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced("{{[]()}}}}"); assertThat(result).isFalse(); } @Test - public void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { + void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced("{[(])}"); assertThat(result).isFalse(); } @Test - public void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { + void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced("{{}("); assertThat(result).isFalse(); } @Test - public void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { + void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingDeque.isBalanced("{[()]}"); assertThat(result).isTrue(); } @Test - public void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() { + void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingDeque.isBalanced("{{[[(())]]}}"); assertThat(result).isTrue(); } @Test - public void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() { + void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingDeque.isBalanced("{{([])}}"); assertThat(result).isTrue(); } @Test - public void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() { + void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingDeque.isBalanced("{{)[](}}"); assertThat(result).isFalse(); } diff --git a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java index bda85a75ce..71bd91c39a 100644 --- a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/balancedbrackets/BalancedBracketsUsingStringUnitTest.java @@ -1,80 +1,81 @@ package com.baeldung.algorithms.balancedbrackets; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -public class BalancedBracketsUsingStringUnitTest { +class BalancedBracketsUsingStringUnitTest { private BalancedBracketsUsingString balancedBracketsUsingString; - @Before + @BeforeEach public void setup() { balancedBracketsUsingString = new BalancedBracketsUsingString(); } @Test - public void givenNullInput_whenCheckingForBalance_shouldReturnFalse() { + void givenNullInput_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced(null); assertThat(result).isFalse(); } @Test - public void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() { + void givenEmptyString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingString.isBalanced(""); assertThat(result).isTrue(); } @Test - public void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() { + void givenInvalidCharacterString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced("abc[](){}"); assertThat(result).isFalse(); } @Test - public void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() { + void givenOddLengthString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}"); assertThat(result).isFalse(); } @Test - public void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() { + void givenEvenLengthString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced("{{[]()}}}}"); assertThat(result).isFalse(); } @Test - public void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { + void givenEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced("{[(])}"); assertThat(result).isFalse(); } @Test - public void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { + void givenAnotherEvenLengthUnbalancedString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced("{{}("); assertThat(result).isFalse(); } @Test - public void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { + void givenEvenLengthBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingString.isBalanced("{[()]}"); assertThat(result).isTrue(); } @Test - public void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() { + void givenBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingString.isBalanced("{{[[(())]]}}"); assertThat(result).isTrue(); } @Test - public void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() { + void givenAnotherBalancedString_whenCheckingForBalance_shouldReturnTrue() { boolean result = balancedBracketsUsingString.isBalanced("{{([])}}"); assertThat(result).isTrue(); } @Test - public void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() { + void givenUnBalancedString_whenCheckingForBalance_shouldReturnFalse() { boolean result = balancedBracketsUsingString.isBalanced("{{)[](}}"); assertThat(result).isFalse(); } diff --git a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java index e61e1e668d..7261dfffc6 100644 --- a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/boruvka/BoruvkaUnitTest.java @@ -2,17 +2,17 @@ package com.baeldung.algorithms.boruvka; import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import com.google.common.graph.MutableValueGraph; import com.google.common.graph.ValueGraphBuilder; -public class BoruvkaUnitTest { +class BoruvkaUnitTest { private MutableValueGraph graph; - @Before + @BeforeEach public void setup() { graph = ValueGraphBuilder.undirected() .build(); @@ -26,7 +26,7 @@ public class BoruvkaUnitTest { } @Test - public void givenInputGraph_whenBoruvkaPerformed_thenMinimumSpanningTree() { + void givenInputGraph_whenBoruvkaPerformed_thenMinimumSpanningTree() { BoruvkaMST boruvkaMST = new BoruvkaMST(graph); MutableValueGraph mst = boruvkaMST.getMST(); diff --git a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/gradientdescent/GradientDescentUnitTest.java b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/gradientdescent/GradientDescentUnitTest.java index 34d3e188f2..d7aa952037 100644 --- a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/gradientdescent/GradientDescentUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/gradientdescent/GradientDescentUnitTest.java @@ -1,15 +1,15 @@ package com.baeldung.algorithms.gradientdescent; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.function.Function; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GradientDescentUnitTest { +class GradientDescentUnitTest { @Test - public void givenFunction_whenStartingPointIsOne_thenLocalMinimumIsFound() { + void givenFunction_whenStartingPointIsOne_thenLocalMinimumIsFound() { Function df = x -> StrictMath.abs(StrictMath.pow(x, 3)) - (3 * StrictMath.pow(x, 2)) + x; GradientDescent gd = new GradientDescent(); diff --git a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java index a503b006de..ea90ea14c1 100644 --- a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/greedy/GreedyAlgorithmUnitTest.java @@ -1,13 +1,14 @@ package com.baeldung.algorithms.greedy; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import org.junit.jupiter.api.Test; import java.util.Arrays; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -public class GreedyAlgorithmUnitTest { + +class GreedyAlgorithmUnitTest { private SocialConnector prepareNetwork() { SocialConnector sc = new SocialConnector(); @@ -35,21 +36,21 @@ public class GreedyAlgorithmUnitTest { } @Test - public void greedyAlgorithmTest() { + void greedyAlgorithmTest() { GreedyAlgorithm ga = new GreedyAlgorithm(prepareNetwork()); assertEquals(ga.findMostFollowersPath("root"), 5); } @Test - public void nongreedyAlgorithmTest() { + void nongreedyAlgorithmTest() { NonGreedyAlgorithm nga = new NonGreedyAlgorithm(prepareNetwork(), 0); - Assertions.assertThrows(IllegalStateException.class, () -> { + assertThrows(IllegalStateException.class, () -> { nga.findMostFollowersPath("root"); }); } @Test - public void nongreedyAlgorithmUnboundedTest() { + void nongreedyAlgorithmUnboundedTest() { SocialConnector sc = prepareNetwork(); sc.switchCounter(); NonGreedyAlgorithm nga = new NonGreedyAlgorithm(sc, 0); diff --git a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/kruskal/KruskalUnitTest.java b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/kruskal/KruskalUnitTest.java index a7206c6cd0..9367942dc6 100644 --- a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/kruskal/KruskalUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/kruskal/KruskalUnitTest.java @@ -1,21 +1,23 @@ package com.baeldung.algorithms.kruskal; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; -import org.junit.Before; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + import com.google.common.graph.MutableValueGraph; import com.google.common.graph.ValueGraph; import com.google.common.graph.ValueGraphBuilder; import com.baeldung.algorithms.kruskal.Kruskal; -public class KruskalUnitTest { +class KruskalUnitTest { private MutableValueGraph graph; - @Before + @BeforeEach public void setup() { graph = ValueGraphBuilder.undirected().build(); graph.putEdgeValue(0, 1, 8.0); @@ -28,7 +30,7 @@ public class KruskalUnitTest { } @Test - public void givenGraph_whenMinimumSpanningTree_thenOutputCorrectResult() { + void givenGraph_whenMinimumSpanningTree_thenOutputCorrectResult() { final Kruskal kruskal = new Kruskal(); ValueGraph spanningTree = kruskal.minSpanningTree(graph); @@ -47,7 +49,7 @@ public class KruskalUnitTest { } @Test - public void givenGraph_whenMaximumSpanningTree_thenOutputCorrectResult() { + void givenGraph_whenMaximumSpanningTree_thenOutputCorrectResult() { final Kruskal kruskal = new Kruskal(); ValueGraph spanningTree = kruskal.maxSpanningTree(graph); diff --git a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/linkedlist/LinkedListReversalUnitTest.java b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/linkedlist/LinkedListReversalUnitTest.java index 0940677959..0d222c0841 100644 --- a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/linkedlist/LinkedListReversalUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/linkedlist/LinkedListReversalUnitTest.java @@ -1,13 +1,13 @@ package com.baeldung.algorithms.linkedlist; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import org.junit.jupiter.api.Test; -public class LinkedListReversalUnitTest { +class LinkedListReversalUnitTest { @Test - public void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() { + void givenLinkedList_whenIterativeReverse_thenOutputCorrectResult() { ListNode head = constructLinkedList(); ListNode node = head; for (int i = 1; i <= 5; i++) { @@ -25,7 +25,7 @@ public class LinkedListReversalUnitTest { } @Test - public void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() { + void givenLinkedList_whenRecursiveReverse_thenOutputCorrectResult() { ListNode head = constructLinkedList(); ListNode node = head; for (int i = 1; i <= 5; i++) { diff --git a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java index f84c860dcc..c5b78bbf48 100644 --- a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/minheapmerge/MinHeapUnitTest.java @@ -2,17 +2,17 @@ package com.baeldung.algorithms.minheapmerge; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class MinHeapUnitTest { +class MinHeapUnitTest { private final int[][] inputArray = { { 0, 6 }, { 1, 5, 10, 100 }, { 2, 4, 200, 650 } }; private final int[] expectedArray = { 0, 1, 2, 4, 5, 6, 10, 100, 200, 650 }; @Test - public void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() { + void givenSortedArrays_whenMerged_thenShouldReturnASingleSortedarray() { int[] resultArray = MinHeap.merge(inputArray); assertThat(resultArray.length, is(equalTo(10))); diff --git a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java index 41fa5e067e..d979d1c856 100644 --- a/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-6/src/test/java/com/baeldung/algorithms/topkelements/TopKElementsFinderUnitTest.java @@ -1,13 +1,13 @@ package com.baeldung.algorithms.topkelements; -import org.junit.Test; - import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Java6Assertions.assertThat; -public class TopKElementsFinderUnitTest { +import org.junit.jupiter.api.Test; + +class TopKElementsFinderUnitTest { private final TopKElementsFinder bruteForceFinder = new BruteForceTopKElementsFinder(); private final TopKElementsFinder maxHeapFinder = new MaxHeapTopKElementsFinder(); private final TopKElementsFinder treeSetFinder = new TreeSetTopKElementsFinder(); @@ -20,27 +20,27 @@ public class TopKElementsFinderUnitTest { @Test - public void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() { + void givenArrayDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() { assertThat(bruteForceFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK); } @Test - public void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() { + void givenArrayDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() { assertThat(maxHeapFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK); } @Test - public void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() { + void givenArrayDistinctIntegers_whenTreeSetFindTopK_thenReturnKLargest() { assertThat(treeSetFinder.findTopK(distinctIntegers, k)).containsOnlyElementsOf(distinctIntegersTopK); } @Test - public void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() { + void givenArrayNonDistinctIntegers_whenBruteForceFindTopK_thenReturnKLargest() { assertThat(bruteForceFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK); } @Test - public void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() { + void givenArrayNonDistinctIntegers_whenMaxHeapFindTopK_thenReturnKLargest() { assertThat(maxHeapFinder.findTopK(nonDistinctIntegers, k)).containsOnlyElementsOf(nonDistinctIntegersTopK); } } diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/luhn/LuhnCheckerUnitTest.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/luhn/LuhnCheckerUnitTest.java index dd1b184b81..9f7c93c1b3 100644 --- a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/luhn/LuhnCheckerUnitTest.java +++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/luhn/LuhnCheckerUnitTest.java @@ -1,63 +1,66 @@ package com.baeldung.algorithms.luhn; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class LuhnCheckerUnitTest { +import org.junit.jupiter.api.Test; + +class LuhnCheckerUnitTest { @Test - public void whenCardNumberDoesMeetLuhnCriteria_thenCheckLuhnReturnsTrue() { + void whenCardNumberDoesMeetLuhnCriteria_thenCheckLuhnReturnsTrue() { String cardNumber = "8649"; boolean result = LuhnChecker.checkLuhn(cardNumber); - Assert.assertTrue(result); + assertTrue(result); } @Test - public void whenCardNumberDoesNotMeetLuhnCriteria_thenCheckLuhnReturnsFalse() { + void whenCardNumberDoesNotMeetLuhnCriteria_thenCheckLuhnReturnsFalse() { String cardNumber = "8642"; boolean result = LuhnChecker.checkLuhn(cardNumber); - Assert.assertFalse(result); + assertFalse(result); } @Test - public void whenCardNumberHasNoSecondDigits_thenCheckLuhnCalculatesCorrectly() { + void whenCardNumberHasNoSecondDigits_thenCheckLuhnCalculatesCorrectly() { String cardNumber = "0505050505050505"; boolean result = LuhnChecker.checkLuhn(cardNumber); - Assert.assertTrue(result); + assertTrue(result); } @Test - public void whenCardNumberHasSecondDigits_thenCheckLuhnCalculatesCorrectly() { + void whenCardNumberHasSecondDigits_thenCheckLuhnCalculatesCorrectly() { String cardNumber = "75757575757575"; boolean result = LuhnChecker.checkLuhn(cardNumber); - Assert.assertTrue(result); + assertTrue(result); } @Test - public void whenDoubleAndSumDigitsIsCalled_thenOutputIsCorrect() { - Assert.assertEquals(LuhnChecker.doubleAndSumDigits(0), 0); - Assert.assertEquals(LuhnChecker.doubleAndSumDigits(1), 2); - Assert.assertEquals(LuhnChecker.doubleAndSumDigits(2), 4); - Assert.assertEquals(LuhnChecker.doubleAndSumDigits(3), 6); - Assert.assertEquals(LuhnChecker.doubleAndSumDigits(4), 8); - Assert.assertEquals(LuhnChecker.doubleAndSumDigits(5), 1); - Assert.assertEquals(LuhnChecker.doubleAndSumDigits(6), 3); - Assert.assertEquals(LuhnChecker.doubleAndSumDigits(7), 5); - Assert.assertEquals(LuhnChecker.doubleAndSumDigits(8), 7); - Assert.assertEquals(LuhnChecker.doubleAndSumDigits(9), 9); + void whenDoubleAndSumDigitsIsCalled_thenOutputIsCorrect() { + assertEquals(0,LuhnChecker.doubleAndSumDigits(0)); + assertEquals(2,LuhnChecker.doubleAndSumDigits(1)); + assertEquals(4, LuhnChecker.doubleAndSumDigits(2)); + assertEquals(6, LuhnChecker.doubleAndSumDigits(3)); + assertEquals(8, LuhnChecker.doubleAndSumDigits(4)); + assertEquals(1, LuhnChecker.doubleAndSumDigits(5)); + assertEquals(3, LuhnChecker.doubleAndSumDigits(6)); + assertEquals(5, LuhnChecker.doubleAndSumDigits(7)); + assertEquals(7, LuhnChecker.doubleAndSumDigits(8)); + assertEquals(9, LuhnChecker.doubleAndSumDigits(9)); } @Test - public void whenCardNumberNonNumeric_thenCheckLuhnReturnsFalse() { + void whenCardNumberNonNumeric_thenCheckLuhnReturnsFalse() { String cardNumber = "test"; boolean result = LuhnChecker.checkLuhn(cardNumber); - Assert.assertFalse(result); + assertFalse(result); } @Test - public void whenCardNumberIsNull_thenCheckLuhnReturnsFalse() { + void whenCardNumberIsNull_thenCheckLuhnReturnsFalse() { String cardNumber = null; boolean result = LuhnChecker.checkLuhn(cardNumber); - Assert.assertFalse(result); + assertFalse(result); } } diff --git a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java index eb3fb4f718..8a4dbb2141 100644 --- a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java +++ b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java @@ -1,11 +1,13 @@ package com.baeldung.algorithms.binarysearch; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.Arrays; import java.util.List; -import org.junit.Assert; -import org.junit.Test; -public class BinarySearchUnitTest { +import org.junit.jupiter.api.Test; + +class BinarySearchUnitTest { int[] sortedArray = { 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9 }; int key = 6; @@ -15,27 +17,27 @@ public class BinarySearchUnitTest { List sortedList = Arrays.asList(0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9); @Test - public void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() { + void givenASortedArrayOfIntegers_whenBinarySearchRunIterativelyForANumber_thenGetIndexOfTheNumber() { BinarySearch binSearch = new BinarySearch(); - Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high)); + assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchIteratively(sortedArray, key, low, high)); } @Test - public void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() { + void givenASortedArrayOfIntegers_whenBinarySearchRunRecursivelyForANumber_thenGetIndexOfTheNumber() { BinarySearch binSearch = new BinarySearch(); - Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high)); + assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchRecursively(sortedArray, key, low, high)); } @Test - public void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() { + void givenASortedArrayOfIntegers_whenBinarySearchRunUsingArraysClassStaticMethodForANumber_thenGetIndexOfTheNumber() { BinarySearch binSearch = new BinarySearch(); - Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key)); + assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaArrays(sortedArray, key)); } @Test - public void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() { + void givenASortedListOfIntegers_whenBinarySearchRunUsingCollectionsClassStaticMethodForANumber_thenGetIndexOfTheNumber() { BinarySearch binSearch = new BinarySearch(); - Assert.assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key)); + assertEquals(expectedIndexForSearchKey, binSearch.runBinarySearchUsingJavaCollections(sortedList, key)); } } diff --git a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/BinaryTreeUnitTest.java b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/BinaryTreeUnitTest.java index f98b4377ed..dc83d8eac8 100644 --- a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/BinaryTreeUnitTest.java +++ b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/BinaryTreeUnitTest.java @@ -1,15 +1,15 @@ package com.baeldung.algorithms.dfs; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import org.junit.jupiter.api.Test; -public class BinaryTreeUnitTest { +class BinaryTreeUnitTest { @Test - public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() { + void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() { BinaryTree bt = createBinaryTree(); @@ -17,7 +17,7 @@ public class BinaryTreeUnitTest { } @Test - public void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() { + void givenABinaryTree_WhenAddingElements_ThenTreeContainsThoseElements() { BinaryTree bt = createBinaryTree(); @@ -28,7 +28,7 @@ public class BinaryTreeUnitTest { } @Test - public void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() { + void givenABinaryTree_WhenAddingExistingElement_ThenElementIsNotAdded() { BinaryTree bt = createBinaryTree(); @@ -40,7 +40,7 @@ public class BinaryTreeUnitTest { } @Test - public void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() { + void givenABinaryTree_WhenLookingForNonExistingElement_ThenReturnsFalse() { BinaryTree bt = createBinaryTree(); @@ -48,7 +48,7 @@ public class BinaryTreeUnitTest { } @Test - public void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() { + void givenABinaryTree_WhenDeletingElements_ThenTreeDoesNotContainThoseElements() { BinaryTree bt = createBinaryTree(); @@ -58,7 +58,7 @@ public class BinaryTreeUnitTest { } @Test - public void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() { + void givenABinaryTree_WhenDeletingNonExistingElement_ThenTreeDoesNotDelete() { BinaryTree bt = createBinaryTree(); @@ -71,7 +71,7 @@ public class BinaryTreeUnitTest { } @Test - public void it_deletes_the_root() { + void it_deletes_the_root() { int value = 12; BinaryTree bt = new BinaryTree(); bt.add(value); @@ -82,7 +82,7 @@ public class BinaryTreeUnitTest { } @Test - public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() { + void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); @@ -92,7 +92,7 @@ public class BinaryTreeUnitTest { } @Test - public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() { + void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); @@ -102,7 +102,7 @@ public class BinaryTreeUnitTest { } @Test - public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() { + void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() { BinaryTree bt = createBinaryTree(); diff --git a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/GraphUnitTest.java b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/GraphUnitTest.java index 7af25a85ca..086eb77a82 100644 --- a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/GraphUnitTest.java +++ b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/dfs/GraphUnitTest.java @@ -2,12 +2,12 @@ package com.baeldung.algorithms.dfs; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GraphUnitTest { +class GraphUnitTest { @Test - public void givenDirectedGraph_whenDFS_thenPrintAllValues() { + void givenDirectedGraph_whenDFS_thenPrintAllValues() { Graph graph = createDirectedGraph(); graph.dfs(0); System.out.println(); @@ -15,7 +15,7 @@ public class GraphUnitTest { } @Test - public void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() { + void givenDirectedGraph_whenGetTopologicalSort_thenPrintValuesSorted() { Graph graph = createDirectedGraph(); List list = graph.topologicalSort(0); System.out.println(list); diff --git a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/interpolationsearch/InterpolationSearchUnitTest.java b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/interpolationsearch/InterpolationSearchUnitTest.java index cabedcefad..c9e95b0cc9 100644 --- a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/interpolationsearch/InterpolationSearchUnitTest.java +++ b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/interpolationsearch/InterpolationSearchUnitTest.java @@ -1,27 +1,28 @@ package com.baeldung.algorithms.interpolationsearch; -import org.junit.Before; -import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertEquals; -public class InterpolationSearchUnitTest { +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class InterpolationSearchUnitTest { private int[] myData; - @Before + @BeforeEach public void setUp() { myData = new int[]{13,21,34,55,69,73,84,101}; } @Test - public void givenSortedArray_whenLookingFor84_thenReturn6() { + void givenSortedArray_whenLookingFor84_thenReturn6() { int pos = InterpolationSearch.interpolationSearch(myData, 84); assertEquals(6, pos); } @Test - public void givenSortedArray_whenLookingFor19_thenReturnMinusOne() { + void givenSortedArray_whenLookingFor19_thenReturnMinusOne() { int pos = InterpolationSearch.interpolationSearch(myData, 19); assertEquals(-1, pos); } diff --git a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/kthsmallest/KthSmallestUnitTest.java b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/kthsmallest/KthSmallestUnitTest.java index 740e89d8e7..1349be59c0 100644 --- a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/kthsmallest/KthSmallestUnitTest.java +++ b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/kthsmallest/KthSmallestUnitTest.java @@ -9,13 +9,13 @@ import java.util.*; import static com.baeldung.algorithms.kthsmallest.KthSmallest.*; import static org.junit.jupiter.api.Assertions.*; -public class KthSmallestUnitTest { +class KthSmallestUnitTest { @Nested class Exceptions { @Test - public void when_at_least_one_list_is_null_then_an_exception_is_thrown() { + void when_at_least_one_list_is_null_then_an_exception_is_thrown() { Executable executable1 = () -> findKthSmallestElement(1, null, null); Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, null); @@ -27,7 +27,7 @@ public class KthSmallestUnitTest { } @Test - public void when_at_least_one_list_is_empty_then_an_exception_is_thrown() { + void when_at_least_one_list_is_empty_then_an_exception_is_thrown() { Executable executable1 = () -> findKthSmallestElement(1, new int[]{}, new int[]{2}); Executable executable2 = () -> findKthSmallestElement(1, new int[]{2}, new int[]{}); @@ -39,19 +39,19 @@ public class KthSmallestUnitTest { } @Test - public void when_k_is_smaller_than_0_then_an_exception_is_thrown() { + void when_k_is_smaller_than_0_then_an_exception_is_thrown() { Executable executable1 = () -> findKthSmallestElement(-1, new int[]{2}, new int[]{2}); assertThrows(IllegalArgumentException.class, executable1); } @Test - public void when_k_is_smaller_than_1_then_an_exception_is_thrown() { + void when_k_is_smaller_than_1_then_an_exception_is_thrown() { Executable executable1 = () -> findKthSmallestElement(0, new int[]{2}, new int[]{2}); assertThrows(IllegalArgumentException.class, executable1); } @Test - public void when_k_bigger_then_the_two_lists_then_an_exception_is_thrown() { + void when_k_bigger_then_the_two_lists_then_an_exception_is_thrown() { Executable executable1 = () -> findKthSmallestElement(6, new int[]{1, 5, 6}, new int[]{2, 5}); assertThrows(NoSuchElementException.class, executable1); } diff --git a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java index 59afed65de..3770ca4ddd 100644 --- a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java +++ b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java @@ -1,12 +1,13 @@ package com.baeldung.algorithms.mcts; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch; import com.baeldung.algorithms.mcts.montecarlo.State; @@ -15,31 +16,31 @@ import com.baeldung.algorithms.mcts.tictactoe.Board; import com.baeldung.algorithms.mcts.tictactoe.Position; import com.baeldung.algorithms.mcts.tree.Tree; -public class MCTSUnitTest { +class MCTSUnitTest { private Tree gameTree; private MonteCarloTreeSearch mcts; - @Before + @BeforeEach public void initGameTree() { gameTree = new Tree(); mcts = new MonteCarloTreeSearch(); } @Test - public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() { + void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() { double uctValue = 15.79; assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01); } @Test - public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() { + void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() { State initState = gameTree.getRoot().getState(); List possibleStates = initState.getAllPossibleStates(); assertTrue(possibleStates.size() > 0); } @Test - public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() { + void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() { Board board = new Board(); int initAvailablePositions = board.getEmptyPositions().size(); board.performMove(Board.P1, new Position(1, 1)); @@ -48,7 +49,7 @@ public class MCTSUnitTest { } @Test - public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() { + void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() { Board board = new Board(); int player = Board.P1; @@ -61,11 +62,11 @@ public class MCTSUnitTest { player = 3 - player; } int winStatus = board.checkStatus(); - assertEquals(winStatus, Board.DRAW); + assertEquals(Board.DRAW, winStatus); } @Test - public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() { + void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() { Board board = new Board(); MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch(); mcts1.setLevel(1); diff --git a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/quadtree/QuadTreeSearchUnitTest.java b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/quadtree/QuadTreeSearchUnitTest.java index 4389795ffb..6bb8ad3e09 100644 --- a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/quadtree/QuadTreeSearchUnitTest.java +++ b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/quadtree/QuadTreeSearchUnitTest.java @@ -1,21 +1,22 @@ package com.baeldung.algorithms.quadtree; -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.List; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class QuadTreeSearchUnitTest { +class QuadTreeSearchUnitTest { private static final Logger LOGGER = LoggerFactory.getLogger(QuadTreeSearchUnitTest.class); private static QuadTree quadTree; - @BeforeClass + @BeforeAll public static void setUp() { Region area = new Region(0, 0, 400, 400); quadTree = new QuadTree(area); @@ -32,30 +33,30 @@ public class QuadTreeSearchUnitTest { } @Test - public void givenQuadTree_whenSearchingForRange_thenReturn1MatchingItem() { + void givenQuadTree_whenSearchingForRange_thenReturn1MatchingItem() { Region searchArea = new Region(200, 200, 250, 250); List result = quadTree.search(searchArea, null, ""); LOGGER.debug(result.toString()); LOGGER.debug(quadTree.printSearchTraversePath()); - Assert.assertEquals(1, result.size()); - Assert.assertArrayEquals(new float[] { 245, 238 }, + assertEquals(1, result.size()); + assertArrayEquals(new float[] { 245, 238 }, new float[]{result.get(0).getX(), result.get(0).getY() }, 0); } @Test - public void givenQuadTree_whenSearchingForRange_thenReturn2MatchingItems() { + void givenQuadTree_whenSearchingForRange_thenReturn2MatchingItems() { Region searchArea = new Region(0, 0, 100, 100); List result = quadTree.search(searchArea, null, ""); LOGGER.debug(result.toString()); LOGGER.debug(quadTree.printSearchTraversePath()); - Assert.assertEquals(2, result.size()); - Assert.assertArrayEquals(new float[] { 21, 25 }, + assertEquals(2, result.size()); + assertArrayEquals(new float[] { 21, 25 }, new float[]{result.get(0).getX(), result.get(0).getY() }, 0); - Assert.assertArrayEquals(new float[] { 55, 53 }, + assertArrayEquals(new float[] { 55, 53 }, new float[]{result.get(1).getX(), result.get(1).getY() }, 0); } diff --git a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/suffixtree/SuffixTreeUnitTest.java b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/suffixtree/SuffixTreeUnitTest.java index d9a4f2962c..7ae9a6fcc4 100644 --- a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/suffixtree/SuffixTreeUnitTest.java +++ b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/suffixtree/SuffixTreeUnitTest.java @@ -1,71 +1,72 @@ package com.baeldung.algorithms.suffixtree; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + import java.util.List; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class SuffixTreeUnitTest { +class SuffixTreeUnitTest { private static final Logger LOGGER = LoggerFactory.getLogger(SuffixTreeUnitTest.class); private static SuffixTree suffixTree; - @BeforeClass + @BeforeAll public static void setUp() { suffixTree = new SuffixTree("havanabanana"); printTree(); } @Test - public void givenSuffixTree_whenSearchingForA_thenReturn6Matches() { + void givenSuffixTree_whenSearchingForA_thenReturn6Matches() { List matches = suffixTree.searchText("a"); matches.stream() .forEach(m -> LOGGER.debug(m)); - Assert.assertArrayEquals(new String[] { "h[a]vanabanana", "hav[a]nabanana", "havan[a]banana", "havanab[a]nana", "havanaban[a]na", "havanabanan[a]" }, matches.toArray()); + assertArrayEquals(new String[] { "h[a]vanabanana", "hav[a]nabanana", "havan[a]banana", "havanab[a]nana", "havanaban[a]na", "havanabanan[a]" }, matches.toArray()); } @Test - public void givenSuffixTree_whenSearchingForNab_thenReturn1Match() { + void givenSuffixTree_whenSearchingForNab_thenReturn1Match() { List matches = suffixTree.searchText("nab"); matches.stream() .forEach(m -> LOGGER.debug(m)); - Assert.assertArrayEquals(new String[] { "hava[nab]anana" }, matches.toArray()); + assertArrayEquals(new String[] { "hava[nab]anana" }, matches.toArray()); } @Test - public void givenSuffixTree_whenSearchingForNag_thenReturnNoMatches() { + void givenSuffixTree_whenSearchingForNag_thenReturnNoMatches() { List matches = suffixTree.searchText("nag"); matches.stream() .forEach(m -> LOGGER.debug(m)); - Assert.assertArrayEquals(new String[] {}, matches.toArray()); + assertArrayEquals(new String[] {}, matches.toArray()); } @Test - public void givenSuffixTree_whenSearchingForBanana_thenReturn2Matches() { + void givenSuffixTree_whenSearchingForBanana_thenReturn2Matches() { List matches = suffixTree.searchText("ana"); matches.stream() .forEach(m -> LOGGER.debug(m)); - Assert.assertArrayEquals(new String[] { "hav[ana]banana", "havanab[ana]na", "havanaban[ana]" }, matches.toArray()); + assertArrayEquals(new String[] { "hav[ana]banana", "havanab[ana]na", "havanaban[ana]" }, matches.toArray()); } @Test - public void givenSuffixTree_whenSearchingForNa_thenReturn4Matches() { + void givenSuffixTree_whenSearchingForNa_thenReturn4Matches() { List matches = suffixTree.searchText("na"); matches.stream() .forEach(m -> LOGGER.debug(m)); - Assert.assertArrayEquals(new String[] { "hava[na]banana", "havanaba[na]na", "havanabana[na]" }, matches.toArray()); + assertArrayEquals(new String[] { "hava[na]banana", "havanaba[na]na", "havanabana[na]" }, matches.toArray()); } @Test - public void givenSuffixTree_whenSearchingForX_thenReturnNoMatches() { + void givenSuffixTree_whenSearchingForX_thenReturnNoMatches() { List matches = suffixTree.searchText("x"); matches.stream() .forEach(m -> LOGGER.debug(m)); - Assert.assertArrayEquals(new String[] {}, matches.toArray()); + assertArrayEquals(new String[] {}, matches.toArray()); } private static void printTree() { diff --git a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/textsearch/TextSearchAlgorithmsUnitTest.java b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/textsearch/TextSearchAlgorithmsUnitTest.java index 543ccb912f..a1a5e9cbbe 100644 --- a/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/textsearch/TextSearchAlgorithmsUnitTest.java +++ b/algorithms-modules/algorithms-searching/src/test/java/com/baeldung/algorithms/textsearch/TextSearchAlgorithmsUnitTest.java @@ -1,23 +1,24 @@ package com.baeldung.algorithms.textsearch; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class TextSearchAlgorithmsUnitTest { +class TextSearchAlgorithmsUnitTest { @Test - public void testStringSearchAlgorithms() { + void testStringSearchAlgorithms() { String text = "This is some nice text."; String pattern = "some"; int realPosition = text.indexOf(pattern); - Assert.assertTrue(realPosition == TextSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray())); - Assert.assertTrue(realPosition == TextSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray())); - Assert.assertTrue(realPosition == TextSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray())); - Assert.assertTrue(realPosition == TextSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray())); - Assert.assertTrue(realPosition == TextSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray())); + assertEquals(TextSearchAlgorithms.simpleTextSearch(pattern.toCharArray(), text.toCharArray()), realPosition); + assertEquals(TextSearchAlgorithms.RabinKarpMethod(pattern.toCharArray(), text.toCharArray()), realPosition); + assertEquals(TextSearchAlgorithms.KnuthMorrisPrattSearch(pattern.toCharArray(), text.toCharArray()) , realPosition); + assertEquals(TextSearchAlgorithms.BoyerMooreHorspoolSimpleSearch(pattern.toCharArray(), text.toCharArray()), realPosition); + assertEquals(TextSearchAlgorithms.BoyerMooreHorspoolSearch(pattern.toCharArray(), text.toCharArray()), realPosition); } } diff --git a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java b/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java index aaa5de87e1..d8b9887605 100644 --- a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java +++ b/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/bynumber/NaturalOrderComparatorsUnitTest.java @@ -1,17 +1,19 @@ package com.baeldung.algorithms.bynumber; -import org.junit.Test; + + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; -public class NaturalOrderComparatorsUnitTest { +class NaturalOrderComparatorsUnitTest { @Test - public void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() { + void givenSimpleStringsContainingIntsAndDoubles_whenSortedByRegex_checkSortingCorrect() { List testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3d"); @@ -25,7 +27,7 @@ public class NaturalOrderComparatorsUnitTest { } @Test - public void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() { + void givenSimpleStringsContainingIntsAndDoublesWithAnInvalidNumber_whenSortedByRegex_checkSortingCorrect() { List testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.4", "d2.3.3d"); @@ -39,7 +41,7 @@ public class NaturalOrderComparatorsUnitTest { } @Test - public void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() { + void givenAllForseenProblems_whenSortedByRegex_checkSortingCorrect() { List testStrings = Arrays.asList("a1", "b3", "c4", "d2.2", "d2.f4", "d2.3.3d"); @@ -53,7 +55,7 @@ public class NaturalOrderComparatorsUnitTest { } @Test - public void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() { + void givenComplexStringsContainingSeparatedNumbers_whenSortedByRegex_checkNumbersCondensedAndSorted() { List testStrings = Arrays.asList("a1b2c5", "b3ght3.2", "something65.thensomething5"); //125, 33.2, 65.5 @@ -66,7 +68,7 @@ public class NaturalOrderComparatorsUnitTest { } @Test - public void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() { + void givenStringsNotContainingNumbers_whenSortedByRegex_checkOrderNotChanged() { List testStrings = Arrays.asList("a", "c", "d", "e"); List expected = new ArrayList<>(testStrings); diff --git a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/gravitysort/GravitySortUnitTest.java b/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/gravitysort/GravitySortUnitTest.java index 89fc1ed687..c1ef611ab6 100644 --- a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/gravitysort/GravitySortUnitTest.java +++ b/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/gravitysort/GravitySortUnitTest.java @@ -1,15 +1,16 @@ package com.baeldung.algorithms.gravitysort; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; -public class GravitySortUnitTest { +import org.junit.jupiter.api.Test; + +class GravitySortUnitTest { @Test - public void givenIntegerArray_whenSortedWithGravitySort_thenGetSortedArray() { + void givenIntegerArray_whenSortedWithGravitySort_thenGetSortedArray() { int[] actual = { 9, 9, 100, 3, 57, 12, 3, 78, 0, 2, 2, 40, 21, 9 }; int[] expected = { 0, 2, 2, 3, 3, 9, 9, 9, 12, 21, 40, 57, 78, 100 }; GravitySort.sort(actual); - Assert.assertArrayEquals(expected, actual); + assertArrayEquals(expected, actual); } } diff --git a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java b/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java index 321b905f68..2d87dfaf1e 100644 --- a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java +++ b/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/inoutsort/InOutSortUnitTest.java @@ -1,23 +1,22 @@ package com.baeldung.algorithms.inoutsort; -import static org.junit.Assert.*; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class InOutSortUnitTest { +class InOutSortUnitTest { @Test - public void givenArray_whenInPlaceSort_thenReversed() { + void givenArray_whenInPlaceSort_thenReversed() { int[] input = {1, 2, 3, 4, 5, 6, 7}; int[] expected = {7, 6, 5, 4, 3, 2, 1}; - assertArrayEquals("the two arrays are not equal", expected, InOutSort.reverseInPlace(input)); + assertArrayEquals(expected, InOutSort.reverseInPlace(input), "the two arrays are not equal"); } @Test - public void givenArray_whenOutOfPlaceSort_thenReversed() { + void givenArray_whenOutOfPlaceSort_thenReversed() { int[] input = {1, 2, 3, 4, 5, 6, 7}; int[] expected = {7, 6, 5, 4, 3, 2, 1}; - assertArrayEquals("the two arrays are not equal", expected, InOutSort.reverseOutOfPlace(input)); + assertArrayEquals(expected, InOutSort.reverseOutOfPlace(input), "the two arrays are not equal"); } } diff --git a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java b/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java index 847f7f8acb..02cb01ab71 100644 --- a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java +++ b/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/BentleyMcilroyPartitioningUnitTest.java @@ -1,16 +1,17 @@ package com.baeldung.algorithms.quicksort; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; -public class BentleyMcilroyPartitioningUnitTest { +import org.junit.jupiter.api.Test; + +class BentleyMcilroyPartitioningUnitTest { @Test - public void given_IntegerArray_whenSortedWithBentleyMcilroyPartitioning_thenGetSortedArray() { + void given_IntegerArray_whenSortedWithBentleyMcilroyPartitioning_thenGetSortedArray() { int[] actual = {3, 2, 2, 2, 3, 7, 7, 3, 2, 2, 7, 3, 3}; int[] expected = {2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 7, 7, 7}; BentleyMcIlroyPartioning.quicksort(actual, 0, actual.length - 1); - Assert.assertArrayEquals(expected, actual); + assertArrayEquals(expected, actual); } } diff --git a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java b/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java index a8e27253cc..f8eec55e8f 100644 --- a/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java +++ b/algorithms-modules/algorithms-sorting-2/src/test/java/com/baeldung/algorithms/quicksort/DNFThreeWayQuickSortUnitTest.java @@ -1,15 +1,16 @@ package com.baeldung.algorithms.quicksort; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; -public class DNFThreeWayQuickSortUnitTest { +import org.junit.jupiter.api.Test; + +class DNFThreeWayQuickSortUnitTest { @Test - public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() { + void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() { int[] actual = {3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3}; int[] expected = {3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7}; DutchNationalFlagPartioning.quicksort(actual, 0, actual.length - 1); - Assert.assertArrayEquals(expected, actual); + assertArrayEquals(expected, actual); } } diff --git a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java index 210ee2378a..edbd352020 100644 --- a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java +++ b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/bubblesort/BubbleSortUnitTest.java @@ -4,10 +4,10 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; -public class BubbleSortUnitTest { +class BubbleSortUnitTest { @Test - public void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() { + void givenIntegerArray_whenSortedWithBubbleSort_thenGetSortedArray() { Integer[] array = { 2, 1, 4, 6, 3, 5 }; Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; BubbleSort bubbleSort = new BubbleSort(); @@ -16,7 +16,7 @@ public class BubbleSortUnitTest { } @Test - public void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() { + void givenIntegerArray_whenSortedWithOptimizedBubbleSort_thenGetSortedArray() { Integer[] array = { 2, 1, 4, 6, 3, 5 }; Integer[] sortedArray = { 1, 2, 3, 4, 5, 6 }; BubbleSort bubbleSort = new BubbleSort(); diff --git a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorterUnitTest.java b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorterUnitTest.java index 4671819673..3916834c83 100644 --- a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorterUnitTest.java +++ b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/bucketsort/IntegerBucketSorterUnitTest.java @@ -1,24 +1,26 @@ package com.baeldung.algorithms.bucketsort; -import static org.junit.Assert.assertEquals; + + +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class IntegerBucketSorterUnitTest { +class IntegerBucketSorterUnitTest { private IntegerBucketSorter sorter; - @Before + @BeforeEach public void setUp() throws Exception { sorter = new IntegerBucketSorter(); } @Test - public void givenUnsortedList_whenSortedUsingBucketSorter_checkSortingCorrect() { + void givenUnsortedList_whenSortedUsingBucketSorter_checkSortingCorrect() { List unsorted = Arrays.asList(80,50,60,30,20,10,70,0,40,500,600,602,200,15); List expected = Arrays.asList(0,10,15,20,30,40,50,60,70,80,200,500,600,602); @@ -26,7 +28,5 @@ public class IntegerBucketSorterUnitTest { List actual = sorter.sort(unsorted); assertEquals(expected, actual); - - } } \ No newline at end of file diff --git a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java index 96e4936eaf..b4240f0287 100644 --- a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java +++ b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/heapsort/HeapUnitTest.java @@ -1,16 +1,16 @@ package com.baeldung.algorithms.heapsort; -import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import java.util.Arrays; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class HeapUnitTest { +class HeapUnitTest { @Test - public void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() { + void givenNotEmptyHeap_whenPopCalled_thenItShouldReturnSmallestElement() { // given Heap heap = Heap.of(3, 5, 1, 4, 2); @@ -22,7 +22,7 @@ public class HeapUnitTest { } @Test - public void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() { + void givenNotEmptyIterable_whenSortCalled_thenItShouldReturnElementsInSortedList() { // given List elements = Arrays.asList(3, 5, 1, 4, 2); diff --git a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java index b3d7e8c534..5845df45ae 100644 --- a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java +++ b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java @@ -1,25 +1,25 @@ package com.baeldung.algorithms.insertionsort; -import com.baeldung.algorithms.insertionsort.InsertionSort; -import org.junit.Test; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; -public class InsertionSortUnitTest { +import org.junit.jupiter.api.Test; + +class InsertionSortUnitTest { @Test - public void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() { + void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() { int[] input = {6, 2, 3, 4, 5, 1}; InsertionSort.insertionSortImperative(input); int[] expected = {1, 2, 3, 4, 5, 6}; - assertArrayEquals("the two arrays are not equal", expected, input); + assertArrayEquals(expected, input, "the two arrays are not equal"); } @Test - public void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() { + void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() { int[] input = {6, 4, 5, 2, 3, 1}; InsertionSort.insertionSortRecursive(input); int[] expected = {1, 2, 3, 4, 5, 6}; - assertArrayEquals("the two arrays are not equal", expected, input); + assertArrayEquals( expected, input, "the two arrays are not equal"); } } diff --git a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java index 5cd14b7bd0..cc663458bd 100644 --- a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java +++ b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java @@ -1,17 +1,17 @@ package com.baeldung.algorithms.mergesort; -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class MergeSortUnitTest { +class MergeSortUnitTest { @Test - public void positiveTest() { + void positiveTest() { int[] actual = { 5, 1, 6, 2, 3, 4 }; int[] expected = { 1, 2, 3, 4, 5, 6 }; MergeSort.mergeSort(actual, actual.length); - Assert.assertArrayEquals(expected, actual); + assertArrayEquals(expected, actual); } } diff --git a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java index c9af5b4bf8..c4e53cc50b 100644 --- a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java +++ b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java @@ -1,17 +1,17 @@ package com.baeldung.algorithms.quicksort; -import com.baeldung.algorithms.quicksort.QuickSort; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; -public class QuickSortUnitTest { +import org.junit.jupiter.api.Test; + +class QuickSortUnitTest { @Test - public void givenIntegerArray_whenSortedWithQuickSort_thenGetSortedArray() { + void givenIntegerArray_whenSortedWithQuickSort_thenGetSortedArray() { int[] actual = { 9, 5, 1, 0, 6, 2, 3, 4, 7, 8 }; int[] expected = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; QuickSort.quickSort(actual, 0, actual.length-1); - Assert.assertArrayEquals(expected, actual); + assertArrayEquals(expected, actual); } } diff --git a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java index cd8c7c1241..bb0b5c6bd3 100644 --- a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java +++ b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java @@ -1,15 +1,16 @@ package com.baeldung.algorithms.quicksort; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; -public class ThreeWayQuickSortUnitTest { +import org.junit.jupiter.api.Test; + +class ThreeWayQuickSortUnitTest { @Test public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() { int[] actual = { 3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3 }; int[] expected = { 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7 }; ThreeWayQuickSort.threeWayQuickSort(actual, 0, actual.length-1); - Assert.assertArrayEquals(expected, actual); + assertArrayEquals(expected, actual); } } diff --git a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/radixsort/RadixSortUnitTest.java b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/radixsort/RadixSortUnitTest.java index 0f6c751ade..66225344cd 100644 --- a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/radixsort/RadixSortUnitTest.java +++ b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/radixsort/RadixSortUnitTest.java @@ -1,13 +1,13 @@ package com.baeldung.algorithms.radixsort; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class RadixSortUnitTest { +class RadixSortUnitTest { @Test - public void givenUnsortedArray_whenRadixSort_thenArraySorted() { + void givenUnsortedArray_whenRadixSort_thenArraySorted() { int[] numbers = { 387, 468, 134, 123, 68, 221, 769, 37, 7 }; RadixSort.sort(numbers); int[] numbersSorted = { 7, 37, 68, 123, 134, 221, 387, 468, 769 }; diff --git a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/selectionsort/SelectionSortUnitTest.java b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/selectionsort/SelectionSortUnitTest.java index 85efd1d3da..3cbc88e128 100644 --- a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/selectionsort/SelectionSortUnitTest.java +++ b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/selectionsort/SelectionSortUnitTest.java @@ -1,25 +1,24 @@ package com.baeldung.algorithms.selectionsort; -import static org.junit.Assert.*; -import static org.junit.Assert.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class SelectionSortUnitTest { +class SelectionSortUnitTest { @Test - public void givenUnsortedArray_whenSelectionSort_SortAscending_thenSortedAsc() { + void givenUnsortedArray_whenSelectionSort_SortAscending_thenSortedAsc() { int[] input = { 5, 4, 1, 6, 2 }; SelectionSort.sortAscending(input); int[] expected = {1, 2, 4, 5, 6}; - assertArrayEquals("the two arrays are not equal", expected, input); + assertArrayEquals(expected, input, "the two arrays are not equal"); } @Test - public void givenUnsortedArray_whenSelectionSort_SortDescending_thenSortedDesc() { + void givenUnsortedArray_whenSelectionSort_SortDescending_thenSortedDesc() { int[] input = { 5, 4, 1, 6, 2 }; SelectionSort.sortDescending(input); int[] expected = {6, 5, 4, 2, 1}; - assertArrayEquals("the two arrays are not equal", expected, input); + assertArrayEquals(expected, input, "the two arrays are not equal"); } } diff --git a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java index 91a27c41d0..38a861c2c0 100644 --- a/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java +++ b/algorithms-modules/algorithms-sorting/src/test/java/com/baeldung/algorithms/shellsort/ShellSortUnitTest.java @@ -1,17 +1,17 @@ package com.baeldung.algorithms.shellsort; -import static org.junit.Assert.*; -import static org.junit.Assert.assertArrayEquals; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; -public class ShellSortUnitTest { +import org.junit.jupiter.api.Test; + +class ShellSortUnitTest { @Test - public void givenUnsortedArray_whenShellSort_thenSortedAsc() { + void givenUnsortedArray_whenShellSort_thenSortedAsc() { int[] input = {41, 15, 82, 5, 65, 19, 32, 43, 8}; ShellSort.sort(input); int[] expected = {5, 8, 15, 19, 32, 41, 43, 65, 82}; - assertArrayEquals("the two arrays are not equal", expected, input); + assertArrayEquals( expected, input, "the two arrays are not equal"); } } diff --git a/pom.xml b/pom.xml index 431d712c6b..05f8326e4c 100644 --- a/pom.xml +++ b/pom.xml @@ -330,8 +330,6 @@ parent-spring-5 parent-java - algorithms-modules - apache-cxf-modules apache-libraries apache-poi @@ -615,8 +613,6 @@ parent-spring-5 parent-java - algorithms-modules - apache-cxf-modules apache-libraries apache-poi @@ -912,6 +908,7 @@ + algorithms-modules core-java-modules/core-java-9 core-java-modules/core-java-9-improvements core-java-modules/core-java-9-jigsaw @@ -1108,6 +1105,7 @@ + algorithms-modules core-java-modules/core-java-9 core-java-modules/core-java-9-improvements core-java-modules/core-java-9-jigsaw From 8f49093d3fd65adc486b1a1569701b3ba3274ab2 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Tue, 7 Feb 2023 15:39:57 +0000 Subject: [PATCH 046/113] Java 15035 (#13421) * [JAVA-15035] Created module httpclient4 and moved related code * [JAVA-15035] Upgraded httpclient-simple to spring-boot-e * [JAVA-15035] Moved modules to to right profiles * [JAVA-15026] Upgraded headers code to apache 5.2 + moved code related to 4.5 to httpclient4 module * [JAVA-14911] Final clean up for http-client module --------- Co-authored-by: panagiotiskakos --- httpclient-simple/pom.xml | 184 +++-------- .../MyBasicAuthenticationEntryPoint.java | 4 +- ...entsClientHttpRequestFactoryBasicAuth.java | 15 +- .../baeldung/client/RestTemplateFactory.java | 4 +- .../com/baeldung/filter/CustomFilter.java | 8 +- .../CustomWebSecurityConfigurerAdapter.java | 33 +- ...uestAwareAuthenticationSuccessHandler.java | 6 +- .../RestAuthenticationEntryPoint.java | 4 +- .../main/java/com/baeldung/web/dto/Bar.java | 2 +- .../main/java/com/baeldung/web/dto/Foo.java | 2 +- .../com/baeldung/client/ClientLiveTest.java | 37 +-- .../client/RestClientLiveManualTest.java | 100 ++---- .../httpclient/HttpClientHeadersLiveTest.java | 116 +++---- .../httpclient/HttpClientParamsLiveTest.java | 80 +++-- .../httpclient/HttpClientTimeoutLiveTest.java | 1 - .../httpclient/HttpsClientSslLiveTest.java | 134 +++----- .../base/HttpClientBasicLiveTest.java | 10 +- .../java/com/baeldung/test/LiveTestSuite.java | 16 - httpclient4/.gitignore | 13 + httpclient4/README.md | 13 + httpclient4/pom.xml | 291 ++++++++++++++++++ .../MyBasicAuthenticationEntryPoint.java | 30 ++ ...entsClientHttpRequestFactoryBasicAuth.java | 39 +++ .../baeldung/client/RestTemplateFactory.java | 44 +++ .../baeldung/client/spring/ClientConfig.java | 16 + .../com/baeldung/filter/CustomFilter.java | 18 ++ .../CustomWebSecurityConfigurerAdapter.java | 49 +++ ...uestAwareAuthenticationSuccessHandler.java | 48 +++ .../RestAuthenticationEntryPoint.java | 23 ++ .../baeldung/spring/SecSecurityConfig.java | 16 + .../java/com/baeldung/spring/WebConfig.java | 30 ++ .../web/controller/BarController.java | 31 ++ .../web/controller/FooController.java | 33 ++ .../main/java/com/baeldung/web/dto/Bar.java | 14 + .../main/java/com/baeldung/web/dto/Foo.java | 14 + httpclient4/src/main/resources/logback.xml | 19 ++ .../src/main/resources/webSecurityConfig.xml | 28 ++ .../src/main/webapp/WEB-INF/api-servlet.xml | 6 + httpclient4/src/main/webapp/WEB-INF/web.xml | 43 +++ .../com/baeldung/client/ClientLiveTest.java | 99 ++++++ .../client/RestClientV4LiveManualTest.java | 92 ++++++ .../HttpClientHeaderV4LiveTest.java | 24 ++ .../HttpClientTimeoutV4LiveTest.java | 2 +- .../httpclient/HttpsClientV4SslLiveTest.java | 111 +++++++ .../com/baeldung/httpclient/ResponseUtil.java | 0 httpclient4/src/test/resources/.gitignore | 13 + httpclient4/src/test/resources/test.in | 1 + pom.xml | 6 +- 48 files changed, 1441 insertions(+), 481 deletions(-) delete mode 100644 httpclient-simple/src/test/java/com/baeldung/test/LiveTestSuite.java create mode 100644 httpclient4/.gitignore create mode 100644 httpclient4/README.md create mode 100644 httpclient4/pom.xml create mode 100644 httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java create mode 100644 httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java create mode 100644 httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java create mode 100644 httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java create mode 100644 httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java create mode 100644 httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java create mode 100644 httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java create mode 100644 httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java create mode 100644 httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java create mode 100644 httpclient4/src/main/java/com/baeldung/spring/WebConfig.java create mode 100644 httpclient4/src/main/java/com/baeldung/web/controller/BarController.java create mode 100644 httpclient4/src/main/java/com/baeldung/web/controller/FooController.java create mode 100644 httpclient4/src/main/java/com/baeldung/web/dto/Bar.java create mode 100644 httpclient4/src/main/java/com/baeldung/web/dto/Foo.java create mode 100644 httpclient4/src/main/resources/logback.xml create mode 100644 httpclient4/src/main/resources/webSecurityConfig.xml create mode 100644 httpclient4/src/main/webapp/WEB-INF/api-servlet.xml create mode 100644 httpclient4/src/main/webapp/WEB-INF/web.xml create mode 100644 httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java create mode 100644 httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java create mode 100644 httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java rename {httpclient-simple => httpclient4}/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java (97%) create mode 100644 httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java rename {httpclient-simple => httpclient4}/src/test/java/com/baeldung/httpclient/ResponseUtil.java (100%) create mode 100644 httpclient4/src/test/resources/.gitignore create mode 100644 httpclient4/src/test/resources/test.in diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml index c39983564f..eea056477c 100644 --- a/httpclient-simple/pom.xml +++ b/httpclient-simple/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 httpclient-simple 0.1-SNAPSHOT @@ -10,90 +10,61 @@ com.baeldung - parent-spring-5 + parent-boot-3 0.0.1-SNAPSHOT - ../parent-spring-5 + ../parent-boot-3 - - org.springframework.security - spring-security-web - ${spring-security.version} + org.springframework.boot + spring-boot-starter - org.springframework.security - spring-security-config - ${spring-security.version} - - - - org.springframework - spring-core - ${spring.version} - - - commons-logging - commons-logging - - + org.springframework.boot + spring-boot-starter-security - org.springframework - spring-context - ${spring.version} + org.springframework.boot + spring-boot-starter-jdbc - org.springframework - spring-jdbc - ${spring.version} + org.springframework.boot + spring-boot-starter-aop - org.springframework - spring-beans - ${spring.version} + org.springframework.boot + spring-boot-starter-web - org.springframework - spring-aop - ${spring.version} + jakarta.xml.bind + jakarta.xml.bind-api + 4.0.0 - org.springframework - spring-tx - ${spring.version} - - - org.springframework - spring-expression - ${spring.version} - - - org.springframework - spring-web - ${spring.version} - - - org.springframework - spring-webmvc - ${spring.version} - - - org.springframework - spring-oxm - ${spring.version} + com.sun.xml.bind + jaxb-impl + 4.0.0 + runtime + com.fasterxml.jackson.core jackson-databind ${jackson.version} + - org.apache.httpcomponents - httpcore - ${httpcore.version} + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.apache.httpcomponents.client5 + httpclient5 + ${httpclient5.version} commons-logging @@ -112,7 +83,6 @@ - org.apache.httpcomponents.client5 httpclient5-fluent @@ -124,67 +94,11 @@ - - - org.apache.commons - commons-lang3 - ${commons-lang3.version} - - - - org.apache.httpcomponents - httpclient - ${httpclient.version} - - - commons-logging - commons-logging - - - - - org.apache.httpcomponents - fluent-hc - ${httpclient.version} - - - commons-logging - commons-logging - - - - - org.apache.httpcomponents.client5 - httpclient5 - ${httpclient5.version} - - - commons-logging - commons-logging - - - - - org.apache.httpcomponents - httpmime - ${httpclient.version} - commons-codec commons-codec ${commons-codec.version} - - org.apache.httpcomponents - httpasyncclient - ${httpasyncclient.version} - - - commons-logging - commons-logging - - - com.github.tomakehurst wiremock @@ -210,13 +124,6 @@ guava ${guava.version} - - - org.springframework - spring-test - ${spring.version} - test - @@ -231,26 +138,13 @@ org.apache.maven.plugins maven-war-plugin - ${maven-war-plugin.version} + 3.3.2 - org.codehaus.cargo - cargo-maven2-plugin - ${cargo-maven2-plugin.version} + org.springframework.boot + spring-boot-maven-plugin - true - - jetty8x - embedded - - - - - - - 8082 - - + true @@ -263,7 +157,7 @@ org.codehaus.cargo - cargo-maven2-plugin + cargo-maven3-plugin start-server @@ -310,13 +204,11 @@ + 17 1.10 - 4.1.4 2.5.1 - 4.4.11 - 4.5.8 5.2 5.2 diff --git a/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java index cafd8cfb7b..487794cc7f 100644 --- a/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java +++ b/httpclient-simple/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -3,8 +3,8 @@ package com.baeldung.basic; import java.io.IOException; import java.io.PrintWriter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; diff --git a/httpclient-simple/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/httpclient-simple/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java index 81f82a2c1c..7a0599cd49 100644 --- a/httpclient-simple/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java +++ b/httpclient-simple/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java @@ -2,13 +2,13 @@ package com.baeldung.client; import java.net.URI; -import org.apache.http.HttpHost; -import org.apache.http.client.AuthCache; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.impl.auth.BasicScheme; -import org.apache.http.impl.client.BasicAuthCache; -import org.apache.http.protocol.BasicHttpContext; -import org.apache.http.protocol.HttpContext; +import org.apache.hc.core5.http.HttpHost; +import org.apache.hc.client5.http.auth.AuthCache; +import org.apache.hc.client5.http.impl.auth.BasicAuthCache; +import org.apache.hc.client5.http.impl.auth.BasicScheme; +import org.apache.hc.client5.http.protocol.HttpClientContext; +import org.apache.hc.core5.http.protocol.BasicHttpContext; +import org.apache.hc.core5.http.protocol.HttpContext; import org.springframework.http.HttpMethod; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; @@ -21,6 +21,7 @@ public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpCompone this.host = host; } + @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { return createHttpContext(); } diff --git a/httpclient-simple/src/main/java/com/baeldung/client/RestTemplateFactory.java b/httpclient-simple/src/main/java/com/baeldung/client/RestTemplateFactory.java index aac4f8cebd..fafaae0157 100644 --- a/httpclient-simple/src/main/java/com/baeldung/client/RestTemplateFactory.java +++ b/httpclient-simple/src/main/java/com/baeldung/client/RestTemplateFactory.java @@ -1,6 +1,6 @@ package com.baeldung.client; -import org.apache.http.HttpHost; +import org.apache.hc.core5.http.HttpHost; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.http.client.ClientHttpRequestFactory; @@ -35,7 +35,7 @@ public class RestTemplateFactory implements FactoryBean, Initializ @Override public void afterPropertiesSet() { - HttpHost host = new HttpHost("localhost", 8082, "http"); + HttpHost host = new HttpHost("http", "localhost", 8082); final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host); restTemplate = new RestTemplate(requestFactory); restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("user1", "user1Pass")); diff --git a/httpclient-simple/src/main/java/com/baeldung/filter/CustomFilter.java b/httpclient-simple/src/main/java/com/baeldung/filter/CustomFilter.java index 6bb12610fa..a9509ddafa 100644 --- a/httpclient-simple/src/main/java/com/baeldung/filter/CustomFilter.java +++ b/httpclient-simple/src/main/java/com/baeldung/filter/CustomFilter.java @@ -2,10 +2,10 @@ package com.baeldung.filter; import org.springframework.web.filter.GenericFilterBean; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; import java.io.IOException; public class CustomFilter extends GenericFilterBean { diff --git a/httpclient-simple/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/httpclient-simple/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java index fb597e46c8..859b900170 100644 --- a/httpclient-simple/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java +++ b/httpclient-simple/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java @@ -7,41 +7,38 @@ import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; @Configuration @EnableWebSecurity -public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { +public class CustomWebSecurityConfigurerAdapter{ @Autowired private RestAuthenticationEntryPoint authenticationEntryPoint; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth - .inMemoryAuthentication() - .withUser("user1") - .password(passwordEncoder().encode("user1Pass")) - .authorities("ROLE_USER"); + .inMemoryAuthentication() + .withUser("user1") + .password(passwordEncoder().encode("user1Pass")) + .authorities("ROLE_USER"); } - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .authorizeRequests() - .antMatchers("/securityNone") - .permitAll() - .anyRequest() - .authenticated() - .and() - .httpBasic() - .authenticationEntryPoint(authenticationEntryPoint); + @Bean + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { + + http.authorizeHttpRequests((authorize) -> authorize.anyRequest() + .authenticated()) + .httpBasic() + .authenticationEntryPoint(authenticationEntryPoint); http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); + return http.build(); } - + @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); diff --git a/httpclient-simple/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/httpclient-simple/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java index 7dc53e3e1e..d53aa5bdfe 100644 --- a/httpclient-simple/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java +++ b/httpclient-simple/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java @@ -2,9 +2,9 @@ package com.baeldung.security; import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; diff --git a/httpclient-simple/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java b/httpclient-simple/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java index 1ae89adb89..615982fae4 100644 --- a/httpclient-simple/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java +++ b/httpclient-simple/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java @@ -2,8 +2,8 @@ package com.baeldung.security; import java.io.IOException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; diff --git a/httpclient-simple/src/main/java/com/baeldung/web/dto/Bar.java b/httpclient-simple/src/main/java/com/baeldung/web/dto/Bar.java index eb139b0ec1..1bb7476669 100644 --- a/httpclient-simple/src/main/java/com/baeldung/web/dto/Bar.java +++ b/httpclient-simple/src/main/java/com/baeldung/web/dto/Bar.java @@ -2,7 +2,7 @@ package com.baeldung.web.dto; import java.io.Serializable; -import javax.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Bar implements Serializable { diff --git a/httpclient-simple/src/main/java/com/baeldung/web/dto/Foo.java b/httpclient-simple/src/main/java/com/baeldung/web/dto/Foo.java index 23cfab132d..f904be0ad9 100644 --- a/httpclient-simple/src/main/java/com/baeldung/web/dto/Foo.java +++ b/httpclient-simple/src/main/java/com/baeldung/web/dto/Foo.java @@ -2,7 +2,7 @@ package com.baeldung.web.dto; import java.io.Serializable; -import javax.xml.bind.annotation.XmlRootElement; +import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Foo implements Serializable { diff --git a/httpclient-simple/src/test/java/com/baeldung/client/ClientLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/client/ClientLiveTest.java index 78e9813f06..1c7e766a72 100644 --- a/httpclient-simple/src/test/java/com/baeldung/client/ClientLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/client/ClientLiveTest.java @@ -1,25 +1,23 @@ package com.baeldung.client; -import static org.hamcrest.Matchers.equalTo; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; -import com.baeldung.client.spring.ClientConfig; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + import com.baeldung.web.dto.Foo; -import org.junit.Test; -import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.support.AnnotationConfigContextLoader; + import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = { ClientConfig.class }, loader = AnnotationConfigContextLoader.class) -public class ClientLiveTest { +class ClientLiveTest { @Autowired private RestTemplate secureRestTemplate; @@ -27,21 +25,24 @@ public class ClientLiveTest { // tests @Test - public final void whenContextIsBootstrapped_thenNoExceptions() { + void whenContextIsBootstrapped_thenNoExceptions() { // } @Test - public final void whenSecuredRestApiIsConsumed_then200OK() { + void whenSecuredRestApiIsConsumed_then200OK() { final ResponseEntity responseEntity = secureRestTemplate.exchange("http://localhost:8082/httpclient-simple/api/foos/1", HttpMethod.GET, null, Foo.class); assertThat(responseEntity.getStatusCode().value(), is(200)); } - @Test(expected = ResourceAccessException.class) - public final void whenHttpsUrlIsConsumed_thenException() { + @Test + void whenHttpsUrlIsConsumed_thenException() { final String urlOverHttps = "https://localhost:8443/httpclient-simple/api/bars/1"; - final ResponseEntity response = new RestTemplate().exchange(urlOverHttps, HttpMethod.GET, null, String.class); - assertThat(response.getStatusCode().value(), equalTo(200)); + assertThrows(ResourceAccessException.class, () -> { + final ResponseEntity response = new RestTemplate() + .exchange(urlOverHttps, HttpMethod.GET, null, String.class); + assertThat(response.getStatusCode().value(), equalTo(200)); + }); } } diff --git a/httpclient-simple/src/test/java/com/baeldung/client/RestClientLiveManualTest.java b/httpclient-simple/src/test/java/com/baeldung/client/RestClientLiveManualTest.java index d133bc376c..efa0695aaf 100644 --- a/httpclient-simple/src/test/java/com/baeldung/client/RestClientLiveManualTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/client/RestClientLiveManualTest.java @@ -1,112 +1,78 @@ package com.baeldung.client; -import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; -import java.io.IOException; import java.security.GeneralSecurityException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLPeerUnverifiedException; -import org.apache.http.HttpResponse; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.NoopHostnameVerifier; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.conn.ssl.TrustStrategy; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.BasicHttpClientConnectionManager; -import org.apache.http.ssl.SSLContexts; -import org.junit.Ignore; -import org.junit.Test; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager; +import org.apache.hc.client5.http.socket.ConnectionSocketFactory; +import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory; +import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; +import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; +import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.config.Registry; +import org.apache.hc.core5.http.config.RegistryBuilder; +import org.apache.hc.core5.ssl.SSLContexts; +import org.apache.hc.core5.ssl.TrustStrategy; +import org.junit.jupiter.api.Test; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestTemplate; +import com.baeldung.handler.CustomHttpClientResponseHandler; + + /** * This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build * */ -public class RestClientLiveManualTest { +class RestClientLiveManualTest { final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1"; - // tests - // old httpClient will throw UnsupportedOperationException - @Ignore - @Test - public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk() throws GeneralSecurityException { - final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - final CloseableHttpClient httpClient = (CloseableHttpClient) requestFactory.getHttpClient(); - - final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true; - - final SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, ALLOW_ALL_HOSTNAME_VERIFIER); - httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 8443, sf)); - - final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); - assertThat(response.getStatusCode().value(), equalTo(200)); - } - // new httpClient : 4.4 and above @Test - public final void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException { + void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk() throws GeneralSecurityException { final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true; final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); final Registry socketFactoryRegistry = RegistryBuilder. create() - .register("https", sslsf) - .register("http", new PlainConnectionSocketFactory()) - .build(); + .register("https", sslsf) + .register("http", new PlainConnectionSocketFactory()) + .build(); final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry); final CloseableHttpClient httpClient = HttpClients.custom() - .setSSLSocketFactory(sslsf) - .setConnectionManager(connectionManager) - .build(); + .setConnectionManager(connectionManager) + .build(); final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); assertThat(response.getStatusCode().value(), equalTo(200)); } - @Test - public final void givenAcceptingAllCertificatesUsing4_4_whenHttpsUrlIsConsumed_thenCorrect() throws ClientProtocolException, IOException { - final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); - final HttpGet getMethod = new HttpGet(urlOverHttps); - final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); - } @Test - public final void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() throws ClientProtocolException, IOException { - final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); - final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - requestFactory.setHttpClient(httpClient); - - final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); - assertThat(response.getStatusCode().value(), equalTo(200)); - } - - @Test(expected = SSLPeerUnverifiedException.class) - public void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException { - CloseableHttpClient httpClient = HttpClients.createDefault(); + void whenHttpsUrlIsConsumed_thenException() { String urlOverHttps = "https://localhost:8082/httpclient-simple"; HttpGet getMethod = new HttpGet(urlOverHttps); - HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + assertThrows(SSLPeerUnverifiedException.class, () -> { + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpResponse response = httpClient.execute(getMethod, new CustomHttpClientResponseHandler()); + assertThat(response.getCode(), equalTo(200)); + }); } } diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java index 44262851fd..616b6470af 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java @@ -1,100 +1,76 @@ package com.baeldung.httpclient; import com.google.common.collect.Lists; -import org.apache.http.Header; -import org.apache.http.HttpHeaders; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.methods.RequestBuilder; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.message.BasicHeader; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; + +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.core5.http.Header; +import org.apache.hc.core5.http.HttpHeaders; +import org.apache.hc.core5.http.message.BasicHeader; + +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.IOException; import java.util.List; -public class HttpClientHeadersLiveTest { +class HttpClientHeadersLiveTest { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); private static final String SAMPLE_URL = "http://www.github.com"; - private CloseableHttpClient client; - - private CloseableHttpResponse response; - - @Before - public final void before() { - client = HttpClientBuilder.create().build(); - } - - @After - public final void after() throws IllegalStateException, IOException { - ResponseUtil.closeResponse(response); - } - - // tests - headers - deprecated - @Test - public final void givenNewApi_whenClientUsesCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException { - client = HttpClients.custom().setUserAgent("Mozilla/5.0 Firefox/26.0").build(); - + void whenClientUsesCustomUserAgent_thenCorrect() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); - response = client.execute(request); + + try (CloseableHttpClient client = HttpClients.custom() + .setUserAgent("Mozilla/5.0 Firefox/26.0") + .build()) { + + String response = client.execute(request, new BasicHttpClientResponseHandler()); + logger.info("Response -> {}", response); + } } - // tests - headers - user agent - @Test - public final void givenConfigOnRequest_whenRequestHasCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException { - client = HttpClients.custom().build(); + void whenRequestHasCustomUserAgent_thenCorrect() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); request.setHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 Firefox/26.0"); - response = client.execute(request); + + try (CloseableHttpClient client = HttpClients.createDefault()) { + String response = client.execute(request, new BasicHttpClientResponseHandler()); + logger.info("Response -> {}", response); + } } @Test - public final void givenConfigOnClient_whenRequestHasCustomUserAgent_thenCorrect() throws ClientProtocolException, IOException { - client = HttpClients.custom().setUserAgent("Mozilla/5.0 Firefox/26.0").build(); - response = client.execute(new HttpGet(SAMPLE_URL)); - } - - // tests - headers - content type - - @Test - public final void givenUsingNewApi_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException { - client = HttpClients.custom().build(); + void whenRequestHasCustomContentType_thenCorrect() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - response = client.execute(request); + + try (CloseableHttpClient client = HttpClients.createDefault()) { + String response = client.execute(request, new BasicHttpClientResponseHandler()); + logger.debug("Response -> {}", response); + } } @Test - public final void givenRequestBuildWithBuilderWithNewApi_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException { - final CloseableHttpClient client2 = HttpClients.custom().build(); + void givenConfigOnClient_whenRequestHasCustomContentType_thenCorrect() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); - request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json"); - response = client2.execute(request); - } - - @Test - public final void givenRequestBuildWithBuilder_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException { - client = HttpClients.custom().build(); - final HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).setHeader(HttpHeaders.CONTENT_TYPE, "application/json").build(); - response = client.execute(request); - } - - @Test - public final void givenConfigOnClient_whenRequestHasCustomContentType_thenCorrect() throws ClientProtocolException, IOException { final Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"); final List
headers = Lists.newArrayList(header); - client = HttpClients.custom().setDefaultHeaders(headers).build(); - final HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build(); - response = client.execute(request); - } + + try (CloseableHttpClient client = HttpClients.custom() + .setDefaultHeaders(headers) + .build()) { + + String response = client.execute(request, new BasicHttpClientResponseHandler()); + logger.debug("Response -> {}", response); + } + } } diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientParamsLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientParamsLiveTest.java index f56a6863a3..ef662e1bd8 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientParamsLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientParamsLiveTest.java @@ -1,7 +1,8 @@ package com.baeldung.httpclient; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; -import static org.junit.Assert.assertThat; + import java.io.IOException; import java.net.URI; @@ -14,28 +15,25 @@ import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; -import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.client5.http.ClientProtocolException; import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.NameValuePair; import org.apache.hc.core5.http.message.BasicNameValuePair; import org.apache.hc.core5.net.URIBuilder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import org.junit.Before; -import org.junit.Test; +import com.baeldung.handler.CustomHttpClientResponseHandler; -public class HttpClientParamsLiveTest { +class HttpClientParamsLiveTest { - private CloseableHttpClient client; - - private CloseableHttpResponse response; private List nameValuePairs; - @Before + @BeforeEach public void setUp() { - client = HttpClientBuilder.create() - .build(); nameValuePairs = new ArrayList<>(); NameValuePair param1NameValuePair = new BasicNameValuePair("param1", "value1"); NameValuePair param2NameValuePair = new BasicNameValuePair("param2", "value2"); @@ -44,63 +42,83 @@ public class HttpClientParamsLiveTest { } @Test - public void givenStringNameValuePairParams_whenGetRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { + void givenStringNameValuePairParams_whenGetRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { HttpGet httpGet = new HttpGet("https://postman-echo.com/get"); URI uri = new URIBuilder(httpGet.getUri()).addParameter("param1", "value1") .addParameter("param2", "value2") .build(); httpGet.setUri(uri); - response = client.execute(httpGet); - assertThat(response.getCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpGet, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public void givenStringNameValuePairParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { + void givenStringNameValuePairParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { HttpPost httpPost = new HttpPost("https://postman-echo.com/post"); URI uri = new URIBuilder(httpPost.getUri()).addParameter("param1", "value1") .addParameter("param2", "value2") .build(); httpPost.setUri(uri); - response = client.execute(httpPost); - assertThat(response.getCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpPost, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public void givenNameValuePairParams_whenGetRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { + void givenNameValuePairParams_whenGetRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { HttpGet httpGet = new HttpGet("https://postman-echo.com/get"); URI uri = new URIBuilder(httpGet.getUri()).addParameters(nameValuePairs) .build(); httpGet.setUri(uri); - response = client.execute(httpGet); - assertThat(response.getCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpGet, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public void givenNameValuePairsParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { + void givenNameValuePairsParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { HttpPost httpPost = new HttpPost("https://postman-echo.com/post"); URI uri = new URIBuilder(httpPost.getUri()).addParameters(nameValuePairs) .build(); httpPost.setUri(uri); - response = client.execute(httpPost); - assertThat(response.getCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpPost, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } @Test - public void givenUrlEncodedEntityParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { + void givenUrlEncodedEntityParams_whenPostRequest_thenResponseOk() throws URISyntaxException, ClientProtocolException, IOException { HttpPost httpPost = new HttpPost("https://postman-echo.com/post"); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, StandardCharsets.UTF_8)); - response = client.execute(httpPost); - assertThat(response.getCode(), equalTo(200)); - client.close(); + try (CloseableHttpClient client = HttpClients.createDefault(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(httpPost, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + assertThat(statusCode, equalTo(HttpStatus.SC_OK)); + } } } diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutLiveTest.java index ab80d5665f..f3d0a1c27f 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutLiveTest.java @@ -3,7 +3,6 @@ package com.baeldung.httpclient; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.Mockito.when; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpsClientSslLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpsClientSslLiveTest.java index 24ceab0069..54633ba932 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpsClientSslLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpsClientSslLiveTest.java @@ -1,7 +1,6 @@ package com.baeldung.httpclient; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.security.GeneralSecurityException; @@ -9,73 +8,50 @@ import java.security.GeneralSecurityException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLHandshakeException; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.ssl.NoopHostnameVerifier; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.conn.ssl.TrustStrategy; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.ssl.SSLContextBuilder; -import org.apache.http.ssl.SSLContexts; -import org.junit.Test; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.client5.http.io.HttpClientConnectionManager; +import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; +import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; +import org.apache.hc.client5.http.ssl.TrustSelfSignedStrategy; +import org.apache.hc.core5.http.HttpResponse; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.ssl.SSLContextBuilder; +import org.apache.hc.core5.ssl.SSLContexts; +import org.apache.hc.core5.ssl.TrustStrategy; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; +import org.junit.jupiter.api.Test; + +import com.baeldung.handler.CustomHttpClientResponseHandler; /** * This test requires a localhost server over HTTPS
* It should only be manually run, not part of the automated build * */ -public class HttpsClientSslLiveTest { +class HttpsClientSslLiveTest { // "https://localhost:8443/spring-security-rest-basic-auth/api/bars/1" // local // "https://mms.nw.ru/" // hosted private static final String HOST_WITH_SSL = "https://mms.nw.ru/"; - // tests - - @Test(expected = SSLHandshakeException.class) - public final void whenHttpsUrlIsConsumed_thenException() throws IOException { - final CloseableHttpClient httpClient = HttpClientBuilder.create() - .build(); - + @Test + void whenHttpsUrlIsConsumed_thenException() { final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); - final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine() - .getStatusCode(), equalTo(200)); + + assertThrows(SSLHandshakeException.class, () -> { + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpResponse response = httpClient.execute(getMethod, new CustomHttpClientResponseHandler()); + MatcherAssert.assertThat(response.getCode(), Matchers.equalTo(200)); + }); + } @Test - public final void givenHttpClientPre4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { - final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; - - final SSLContext sslContext = SSLContexts.custom() - .loadTrustMaterial(null, acceptingTrustStrategy) - .build(); - - final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); - Registry socketFactoryRegistry = RegistryBuilder. create().register("https", sslsf).build(); - PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); - - final CloseableHttpClient httpClient = HttpClients.custom() - .setSSLSocketFactory(sslsf) - .setConnectionManager(clientConnectionManager) - .build(); - - final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); - final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine() - .getStatusCode(), equalTo(200)); - - httpClient.close(); - } - - @Test - public final void givenHttpClientAfter4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { + void whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; final SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) @@ -83,55 +59,45 @@ public class HttpsClientSslLiveTest { final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); - final CloseableHttpClient httpClient = HttpClients.custom() + final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create() .setSSLSocketFactory(sslsf) .build(); final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); - final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine() - .getStatusCode(), equalTo(200)); + try (CloseableHttpClient client = HttpClients.custom() + .setConnectionManager(cm) + .build(); - httpClient.close(); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(getMethod, new CustomHttpClientResponseHandler())) { + + final int statusCode = response.getCode(); + MatcherAssert.assertThat(statusCode, Matchers.equalTo(HttpStatus.SC_OK)); + } } @Test - public final void givenHttpClientPost4_3_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { + void usingBuilder_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) .build(); final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier(); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); - final CloseableHttpClient httpClient = HttpClients.custom() - .setSSLHostnameVerifier(hostnameVerifier) + final HttpClientConnectionManager cm = PoolingHttpClientConnectionManagerBuilder.create() .setSSLSocketFactory(sslsf) .build(); - // new - final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); - final HttpResponse response = httpClient.execute(getMethod); - assertThat(response.getStatusLine() - .getStatusCode(), equalTo(200)); - httpClient.close(); - - } - - @Test - public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception { - final SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true) + try (CloseableHttpClient client = HttpClients.custom() + .setConnectionManager(cm) .build(); - final CloseableHttpClient client = HttpClients.custom() - .setSSLContext(sslContext) - .setSSLHostnameVerifier(new NoopHostnameVerifier()) - .build(); - final HttpGet httpGet = new HttpGet(HOST_WITH_SSL); - httpGet.setHeader("Accept", "application/xml"); + CloseableHttpResponse response = (CloseableHttpResponse) client + .execute(getMethod, new CustomHttpClientResponseHandler())) { - final HttpResponse response = client.execute(httpGet); - assertThat(response.getStatusLine() - .getStatusCode(), equalTo(200)); + final int statusCode = response.getCode(); + MatcherAssert.assertThat(statusCode, Matchers.equalTo(HttpStatus.SC_OK)); + } } } diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/base/HttpClientBasicLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/base/HttpClientBasicLiveTest.java index e05017ccdd..b850f2e8ba 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/base/HttpClientBasicLiveTest.java +++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/base/HttpClientBasicLiveTest.java @@ -19,12 +19,12 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; -public class HttpClientBasicLiveTest { +class HttpClientBasicLiveTest { private static final String SAMPLE_URL = "http://www.github.com"; @Test - public final void whenExecutingBasicGetRequest_thenNoExceptions() throws IOException { + void whenExecutingBasicGetRequest_thenNoExceptions() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); try (CloseableHttpClient client = HttpClientBuilder.create().build(); @@ -35,7 +35,7 @@ public class HttpClientBasicLiveTest { } @Test - public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { + void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); try (CloseableHttpClient client = HttpClientBuilder.create().build(); @@ -48,7 +48,7 @@ public class HttpClientBasicLiveTest { @Test - public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectMimeType() throws IOException { + void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectMimeType() throws IOException { final HttpGet request = new HttpGet(SAMPLE_URL); try (CloseableHttpClient client = HttpClientBuilder.create().build(); @@ -63,7 +63,7 @@ public class HttpClientBasicLiveTest { @Test - public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectBody() throws IOException, ParseException { + void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectBody() throws IOException, ParseException { final HttpGet request = new HttpGet(SAMPLE_URL); try (CloseableHttpClient client = HttpClientBuilder.create().build(); diff --git a/httpclient-simple/src/test/java/com/baeldung/test/LiveTestSuite.java b/httpclient-simple/src/test/java/com/baeldung/test/LiveTestSuite.java deleted file mode 100644 index c864349e02..0000000000 --- a/httpclient-simple/src/test/java/com/baeldung/test/LiveTestSuite.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.baeldung.test; - -import com.baeldung.client.ClientLiveTest; -import com.baeldung.client.RestClientLiveManualTest; -import org.junit.runner.RunWith; -import org.junit.runners.Suite; - -@RunWith(Suite.class) -@Suite.SuiteClasses({ -// @formatter:off - RestClientLiveManualTest.class - ,ClientLiveTest.class -}) // -public class LiveTestSuite { - -} diff --git a/httpclient4/.gitignore b/httpclient4/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/httpclient4/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/httpclient4/README.md b/httpclient4/README.md new file mode 100644 index 0000000000..08e04c511d --- /dev/null +++ b/httpclient4/README.md @@ -0,0 +1,13 @@ +## Apache HttpClient + +This module contains articles about Apache HttpClient 4.5 + +### Relevant Articles + +- [Apache HttpClient with SSL](https://www.baeldung.com/httpclient-ssl) +- [Apache HttpClient Timeout](https://www.baeldung.com/httpclient-timeout) + +### Running the Tests +To run the live tests, use the command: mvn clean install -Plive +This will start an embedded Jetty server on port 8082 using the Cargo plugin configured in the pom.xml file, +for the live Maven profile \ No newline at end of file diff --git a/httpclient4/pom.xml b/httpclient4/pom.xml new file mode 100644 index 0000000000..8f896283b3 --- /dev/null +++ b/httpclient4/pom.xml @@ -0,0 +1,291 @@ + + + 4.0.0 + httpclient4 + 0.1-SNAPSHOT + httpclient4 + war + + + com.baeldung + parent-spring-5 + 0.0.1-SNAPSHOT + ../parent-spring-5 + + + + + + org.springframework.security + spring-security-web + ${spring-security.version} + + + org.springframework.security + spring-security-config + ${spring-security.version} + + + + org.springframework + spring-core + ${spring.version} + + + commons-logging + commons-logging + + + + + org.springframework + spring-context + ${spring.version} + + + org.springframework + spring-jdbc + ${spring.version} + + + org.springframework + spring-beans + ${spring.version} + + + org.springframework + spring-aop + ${spring.version} + + + org.springframework + spring-tx + ${spring.version} + + + org.springframework + spring-expression + ${spring.version} + + + org.springframework + spring-web + ${spring.version} + + + org.springframework + spring-webmvc + ${spring.version} + + + org.springframework + spring-oxm + ${spring.version} + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + + + commons-logging + commons-logging + + + + + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + commons-logging + commons-logging + + + + + org.apache.httpcomponents + fluent-hc + ${httpclient.version} + + + commons-logging + commons-logging + + + + + org.apache.httpcomponents + httpmime + ${httpclient.version} + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.apache.httpcomponents + httpasyncclient + ${httpasyncclient.version} + + + commons-logging + commons-logging + + + + + com.github.tomakehurst + wiremock + ${wiremock.version} + test + + + + javax.servlet + javax.servlet-api + ${javax.servlet-api.version} + provided + + + javax.servlet + jstl + ${jstl.version} + runtime + + + + com.google.guava + guava + ${guava.version} + + + + org.springframework + spring-test + ${spring.version} + test + + + + + httpclient-simple + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-war-plugin + ${maven-war-plugin.version} + + + org.codehaus.cargo + cargo-maven2-plugin + ${cargo-maven2-plugin.version} + + true + + jetty8x + embedded + + + + + + + 8082 + + + + + + + + + + live + + + + org.codehaus.cargo + cargo-maven2-plugin + + + start-server + pre-integration-test + + start + + + + stop-server + post-integration-test + + stop + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + none + + + **/*LiveTest.java + + + cargo + + + + + + + + + + + + + 1.10 + 4.1.5 + + 2.5.1 + 4.4.16 + 4.5.14 + + 1.6.1 + + + \ No newline at end of file diff --git a/httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java new file mode 100644 index 0000000000..cafd8cfb7b --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java @@ -0,0 +1,30 @@ +package com.baeldung.basic; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +@Component +public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint { + + @Override + public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException { + response.addHeader("WWW-Authenticate", "Basic realm=\"" + getRealmName() + "\""); + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + final PrintWriter writer = response.getWriter(); + writer.println("HTTP Status " + HttpServletResponse.SC_UNAUTHORIZED + " - " + authException.getMessage()); + } + + @Override + public void afterPropertiesSet() { + setRealmName("Baeldung"); + super.afterPropertiesSet(); + } + +} diff --git a/httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java new file mode 100644 index 0000000000..81f82a2c1c --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java @@ -0,0 +1,39 @@ +package com.baeldung.client; + +import java.net.URI; + +import org.apache.http.HttpHost; +import org.apache.http.client.AuthCache; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.impl.auth.BasicScheme; +import org.apache.http.impl.client.BasicAuthCache; +import org.apache.http.protocol.BasicHttpContext; +import org.apache.http.protocol.HttpContext; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; + +public class HttpComponentsClientHttpRequestFactoryBasicAuth extends HttpComponentsClientHttpRequestFactory { + + HttpHost host; + + public HttpComponentsClientHttpRequestFactoryBasicAuth(HttpHost host) { + super(); + this.host = host; + } + + protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { + return createHttpContext(); + } + + private HttpContext createHttpContext() { + + AuthCache authCache = new BasicAuthCache(); + + BasicScheme basicAuth = new BasicScheme(); + authCache.put(host, basicAuth); + + BasicHttpContext localcontext = new BasicHttpContext(); + localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); + return localcontext; + } +} \ No newline at end of file diff --git a/httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java b/httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java new file mode 100644 index 0000000000..aac4f8cebd --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java @@ -0,0 +1,44 @@ +package com.baeldung.client; + +import org.apache.http.HttpHost; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.http.client.ClientHttpRequestFactory; +import org.springframework.http.client.support.BasicAuthenticationInterceptor; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +@Component +public class RestTemplateFactory implements FactoryBean, InitializingBean { + private RestTemplate restTemplate; + + public RestTemplateFactory() { + super(); + } + + // API + + @Override + public RestTemplate getObject() { + return restTemplate; + } + + @Override + public Class getObjectType() { + return RestTemplate.class; + } + + @Override + public boolean isSingleton() { + return true; + } + + @Override + public void afterPropertiesSet() { + HttpHost host = new HttpHost("localhost", 8082, "http"); + final ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactoryBasicAuth(host); + restTemplate = new RestTemplate(requestFactory); + restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("user1", "user1Pass")); + } + +} \ No newline at end of file diff --git a/httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java b/httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java new file mode 100644 index 0000000000..03994b55a5 --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.client.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.client") +public class ClientConfig { + + public ClientConfig() { + super(); + } + + // beans + +} \ No newline at end of file diff --git a/httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java b/httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java new file mode 100644 index 0000000000..6bb12610fa --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java @@ -0,0 +1,18 @@ +package com.baeldung.filter; + +import org.springframework.web.filter.GenericFilterBean; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import java.io.IOException; + +public class CustomFilter extends GenericFilterBean { + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + chain.doFilter(request, response); + } + +} diff --git a/httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java new file mode 100644 index 0000000000..fb597e46c8 --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java @@ -0,0 +1,49 @@ +package com.baeldung.filter; + +import com.baeldung.security.RestAuthenticationEntryPoint; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; + +@Configuration +@EnableWebSecurity +public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { + + @Autowired private RestAuthenticationEntryPoint authenticationEntryPoint; + + @Autowired + public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { + auth + .inMemoryAuthentication() + .withUser("user1") + .password(passwordEncoder().encode("user1Pass")) + .authorities("ROLE_USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .authorizeRequests() + .antMatchers("/securityNone") + .permitAll() + .anyRequest() + .authenticated() + .and() + .httpBasic() + .authenticationEntryPoint(authenticationEntryPoint); + + http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java new file mode 100644 index 0000000000..7dc53e3e1e --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java @@ -0,0 +1,48 @@ +package com.baeldung.security; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.core.Authentication; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; +import org.springframework.security.web.savedrequest.HttpSessionRequestCache; +import org.springframework.security.web.savedrequest.RequestCache; +import org.springframework.security.web.savedrequest.SavedRequest; +import org.springframework.util.StringUtils; + +public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { + + private RequestCache requestCache = new HttpSessionRequestCache(); + + @Override + public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws ServletException, IOException { + final SavedRequest savedRequest = requestCache.getRequest(request, response); + + if (savedRequest == null) { + super.onAuthenticationSuccess(request, response, authentication); + + return; + } + final String targetUrlParameter = getTargetUrlParameter(); + if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) { + requestCache.removeRequest(request, response); + super.onAuthenticationSuccess(request, response, authentication); + + return; + } + + clearAuthenticationAttributes(request); + + // Use the DefaultSavedRequest URL + // final String targetUrl = savedRequest.getRedirectUrl(); + // logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl); + // getRedirectStrategy().sendRedirect(request, response, targetUrl); + } + + public void setRequestCache(final RequestCache requestCache) { + this.requestCache = requestCache; + } +} diff --git a/httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java b/httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java new file mode 100644 index 0000000000..1ae89adb89 --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java @@ -0,0 +1,23 @@ +package com.baeldung.security; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.AuthenticationEntryPoint; +import org.springframework.stereotype.Component; + +/** + * The Entry Point will not redirect to any sort of Login - it will return the 401 + */ +@Component +public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { + + @Override + public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException { + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); + } + +} \ No newline at end of file diff --git a/httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java new file mode 100644 index 0000000000..4ba9d47f8d --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.spring; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.ImportResource; + +@Configuration +@ImportResource({ "classpath:webSecurityConfig.xml" }) +@ComponentScan("com.baeldung.security") +public class SecSecurityConfig { + + public SecSecurityConfig() { + super(); + } + +} diff --git a/httpclient4/src/main/java/com/baeldung/spring/WebConfig.java b/httpclient4/src/main/java/com/baeldung/spring/WebConfig.java new file mode 100644 index 0000000000..8d5c1dc7f1 --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/spring/WebConfig.java @@ -0,0 +1,30 @@ +package com.baeldung.spring; + +import java.util.List; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +@EnableWebMvc +@ComponentScan("com.baeldung.web") +public class WebConfig implements WebMvcConfigurer { + + public WebConfig() { + super(); + } + + // beans + + @Override + public void configureMessageConverters(final List> converters) { + converters.add(new MappingJackson2HttpMessageConverter()); + } + + // + +} \ No newline at end of file diff --git a/httpclient4/src/main/java/com/baeldung/web/controller/BarController.java b/httpclient4/src/main/java/com/baeldung/web/controller/BarController.java new file mode 100644 index 0000000000..02e6af03af --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/web/controller/BarController.java @@ -0,0 +1,31 @@ +package com.baeldung.web.controller; + +import com.baeldung.web.dto.Bar; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping(value = "/bars") +public class BarController { + + @Autowired + private ApplicationEventPublisher eventPublisher; + + public BarController() { + super(); + } + + // API + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + public Bar findOne(@PathVariable("id") final Long id) { + return new Bar(); + } + +} diff --git a/httpclient4/src/main/java/com/baeldung/web/controller/FooController.java b/httpclient4/src/main/java/com/baeldung/web/controller/FooController.java new file mode 100644 index 0000000000..461a5e351a --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/web/controller/FooController.java @@ -0,0 +1,33 @@ +package com.baeldung.web.controller; + +import com.baeldung.web.dto.Foo; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping(value = "/foos") +public class FooController { + + @Autowired + private ApplicationEventPublisher eventPublisher; + + public FooController() { + super(); + } + + // API + + @RequestMapping(value = "/{id}", method = RequestMethod.GET) + @ResponseBody + @PreAuthorize("hasRole('ROLE_USER')") + public Foo findOne(@PathVariable("id") final Long id) { + return new Foo(); + } + +} diff --git a/httpclient4/src/main/java/com/baeldung/web/dto/Bar.java b/httpclient4/src/main/java/com/baeldung/web/dto/Bar.java new file mode 100644 index 0000000000..eb139b0ec1 --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/web/dto/Bar.java @@ -0,0 +1,14 @@ +package com.baeldung.web.dto; + +import java.io.Serializable; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Bar implements Serializable { + + public Bar() { + super(); + } + +} diff --git a/httpclient4/src/main/java/com/baeldung/web/dto/Foo.java b/httpclient4/src/main/java/com/baeldung/web/dto/Foo.java new file mode 100644 index 0000000000..23cfab132d --- /dev/null +++ b/httpclient4/src/main/java/com/baeldung/web/dto/Foo.java @@ -0,0 +1,14 @@ +package com.baeldung.web.dto; + +import java.io.Serializable; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class Foo implements Serializable { + + public Foo() { + super(); + } + +} diff --git a/httpclient4/src/main/resources/logback.xml b/httpclient4/src/main/resources/logback.xml new file mode 100644 index 0000000000..56af2d397e --- /dev/null +++ b/httpclient4/src/main/resources/logback.xml @@ -0,0 +1,19 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + \ No newline at end of file diff --git a/httpclient4/src/main/resources/webSecurityConfig.xml b/httpclient4/src/main/resources/webSecurityConfig.xml new file mode 100644 index 0000000000..2ff9a1de15 --- /dev/null +++ b/httpclient4/src/main/resources/webSecurityConfig.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/httpclient4/src/main/webapp/WEB-INF/api-servlet.xml b/httpclient4/src/main/webapp/WEB-INF/api-servlet.xml new file mode 100644 index 0000000000..1dbff70b83 --- /dev/null +++ b/httpclient4/src/main/webapp/WEB-INF/api-servlet.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/httpclient4/src/main/webapp/WEB-INF/web.xml b/httpclient4/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..4b2dd54266 --- /dev/null +++ b/httpclient4/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,43 @@ + + + + Spring Security Custom Application + + + + contextClass + org.springframework.web.context.support.AnnotationConfigWebApplicationContext + + + contextConfigLocation + com.baeldung.spring + + + + org.springframework.web.context.ContextLoaderListener + + + + + api + org.springframework.web.servlet.DispatcherServlet + 1 + + + api + /api/* + + + + + springSecurityFilterChain + org.springframework.web.filter.DelegatingFilterProxy + + + springSecurityFilterChain + /* + + + \ No newline at end of file diff --git a/httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java b/httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java new file mode 100644 index 0000000000..2785bc5d08 --- /dev/null +++ b/httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java @@ -0,0 +1,99 @@ +package com.baeldung.client; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLPeerUnverifiedException; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustStrategy; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.BasicHttpClientConnectionManager; +import org.apache.http.ssl.SSLContexts; + +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + + +class ClientLiveTest { + + final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1"; + + @Test + void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException { + + final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true; + final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); + final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); + final Registry socketFactoryRegistry = RegistryBuilder. create() + .register("https", sslsf) + .register("http", new PlainConnectionSocketFactory()) + .build(); + + final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry); + final CloseableHttpClient httpClient = HttpClients.custom() + .setSSLSocketFactory(sslsf) + .setConnectionManager(connectionManager) + .build(); + + final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); + assertThat(response.getStatusCode().value(), equalTo(200)); + } + + @Test + void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException { + final HttpGet getMethod = new HttpGet(urlOverHttps); + + try (final CloseableHttpClient httpClient = HttpClients.custom() + .setSSLHostnameVerifier(new NoopHostnameVerifier()) + .build()) { + + final HttpResponse response = httpClient.execute(getMethod); + assertThat(response.getStatusLine() + .getStatusCode(), equalTo(200)); + } + } + + @Test + void givenAcceptingAllCertificates_whenUsingRestTemplate_thenCorrect() { + final CloseableHttpClient httpClient = HttpClients.custom() + .setSSLHostnameVerifier(new NoopHostnameVerifier()) + .build(); + final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); + requestFactory.setHttpClient(httpClient); + + final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); + assertThat(response.getStatusCode().value(), equalTo(200)); + } + + @Test + void whenHttpsUrlIsConsumed_thenException() { + String urlOverHttps = "https://localhost:8082/httpclient-simple"; + HttpGet getMethod = new HttpGet(urlOverHttps); + + assertThrows(SSLPeerUnverifiedException.class, () -> { + CloseableHttpClient httpClient = HttpClients.createDefault(); + HttpResponse response = httpClient.execute(getMethod); + assertThat(response.getStatusLine() + .getStatusCode(), equalTo(200)); + }); + } +} \ No newline at end of file diff --git a/httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java b/httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java new file mode 100644 index 0000000000..c336e6a068 --- /dev/null +++ b/httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java @@ -0,0 +1,92 @@ +package com.baeldung.client; + +import static org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +import javax.net.ssl.SSLContext; + + +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; + +import org.apache.http.conn.ssl.TrustStrategy; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.BasicHttpClientConnectionManager; +import org.apache.http.ssl.SSLContexts; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +/** + * This test requires a localhost server over HTTPS
+ * It should only be manually run, not part of the automated build + * */ +public class RestClientV4LiveManualTest { + + final String urlOverHttps = "http://localhost:8082/httpclient-simple/api/bars/1"; + + @Test + void givenAcceptingAllCertificates_whenHttpsUrlIsConsumed_thenOk_2() throws GeneralSecurityException { + + final TrustStrategy acceptingTrustStrategy = (cert, authType) -> true; + final SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); + final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); + final Registry socketFactoryRegistry = RegistryBuilder. create() + .register("https", sslsf) + .register("http", new PlainConnectionSocketFactory()) + .build(); + + final BasicHttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry); + final CloseableHttpClient httpClient = HttpClients.custom() + .setSSLSocketFactory(sslsf) + .setConnectionManager(connectionManager) + .build(); + + final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); + final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); + assertThat(response.getStatusCode().value(), equalTo(200)); + } + + @Test + void givenAcceptingAllCertificatesUsing4_4_whenHttpsUrlIsConsumed_thenCorrect() throws IOException { + final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + + final HttpGet getMethod = new HttpGet(urlOverHttps); + final HttpResponse response = httpClient.execute(getMethod); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + } + + @Test + void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect(){ + final CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); + final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); + requestFactory.setHttpClient(httpClient); + + final ResponseEntity response = new RestTemplate(requestFactory).exchange(urlOverHttps, HttpMethod.GET, null, String.class); + assertThat(response.getStatusCode().value(), equalTo(200)); + } + + @Test + public void whenHttpsUrlIsConsumed_thenException() throws ClientProtocolException, IOException { + CloseableHttpClient httpClient = HttpClients.createDefault(); + String urlOverHttps = "https://localhost:8082/httpclient-simple"; + HttpGet getMethod = new HttpGet(urlOverHttps); + HttpResponse response = httpClient.execute(getMethod); + assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); + } +} diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java b/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java new file mode 100644 index 0000000000..eef813b3ff --- /dev/null +++ b/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java @@ -0,0 +1,24 @@ +package com.baeldung.httpclient; + +import java.io.IOException; +import org.apache.http.HttpHeaders; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.client.methods.RequestBuilder; +import org.apache.http.impl.client.HttpClients; +import org.junit.jupiter.api.Test; + +class HttpClientHeaderV4LiveTest { + + private static final String SAMPLE_URL = "http://www.github.com"; + + @Test + void givenRequestBuildWithBuilder_whenRequestHasCustomContentType_thenCorrect() throws IOException { + HttpClient client = HttpClients.custom().build(); + HttpUriRequest request = RequestBuilder.get() + .setUri(SAMPLE_URL) + .setHeader(HttpHeaders.CONTENT_TYPE, "application/json") + .build(); + client.execute(request); + } +} \ No newline at end of file diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java b/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java similarity index 97% rename from httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java rename to httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java index 9bf523590e..4d4dd7be15 100644 --- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java +++ b/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java @@ -76,7 +76,7 @@ class HttpClientTimeoutV4LiveTest { */ @Test @Disabled - public final void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException { + void givenTimeoutIsConfigured_whenTimingOut_thenTimeoutException() throws IOException { final int timeout = 3; final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java b/httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java new file mode 100644 index 0000000000..6c7bcf9b08 --- /dev/null +++ b/httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java @@ -0,0 +1,111 @@ +package com.baeldung.httpclient; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.conn.ssl.NoopHostnameVerifier; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.conn.ssl.TrustStrategy; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; + +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.SSLContexts; +import org.junit.jupiter.api.Test; + +class HttpsClientV4SslLiveTest { + + + // "https://localhost:8443/spring-security-rest-basic-auth/api/bars/1" // local + // "https://mms.nw.ru/" // hosted + private static final String HOST_WITH_SSL = "https://mms.nw.ru/"; + + // tests + + @Test + void whenHttpsUrlIsConsumed_thenException() { + final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); + + assertThrows(SSLHandshakeException.class, () -> { + final CloseableHttpClient httpClient = HttpClientBuilder + .create() + .build(); + final HttpResponse response = httpClient.execute(getMethod); + assertThat(response.getStatusLine() + .getStatusCode(), equalTo(200)); + }); + } + + + @Test + void whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { + final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true; + final SSLContext sslContext = SSLContexts.custom() + .loadTrustMaterial(null, acceptingTrustStrategy) + .build(); + + final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); + + final CloseableHttpClient httpClient = HttpClients.custom() + .setSSLSocketFactory(sslsf) + .build(); + + final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); + final HttpResponse response = httpClient.execute(getMethod); + assertThat(response.getStatusLine() + .getStatusCode(), equalTo(200)); + + httpClient.close(); + } + + @Test + void using_builder_whenAcceptingAllCertificates_thenCanConsumeHttpsUriWithSelfSignedCertificate() throws IOException, GeneralSecurityException { + final SSLContext sslContext = new SSLContextBuilder() + .loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .build(); + final NoopHostnameVerifier hostnameVerifier = new NoopHostnameVerifier(); + + final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); + final CloseableHttpClient httpClient = HttpClients.custom() + .setSSLHostnameVerifier(hostnameVerifier) + .setSSLSocketFactory(sslsf) + .build(); + + final HttpGet getMethod = new HttpGet(HOST_WITH_SSL); + final HttpResponse response = httpClient.execute(getMethod); + assertThat(response.getStatusLine() + .getStatusCode(), equalTo(200)); + httpClient.close(); + + } + + @Test + void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws Exception { + final SSLContext sslContext = new SSLContextBuilder() + .loadTrustMaterial(null, (certificate, authType) -> true) + .build(); + + final CloseableHttpClient client = HttpClients.custom() + .setSSLContext(sslContext) + .setSSLHostnameVerifier(new NoopHostnameVerifier()) + .build(); + final HttpGet httpGet = new HttpGet(HOST_WITH_SSL); + httpGet.setHeader("Accept", "application/xml"); + + final HttpResponse response = client.execute(httpGet); + assertThat(response.getStatusLine() + .getStatusCode(), equalTo(200)); + } + +} \ No newline at end of file diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/ResponseUtil.java b/httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java similarity index 100% rename from httpclient-simple/src/test/java/com/baeldung/httpclient/ResponseUtil.java rename to httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java diff --git a/httpclient4/src/test/resources/.gitignore b/httpclient4/src/test/resources/.gitignore new file mode 100644 index 0000000000..83c05e60c8 --- /dev/null +++ b/httpclient4/src/test/resources/.gitignore @@ -0,0 +1,13 @@ +*.class + +#folders# +/target +/neoDb* +/data +/src/main/webapp/WEB-INF/classes +*/META-INF/* + +# Packaged files # +*.jar +*.war +*.ear \ No newline at end of file diff --git a/httpclient4/src/test/resources/test.in b/httpclient4/src/test/resources/test.in new file mode 100644 index 0000000000..95d09f2b10 --- /dev/null +++ b/httpclient4/src/test/resources/test.in @@ -0,0 +1 @@ +hello world \ No newline at end of file diff --git a/pom.xml b/pom.xml index 05f8326e4c..4016d669a4 100644 --- a/pom.xml +++ b/pom.xml @@ -365,7 +365,7 @@ apache-httpclient - httpclient-simple + httpclient4 jackson-modules @@ -648,7 +648,7 @@ apache-httpclient - httpclient-simple + httpclient4 jackson-modules @@ -976,6 +976,7 @@ akka-modules annotations apache-httpclient + httpclient-simple antlr apache-kafka apache-kafka-2 @@ -1201,6 +1202,7 @@ graphql-modules grpc hazelcast + httpclient-simple hystrix jackson-simple java-blockchain From 0be934a8e8331b0b892fdfbaab2a4a96f214bf17 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Tue, 7 Feb 2023 15:51:29 +0000 Subject: [PATCH 047/113] [JAVA-12714] Removed compiler plugin (#13420) Co-authored-by: panagiotiskakos --- java-websocket/pom.xml | 9 --------- libraries-server-2/pom.xml | 4 ---- spring-di/pom.xml | 4 ---- spring-exceptions/pom.xml | 4 ---- spring-katharsis/pom.xml | 4 ---- spring-mobile/pom.xml | 9 --------- vaadin/pom.xml | 4 ---- 7 files changed, 38 deletions(-) diff --git a/java-websocket/pom.xml b/java-websocket/pom.xml index 7c3f32b092..ffc2b0631e 100644 --- a/java-websocket/pom.xml +++ b/java-websocket/pom.xml @@ -28,15 +28,6 @@ - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - 1.1 2.8.0 diff --git a/libraries-server-2/pom.xml b/libraries-server-2/pom.xml index 359954a6d2..7377fa3fa9 100644 --- a/libraries-server-2/pom.xml +++ b/libraries-server-2/pom.xml @@ -34,10 +34,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - org.eclipse.jetty jetty-maven-plugin diff --git a/spring-di/pom.xml b/spring-di/pom.xml index 9d2a260a06..af0601deb6 100644 --- a/spring-di/pom.xml +++ b/spring-di/pom.xml @@ -111,10 +111,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - org.apache.maven.plugins maven-war-plugin diff --git a/spring-exceptions/pom.xml b/spring-exceptions/pom.xml index 6d573b6813..0621009bdd 100644 --- a/spring-exceptions/pom.xml +++ b/spring-exceptions/pom.xml @@ -144,10 +144,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - org.apache.maven.plugins maven-war-plugin diff --git a/spring-katharsis/pom.xml b/spring-katharsis/pom.xml index 2fcc87e2dd..b836a42bca 100644 --- a/spring-katharsis/pom.xml +++ b/spring-katharsis/pom.xml @@ -55,10 +55,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - org.codehaus.cargo cargo-maven2-plugin diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index bac1d2cdc9..7f715c8735 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -32,15 +32,6 @@ - - - - org.apache.maven.plugins - maven-compiler-plugin - - - - 1.1.5.RELEASE diff --git a/vaadin/pom.xml b/vaadin/pom.xml index 82963f9e7f..aa37a2392a 100644 --- a/vaadin/pom.xml +++ b/vaadin/pom.xml @@ -76,10 +76,6 @@ - - org.apache.maven.plugins - maven-compiler-plugin - org.apache.maven.plugins maven-war-plugin From 5fcfdf1a7dbf34a81f33340e36e67db7168b2ab5 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Tue, 7 Feb 2023 23:21:05 +0530 Subject: [PATCH 048/113] Update README.md (#13444) --- httpclient4/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/httpclient4/README.md b/httpclient4/README.md index 08e04c511d..445db1108b 100644 --- a/httpclient4/README.md +++ b/httpclient4/README.md @@ -6,8 +6,9 @@ This module contains articles about Apache HttpClient 4.5 - [Apache HttpClient with SSL](https://www.baeldung.com/httpclient-ssl) - [Apache HttpClient Timeout](https://www.baeldung.com/httpclient-timeout) +- [Custom HTTP Header with the Apache HttpClient](https://www.baeldung.com/httpclient-custom-http-header) ### Running the Tests To run the live tests, use the command: mvn clean install -Plive This will start an embedded Jetty server on port 8082 using the Cargo plugin configured in the pom.xml file, -for the live Maven profile \ No newline at end of file +for the live Maven profile From 424f295eddbea68097b8a905bcf92754cba17f47 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Wed, 8 Feb 2023 01:49:49 +0100 Subject: [PATCH 049/113] =?UTF-8?q?[streamOf-vs-intStreamRange]=20Understa?= =?UTF-8?q?nding=20the=20Difference=20Between=20Str=E2=80=A6=20(#13429)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [streamOf-vs-intStreamRange] Understanding the Difference Between Stream.of and IntStream.range * [streamOf-vs-intStreamRange] fix indent --- ...weenStreamOfAndIntStreamRangeUnitTest.java | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/streamofvsintstream/DiffBetweenStreamOfAndIntStreamRangeUnitTest.java diff --git a/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/streamofvsintstream/DiffBetweenStreamOfAndIntStreamRangeUnitTest.java b/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/streamofvsintstream/DiffBetweenStreamOfAndIntStreamRangeUnitTest.java new file mode 100644 index 0000000000..23957fe2c6 --- /dev/null +++ b/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/streamofvsintstream/DiffBetweenStreamOfAndIntStreamRangeUnitTest.java @@ -0,0 +1,66 @@ +package com.baeldung.streams.streamofvsintstream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; + +public class DiffBetweenStreamOfAndIntStreamRangeUnitTest { + @Test + void givenStreamOfAndIntStreamRange_whenPeekSortAndFirst_shouldResultDifferent() { + Stream normalStream = Stream.of(1, 2, 3, 4, 5); + IntStream intStreamByRange = IntStream.range(1, 6); + List normalStreamPeekResult = new ArrayList<>(); + List intStreamPeekResult = new ArrayList<>(); + + // First, the regular Stream + normalStream.peek(normalStreamPeekResult::add) + .sorted() + .findFirst(); + assertEquals(Arrays.asList(1, 2, 3, 4, 5), normalStreamPeekResult); + + // Then, the IntStream + intStreamByRange.peek(intStreamPeekResult::add) + .sorted() + .findFirst(); + assertEquals(Arrays.asList(1), intStreamPeekResult); + } + + @Test + void givenStream_whenPeekAndFirst_shouldHaveOnlyFirstElement() { + Stream normalStream = Stream.of(1, 2, 3, 4, 5); + IntStream intStreamByRange = IntStream.range(1, 6); + List normalStreamPeekResult = new ArrayList<>(); + List intStreamPeekResult = new ArrayList<>(); + + // First, the regular Stream + normalStream.peek(normalStreamPeekResult::add) + .findFirst(); + assertEquals(Arrays.asList(1), normalStreamPeekResult); + + // Then, the IntStream + intStreamByRange.peek(intStreamPeekResult::add) + .findFirst(); + assertEquals(Arrays.asList(1), intStreamPeekResult); + } + + @Test + void givenSortedStream_whenPeekSortAndFirst_shouldOnlyHaveOneElement() { + List peekResult = new ArrayList<>(); + + TreeSet treeSet = new TreeSet<>(Arrays.asList("CCC", "BBB", "AAA", "DDD", "KKK")); + + treeSet.stream() + .peek(peekResult::add) + .sorted() + .findFirst(); + + assertEquals(Arrays.asList("AAA"), peekResult); + } +} \ No newline at end of file From 633b9850b090d19886c22c2af6f9a2fe82915281 Mon Sep 17 00:00:00 2001 From: apeterlic Date: Wed, 8 Feb 2023 14:18:42 +0100 Subject: [PATCH 050/113] BAEL-5864 - Getting the Current ApplicationContext in Spring (#13433) --- .../ApplicationContextProvider.java | 20 ++++++++++++ .../applicationcontext/ItemService.java | 11 +++++++ .../baeldung/applicationcontext/MyBean.java | 17 ++++++++++ .../ApplicationContextProviderUnitTest.java | 32 +++++++++++++++++++ .../applicationcontext/MyBeanUnitTest.java | 28 ++++++++++++++++ .../applicationcontext/TestContextConfig.java | 11 +++++++ 6 files changed, 119 insertions(+) create mode 100644 spring-core-6/src/main/java/com/baeldung/applicationcontext/ApplicationContextProvider.java create mode 100644 spring-core-6/src/main/java/com/baeldung/applicationcontext/ItemService.java create mode 100644 spring-core-6/src/main/java/com/baeldung/applicationcontext/MyBean.java create mode 100644 spring-core-6/src/test/java/com/baeldung/applicationcontext/ApplicationContextProviderUnitTest.java create mode 100644 spring-core-6/src/test/java/com/baeldung/applicationcontext/MyBeanUnitTest.java create mode 100644 spring-core-6/src/test/java/com/baeldung/applicationcontext/TestContextConfig.java diff --git a/spring-core-6/src/main/java/com/baeldung/applicationcontext/ApplicationContextProvider.java b/spring-core-6/src/main/java/com/baeldung/applicationcontext/ApplicationContextProvider.java new file mode 100644 index 0000000000..260620ff48 --- /dev/null +++ b/spring-core-6/src/main/java/com/baeldung/applicationcontext/ApplicationContextProvider.java @@ -0,0 +1,20 @@ +package com.baeldung.applicationcontext; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +@Component +public class ApplicationContextProvider implements ApplicationContextAware { + private static ApplicationContext applicationContext; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + ApplicationContextProvider.applicationContext = applicationContext; + } + + public static ApplicationContext getApplicationContext() { + return applicationContext; + } +} \ No newline at end of file diff --git a/spring-core-6/src/main/java/com/baeldung/applicationcontext/ItemService.java b/spring-core-6/src/main/java/com/baeldung/applicationcontext/ItemService.java new file mode 100644 index 0000000000..344ea3af0f --- /dev/null +++ b/spring-core-6/src/main/java/com/baeldung/applicationcontext/ItemService.java @@ -0,0 +1,11 @@ +package com.baeldung.applicationcontext; + +import org.springframework.stereotype.Service; + +@Service +public class ItemService { + + public String getItem(){ + return "New Item"; + } +} diff --git a/spring-core-6/src/main/java/com/baeldung/applicationcontext/MyBean.java b/spring-core-6/src/main/java/com/baeldung/applicationcontext/MyBean.java new file mode 100644 index 0000000000..95be3375c7 --- /dev/null +++ b/spring-core-6/src/main/java/com/baeldung/applicationcontext/MyBean.java @@ -0,0 +1,17 @@ +package com.baeldung.applicationcontext; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Component; + +@Component +public class MyBean { + + @Autowired + private ApplicationContext applicationContext; + + public ApplicationContext getApplicationContext() { + return applicationContext; + } + +} diff --git a/spring-core-6/src/test/java/com/baeldung/applicationcontext/ApplicationContextProviderUnitTest.java b/spring-core-6/src/test/java/com/baeldung/applicationcontext/ApplicationContextProviderUnitTest.java new file mode 100644 index 0000000000..3c3053e61c --- /dev/null +++ b/spring-core-6/src/test/java/com/baeldung/applicationcontext/ApplicationContextProviderUnitTest.java @@ -0,0 +1,32 @@ +package com.baeldung.applicationcontext; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@ContextConfiguration(classes = TestContextConfig.class) +@ExtendWith(SpringExtension.class) +class ApplicationContextProviderUnitTest { + + @Test + void whenGetApplicationContext_thenReturnApplicationContext() { + ApplicationContext context = ApplicationContextProvider.getApplicationContext(); + assertNotNull(context); + System.out.printf("ApplicationContext has %d beans %n", context.getBeanDefinitionCount()); + } + + @Test + void whenGetBean_thenReturnItemServiceReference() { + ApplicationContext context = ApplicationContextProvider.getApplicationContext(); + assertNotNull(context); + + ItemService itemService = context.getBean(ItemService.class); + assertNotNull(context); + + System.out.println(itemService.getItem()); + } +} \ No newline at end of file diff --git a/spring-core-6/src/test/java/com/baeldung/applicationcontext/MyBeanUnitTest.java b/spring-core-6/src/test/java/com/baeldung/applicationcontext/MyBeanUnitTest.java new file mode 100644 index 0000000000..bff04c2d20 --- /dev/null +++ b/spring-core-6/src/test/java/com/baeldung/applicationcontext/MyBeanUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.applicationcontext; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@ContextConfiguration(classes = TestContextConfig.class) +@ExtendWith(SpringExtension.class) +class MyBeanUnitTest { + + @Autowired + MyBean myBean; + + @Test + void whenGetApplicationContext_thenReturnApplicationContext() { + assertNotNull(myBean); + ApplicationContext context = myBean.getApplicationContext(); + assertNotNull(context); + + System.out.printf("ApplicationContext has %d beans %n", context.getBeanDefinitionCount()); + } + +} \ No newline at end of file diff --git a/spring-core-6/src/test/java/com/baeldung/applicationcontext/TestContextConfig.java b/spring-core-6/src/test/java/com/baeldung/applicationcontext/TestContextConfig.java new file mode 100644 index 0000000000..257500a00f --- /dev/null +++ b/spring-core-6/src/test/java/com/baeldung/applicationcontext/TestContextConfig.java @@ -0,0 +1,11 @@ +package com.baeldung.applicationcontext; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.applicationcontext") +public class TestContextConfig { + + +} From 847256f73841edc6c713aac5e770f31fec43e362 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Wed, 8 Feb 2023 18:17:09 +0200 Subject: [PATCH 051/113] JAVA-17333 Update Java Timer Article (#13423) * JAVA-17333 Update Java Timer Article * JAVA-17333 Rename the test class --------- Co-authored-by: timis1 --- .../main/java/com/baeldung/timer/NewsletterTask.java | 12 ++++++++++++ ...itTest.java => NewsletterTaskUnitManualTest.java} | 10 +++------- 2 files changed, 15 insertions(+), 7 deletions(-) rename core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/{NewsletterTaskUnitTest.java => NewsletterTaskUnitManualTest.java} (76%) diff --git a/core-java-modules/core-java-time-measurements/src/main/java/com/baeldung/timer/NewsletterTask.java b/core-java-modules/core-java-time-measurements/src/main/java/com/baeldung/timer/NewsletterTask.java index 16dd6c12ff..d99f7acea7 100644 --- a/core-java-modules/core-java-time-measurements/src/main/java/com/baeldung/timer/NewsletterTask.java +++ b/core-java-modules/core-java-time-measurements/src/main/java/com/baeldung/timer/NewsletterTask.java @@ -3,12 +3,24 @@ package com.baeldung.timer; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; +import java.util.Random; import java.util.TimerTask; +import java.util.concurrent.TimeUnit; public class NewsletterTask extends TimerTask { @Override public void run() { System.out.println("Email sent at: " + LocalDateTime.ofInstant(Instant.ofEpochMilli(scheduledExecutionTime()), ZoneId.systemDefault())); + Random random = new Random(); + int value = random.ints(1, 7) + .findFirst() + .getAsInt(); + System.out.println("The duration of sending the mail will took: " + value); + try { + TimeUnit.SECONDS.sleep(value); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } } } diff --git a/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitManualTest.java similarity index 76% rename from core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java rename to core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitManualTest.java index ffbe39c2bc..049fc3bf6d 100644 --- a/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitTest.java +++ b/core-java-modules/core-java-time-measurements/src/test/java/com/baeldung/timer/NewsletterTaskUnitManualTest.java @@ -5,7 +5,7 @@ import org.junit.jupiter.api.Test; import java.util.Timer; -class NewsletterTaskUnitTest { +class NewsletterTaskUnitManualTest { private final Timer timer = new Timer(); @AfterEach @@ -17,17 +17,13 @@ class NewsletterTaskUnitTest { void givenNewsletterTask_whenTimerScheduledEachSecondFixedDelay_thenNewsletterSentEachSecond() throws Exception { timer.schedule(new NewsletterTask(), 0, 1000); - for (int i = 0; i < 3; i++) { - Thread.sleep(1000); - } + Thread.sleep(20000); } @Test void givenNewsletterTask_whenTimerScheduledEachSecondFixedRate_thenNewsletterSentEachSecond() throws Exception { timer.scheduleAtFixedRate(new NewsletterTask(), 0, 1000); - for (int i = 0; i < 3; i++) { - Thread.sleep(1000); - } + Thread.sleep(20000); } } \ No newline at end of file From 0ede8fa526d045f7cc50e7e2de69776b88cfee68 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Wed, 8 Feb 2023 18:05:24 +0000 Subject: [PATCH 052/113] [JAVA-15024] Changed HttpMultipartMode from STRICT to LEGACY (#13446) Co-authored-by: panagiotiskakos --- .../com/baeldung/httpclient/HttpClientMultipartLiveTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java index b5ede3ed60..720049378b 100644 --- a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java +++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientMultipartLiveTest.java @@ -124,7 +124,7 @@ class HttpClientMultipartLiveTest { final File file = new File(url2.getPath()); final String message = "This is a multipart post"; final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.STRICT); + builder.setMode(HttpMultipartMode.LEGACY); builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, IMAGEFILENAME); builder.addBinaryBody("upstream", inputStream, ContentType.create("application/zip"), ZIPFILENAME); builder.addTextBody("text", message, ContentType.TEXT_PLAIN); @@ -153,7 +153,7 @@ class HttpClientMultipartLiveTest { final String message = "This is a multipart post"; final byte[] bytes = "binary code".getBytes(); final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.STRICT); + builder.setMode(HttpMultipartMode.LEGACY); builder.addBinaryBody("file", bytes, ContentType.DEFAULT_BINARY, TEXTFILENAME); builder.addTextBody("text", message, ContentType.TEXT_PLAIN); final HttpEntity entity = builder.build(); From 8ebfa6955443feff2950226e166848aaa0f9d5dc Mon Sep 17 00:00:00 2001 From: Dmitriy Budim <46810751+dbudim@users.noreply.github.com> Date: Wed, 8 Feb 2023 22:48:26 +0100 Subject: [PATCH 053/113] [Difference Between Class.forName() and Class.forName().newInstance()] sample code (#13451) --- .../baeldung/loadclass/MyClassForLoad.java | 8 +++++ .../baeldung/loadclass/LoadClassUnitTest.java | 30 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 core-java-modules/core-java/src/main/java/com/baeldung/loadclass/MyClassForLoad.java create mode 100644 core-java-modules/core-java/src/test/java/com/baeldung/loadclass/LoadClassUnitTest.java diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/loadclass/MyClassForLoad.java b/core-java-modules/core-java/src/main/java/com/baeldung/loadclass/MyClassForLoad.java new file mode 100644 index 0000000000..e97848fb1f --- /dev/null +++ b/core-java-modules/core-java/src/main/java/com/baeldung/loadclass/MyClassForLoad.java @@ -0,0 +1,8 @@ +package com.baeldung.loadclass; + + +public class MyClassForLoad { + + private String data = "some data"; + +} diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/loadclass/LoadClassUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/loadclass/LoadClassUnitTest.java new file mode 100644 index 0000000000..1f7eb139a2 --- /dev/null +++ b/core-java-modules/core-java/src/test/java/com/baeldung/loadclass/LoadClassUnitTest.java @@ -0,0 +1,30 @@ +package com.baeldung.loadclass; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.InvocationTargetException; + +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + + +public class LoadClassUnitTest { + + @Test + public void whenUseClassForName_createdInstanceOfClassClass() throws ClassNotFoundException { + Class instance = Class.forName("com.baeldung.loadclass.MyClassForLoad"); + assertInstanceOf(Class.class, instance, "instance should be of Class.class"); + } + + @Test + public void whenUseClassForNameWithNewInstance_createdInstanceOfTargetClas() throws ClassNotFoundException, InstantiationException, IllegalAccessException { + Object instance = Class.forName("com.baeldung.loadclass.MyClassForLoad").newInstance(); + assertInstanceOf(MyClassForLoad.class, instance, "instance should be of MyClassForLoad class"); + } + + @Test + public void whenUseClassForNameWithDeclaredConstructor_newInstanceCreatedInstanceOfTargetClas() throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { + Object instance = Class.forName("com.baeldung.loadclass.MyClassForLoad").getDeclaredConstructor().newInstance(); + assertInstanceOf(MyClassForLoad.class, instance, "instance should be of MyClassForLoad class"); + } + +} From 67e70c7e902fe45fb4c5c53a1acbfbae382df615 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 9 Feb 2023 07:13:07 +0800 Subject: [PATCH 054/113] Update README.md [skip ci] --- core-java-modules/core-java-collections-array-list/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-array-list/README.md b/core-java-modules/core-java-collections-array-list/README.md index 53568ca98a..e3d41d8f88 100644 --- a/core-java-modules/core-java-collections-array-list/README.md +++ b/core-java-modules/core-java-collections-array-list/README.md @@ -12,3 +12,4 @@ This module contains articles about the Java ArrayList collection - [Case-Insensitive Searching in ArrayList](https://www.baeldung.com/java-arraylist-case-insensitive-search) - [Storing Data Triple in a List in Java](https://www.baeldung.com/java-list-storing-triple) - [Convert an ArrayList of Object to an ArrayList of String Elements](https://www.baeldung.com/java-object-list-to-strings) +- [Initialize an ArrayList with Zeroes or Null in Java](https://www.baeldung.com/java-arraylist-with-zeroes-or-null) From 0d74a8052f2ba77e1380ad846e62ed651daa9bbf Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 9 Feb 2023 07:18:14 +0800 Subject: [PATCH 055/113] Update README.md [skip ci] --- core-java-modules/core-java-numbers-5/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-numbers-5/README.md b/core-java-modules/core-java-numbers-5/README.md index 34651c8e6c..fcc3d55dd9 100644 --- a/core-java-modules/core-java-numbers-5/README.md +++ b/core-java-modules/core-java-numbers-5/README.md @@ -8,3 +8,4 @@ - [Creating Random Numbers With No Duplicates in Java](https://www.baeldung.com/java-unique-random-numbers) - [Multiply a BigDecimal by an Integer in Java](https://www.baeldung.com/java-bigdecimal-multiply-integer) - [Check if an Integer Value is null or Zero in Java](https://www.baeldung.com/java-check-integer-null-or-zero) +- [Return Absolute Difference of Two Integers in Java](https://www.baeldung.com/java-absolute-difference-of-two-integers) From da75aee34863c89d974332132449b369b692347e Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 9 Feb 2023 07:21:16 +0800 Subject: [PATCH 056/113] Update README.md [skip ci] --- pdf/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/pdf/README.md b/pdf/README.md index dd6931ba78..2a9a23a804 100644 --- a/pdf/README.md +++ b/pdf/README.md @@ -8,3 +8,4 @@ This module contains articles about PDF files. - [Generating PDF Files Using Thymeleaf](https://www.baeldung.com/thymeleaf-generate-pdf) - [Java Convert PDF to Base64](https://www.baeldung.com/java-convert-pdf-to-base64) - [HTML to PDF Using OpenPDF](https://www.baeldung.com/java-html-to-pdf) +- [Reading PDF File Using Java](https://www.baeldung.com/java-pdf-file-read) From 24ddec2fb0a2cea369ecd47754cf6ff4e4cec2c5 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 9 Feb 2023 07:26:39 +0800 Subject: [PATCH 057/113] Update README.md [skip ci] --- testing-modules/junit-5-advanced/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/junit-5-advanced/README.md b/testing-modules/junit-5-advanced/README.md index 16509b75bf..9b3a5fa299 100644 --- a/testing-modules/junit-5-advanced/README.md +++ b/testing-modules/junit-5-advanced/README.md @@ -7,3 +7,4 @@ - [Run JUnit Test Cases From the Command Line](https://www.baeldung.com/junit-run-from-command-line) - [Parallel Test Execution for JUnit 5](https://www.baeldung.com/junit-5-parallel-tests) - [JUnit – Testing Methods That Call System.exit()](https://www.baeldung.com/junit-system-exit) +- [Single Assert Call for Multiple Properties in Java Unit Testing](https://www.baeldung.com/java-testing-single-assert-multiple-properties) From 3a156451cbdaf52326533e9cce9cf2fa225854e8 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 9 Feb 2023 07:31:37 +0800 Subject: [PATCH 058/113] Update README.md [skip ci] --- jmeter/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jmeter/README.md b/jmeter/README.md index 76d329342d..f01fa4eca5 100644 --- a/jmeter/README.md +++ b/jmeter/README.md @@ -55,3 +55,4 @@ Enjoy it :) - [Write Extracted Data to a File Using JMeter](https://www.baeldung.com/jmeter-write-to-file) - [Basic Authentication in JMeter](https://www.baeldung.com/jmeter-basic-auth) - [JMeter: Latency vs. Load Time](https://www.baeldung.com/java-jmeter-latency-vs-load-time) +- [How Do I Generate a Dashboard Report in JMeter?](https://www.baeldung.com/jmeter-dashboard-report) From 836c4154d710e95a339bfd3d34bc650224eb6c35 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 9 Feb 2023 07:51:27 +0800 Subject: [PATCH 059/113] Update README.md [skip ci] --- core-java-modules/core-java-networking-4/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-networking-4/README.md b/core-java-modules/core-java-networking-4/README.md index 5f0958fae0..daec647ebe 100644 --- a/core-java-modules/core-java-networking-4/README.md +++ b/core-java-modules/core-java-networking-4/README.md @@ -1,3 +1,4 @@ ## Relevant Articles: - [Difference Between URI.create() and new URI()](https://www.baeldung.com/java-uri-create-and-new-uri) -- [Validating URL in Java](https://www.baeldung.com/java-validate-url) \ No newline at end of file +- [Validating URL in Java](https://www.baeldung.com/java-validate-url) +- [Validating IPv4 Address in Java](https://www.baeldung.com/java-validate-ipv4-address) From e23d41530626019505537ad68ebe88240cc97afe Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 9 Feb 2023 07:54:56 +0800 Subject: [PATCH 060/113] Create README.md [skip ci] --- spring-cloud-modules/spring-cloud-open-telemetry/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 spring-cloud-modules/spring-cloud-open-telemetry/README.md diff --git a/spring-cloud-modules/spring-cloud-open-telemetry/README.md b/spring-cloud-modules/spring-cloud-open-telemetry/README.md new file mode 100644 index 0000000000..4a24159982 --- /dev/null +++ b/spring-cloud-modules/spring-cloud-open-telemetry/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [OpenTelemetry Setup in Spring Boot Application](https://www.baeldung.com/spring-boot-opentelemetry-setup) From 8b266833920dd0c564282d05e979c114ab5e9c3d Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Thu, 9 Feb 2023 08:01:56 +0800 Subject: [PATCH 061/113] Update README.md [skip ci] --- core-java-modules/core-java-streams-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-streams-4/README.md b/core-java-modules/core-java-streams-4/README.md index 8e5e0652ef..b0b42324d6 100644 --- a/core-java-modules/core-java-streams-4/README.md +++ b/core-java-modules/core-java-streams-4/README.md @@ -7,3 +7,4 @@ - [Finding Max Date in List Using Streams](https://www.baeldung.com/java-max-date-list-streams) - [Batch Processing of Stream Data in Java](https://www.baeldung.com/java-stream-batch-processing) - [Stream to Iterable in Java](https://www.baeldung.com/java-stream-to-iterable) +- [Understanding the Difference Between Stream.of() and IntStream.range()](https://www.baeldung.com/java-stream-of-and-intstream-range) From f90837908ad406f615d5129900300d5401099ead Mon Sep 17 00:00:00 2001 From: Pedro Lopes Date: Thu, 9 Feb 2023 01:58:28 -0300 Subject: [PATCH 062/113] BAEL-6119: Difference Between findBy and findAllBy in Spring Data JPA (#13344) * player entity and repository. test structure * moving modules * test findFirst. cleanups. * adding @Repository * player entity and repository. test structure * moving modules * test findFirst. cleanups. * adding @Repository * changing module * adding show-sql config * removing unrelated change * properties SB annotation --- .../FindByVsFindAllByApplication.java | 11 +++++ .../findbyvsfindallby/model/Player.java | 43 +++++++++++++++++ .../repository/PlayerRepository.java | 17 +++++++ .../FindByVsFindAllByIntegrationTest.java | 46 +++++++++++++++++++ 4 files changed, 117 insertions(+) create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/findbyvsfindallby/FindByVsFindAllByApplication.java create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/findbyvsfindallby/model/Player.java create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/findbyvsfindallby/repository/PlayerRepository.java create mode 100644 persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/findbyvsfindallby/FindByVsFindAllByIntegrationTest.java diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/findbyvsfindallby/FindByVsFindAllByApplication.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/findbyvsfindallby/FindByVsFindAllByApplication.java new file mode 100644 index 0000000000..c9757e2f04 --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/findbyvsfindallby/FindByVsFindAllByApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.spring.data.persistence.findbyvsfindallby; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class FindByVsFindAllByApplication { + public static void main(String[] args) { + SpringApplication.run(FindByVsFindAllByApplication.class, args); + } +} diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/findbyvsfindallby/model/Player.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/findbyvsfindallby/model/Player.java new file mode 100644 index 0000000000..0d8f833b4c --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/findbyvsfindallby/model/Player.java @@ -0,0 +1,43 @@ +package com.baeldung.spring.data.persistence.findbyvsfindallby.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.util.Objects; + +@Entity +public class Player { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long id; + + private Integer score; + + public Player(Integer score) { + this.score = score; + } + + public Player() { + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Integer getScore() { + return score; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Player player = (Player) o; + return id == player.id && Objects.equals(score, player.score); + } +} diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/findbyvsfindallby/repository/PlayerRepository.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/findbyvsfindallby/repository/PlayerRepository.java new file mode 100644 index 0000000000..6b0d1c6e5d --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/findbyvsfindallby/repository/PlayerRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.spring.data.persistence.findbyvsfindallby.repository; + +import com.baeldung.spring.data.persistence.findbyvsfindallby.model.Player; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface PlayerRepository extends JpaRepository { + List findByScoreGreaterThan(Integer target); + + List findAllByScoreGreaterThan(Integer target); + + Optional findFirstByScoreGreaterThan(Integer target); +} diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/findbyvsfindallby/FindByVsFindAllByIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/findbyvsfindallby/FindByVsFindAllByIntegrationTest.java new file mode 100644 index 0000000000..add340b4dd --- /dev/null +++ b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/findbyvsfindallby/FindByVsFindAllByIntegrationTest.java @@ -0,0 +1,46 @@ +package com.baeldung.spring.data.persistence.findbyvsfindallby; + +import com.baeldung.spring.data.persistence.findbyvsfindallby.model.Player; +import com.baeldung.spring.data.persistence.findbyvsfindallby.repository.PlayerRepository; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = FindByVsFindAllByApplication.class, properties = "spring.jpa.show-sql=true") +public class FindByVsFindAllByIntegrationTest { + @Autowired + private PlayerRepository playerRepository; + + @Before + public void setup() { + Player player1 = new Player(600); + Player player2 = new Player(500); + Player player3 = new Player(300); + playerRepository.saveAll(Arrays.asList(player1, player2, player3)); + } + + @Test + public void givenSavedPlayer_whenUseFindByOrFindAllBy_thenReturnSameResult() { + List findByPlayers = playerRepository.findByScoreGreaterThan(400); + List findAllByPlayers = playerRepository.findAllByScoreGreaterThan(400); + assertEquals(findByPlayers, findAllByPlayers); + } + + @Test + public void givenSavedPlayer_whenUseFindFirst_thenReturnSingleResult() { + Optional player = playerRepository.findFirstByScoreGreaterThan(400); + assertTrue(player.isPresent()); + assertEquals(600, player.get().getScore()); + } +} From ffa1fb3e8f213858583d029723e756d53a6c5f03 Mon Sep 17 00:00:00 2001 From: Arya <108480101+drafii@users.noreply.github.com> Date: Thu, 9 Feb 2023 20:58:24 +0300 Subject: [PATCH 063/113] Record vs Final class in Java (#13455) * Added code for record vs final. * Fixed a small mistake. --- .../java14/recordvsfinal/USCitizen.java | 18 +++++++++++++ .../recordvsfinal/USCitizenUnitTest.java | 26 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordvsfinal/USCitizen.java create mode 100644 core-java-modules/core-java-14/src/test/java/com/baeldung/java14/recordvsfinal/USCitizenUnitTest.java diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordvsfinal/USCitizen.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordvsfinal/USCitizen.java new file mode 100644 index 0000000000..9ff3676ae7 --- /dev/null +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordvsfinal/USCitizen.java @@ -0,0 +1,18 @@ +package com.baeldung.java14.recordvsfinal; + +public record USCitizen(String firstName, String lastName, String address) { + static int countryCode; + + // static initializer + static { + countryCode = 1; + } + + public static int getCountryCode() { + return countryCode; + } + + public String getFullName() { + return firstName + " " + lastName; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/recordvsfinal/USCitizenUnitTest.java b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/recordvsfinal/USCitizenUnitTest.java new file mode 100644 index 0000000000..bb4c16b500 --- /dev/null +++ b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/recordvsfinal/USCitizenUnitTest.java @@ -0,0 +1,26 @@ +package com.baeldung.java14.recordvsfinal; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class USCitizenUnitTest { + + @Test + public void givenName_whenGetNameAndCode_thenExpectedValuesReturned() { + + String firstName = "Joan"; + String lastName = "Winn"; + String address = "1892 Black Stallion Road"; + int countryCode = 1; + + USCitizen citizen = new USCitizen(firstName, lastName, address); + + assertEquals(firstName + " " + lastName, citizen.getFullName()); + assertEquals(countryCode, USCitizen.getCountryCode()); + } + +} \ No newline at end of file From 3daf5cdb4ac624be7166ba3cfd57880fdb77de66 Mon Sep 17 00:00:00 2001 From: Avin Buricha Date: Thu, 9 Feb 2023 23:40:24 +0530 Subject: [PATCH 064/113] BAEL-6072 | Create Dynamic Queues in RabbitMQ (#13301) * BAEL-6072 | Article code * Code changes as per editor review * Test cases updated * Removed unused imports * Updated test case --- .../queue/dynamic/DynamicQueueCreation.java | 34 +++++++++ .../dynamic/DynamicQueueCreationLiveTest.java | 71 +++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 messaging-modules/rabbitmq/src/main/java/com/baeldung/queue/dynamic/DynamicQueueCreation.java create mode 100644 messaging-modules/rabbitmq/src/test/java/com/baeldung/benchmark/queue/dynamic/DynamicQueueCreationLiveTest.java diff --git a/messaging-modules/rabbitmq/src/main/java/com/baeldung/queue/dynamic/DynamicQueueCreation.java b/messaging-modules/rabbitmq/src/main/java/com/baeldung/queue/dynamic/DynamicQueueCreation.java new file mode 100644 index 0000000000..f62660bf81 --- /dev/null +++ b/messaging-modules/rabbitmq/src/main/java/com/baeldung/queue/dynamic/DynamicQueueCreation.java @@ -0,0 +1,34 @@ +package com.baeldung.queue.dynamic; + +import java.io.IOException; +import java.util.concurrent.TimeoutException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.rabbitmq.client.AMQP; +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.ConnectionFactory; + +public class DynamicQueueCreation { + + private static final Logger log = LoggerFactory.getLogger(DynamicQueueCreation.class); + + private static final String QUEUE_NAME = "baeldung-queue"; + + public static void main(String[] args) throws IOException, TimeoutException { + + ConnectionFactory factory = new ConnectionFactory(); + factory.setHost("localhost"); + + try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { + AMQP.Queue.DeclareOk declareOk = channel.queueDeclare(QUEUE_NAME, true, false, false, null); + log.info(declareOk.getQueue()); + + AMQP.Queue.DeclareOk declareOkExists = channel.queueDeclarePassive(QUEUE_NAME); + log.info(declareOkExists.getQueue()); + } + } + +} diff --git a/messaging-modules/rabbitmq/src/test/java/com/baeldung/benchmark/queue/dynamic/DynamicQueueCreationLiveTest.java b/messaging-modules/rabbitmq/src/test/java/com/baeldung/benchmark/queue/dynamic/DynamicQueueCreationLiveTest.java new file mode 100644 index 0000000000..aa430035ef --- /dev/null +++ b/messaging-modules/rabbitmq/src/test/java/com/baeldung/benchmark/queue/dynamic/DynamicQueueCreationLiveTest.java @@ -0,0 +1,71 @@ +package com.baeldung.benchmark.queue.dynamic; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.io.IOException; +import java.util.concurrent.TimeoutException; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import com.rabbitmq.client.AMQP; +import com.rabbitmq.client.Channel; +import com.rabbitmq.client.Connection; +import com.rabbitmq.client.ConnectionFactory; + +public class DynamicQueueCreationLiveTest { + + private static final String QUEUE_NAME = "baeldung-queue"; + private static final String QUEUE_NAME_NEW = "baeldung-queue-new"; + + private static Connection connection; + + @BeforeAll + public static void setUpConnection() throws IOException, TimeoutException { + ConnectionFactory factory = new ConnectionFactory(); + factory.setHost("localhost"); + connection = factory.newConnection(); + } + + @Test + void givenQueueName_whenCreatingQueue_thenCheckingIfQueueCreated() throws IOException, TimeoutException { + + try (Channel channel = connection.createChannel()) { + AMQP.Queue.DeclareOk declareOk = channel.queueDeclare(QUEUE_NAME, true, false, false, null); + + assertNotNull(declareOk); + assertEquals(QUEUE_NAME, declareOk.getQueue()); + } + } + + @Test + void givenQueueName_whenCreatingQueue_thenCheckingIfQueueExists() throws IOException, TimeoutException { + + try (Channel channel = connection.createChannel()) { + channel.queueDeclare(QUEUE_NAME, true, false, false, null); + + AMQP.Queue.DeclareOk declareOk = channel.queueDeclarePassive(QUEUE_NAME); + + assertNotNull(declareOk); + assertEquals(QUEUE_NAME, declareOk.getQueue()); + } + } + + @Test + void givenQueueName_whenQueueDoesNotExist_thenCheckingIfQueueExists() throws IOException, TimeoutException { + + try (Channel channel = connection.createChannel()) { + assertThrows(IOException.class, () -> { + channel.queueDeclarePassive(QUEUE_NAME_NEW); + }); + } + } + + @AfterAll + public static void destroyConnection() throws IOException { + connection.close(); + } +} From c60e82a93d27cdf5c11d0f465f20e1d98603ee38 Mon Sep 17 00:00:00 2001 From: Azhwani <13301425+azhwani@users.noreply.github.com> Date: Thu, 9 Feb 2023 19:10:51 +0100 Subject: [PATCH 065/113] BAEL-5742: Fix EmptyResultDataAccessException when using Jdbctemplate (#13338) --- .../jdbc/template/testing/EmployeeDAO.java | 25 ++++++++-- .../template/testing/EmployeeDAOUnitTest.java | 47 +++++++++++++++---- 2 files changed, 59 insertions(+), 13 deletions(-) diff --git a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAO.java b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAO.java index 15da78ce35..77b69daa01 100644 --- a/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAO.java +++ b/persistence-modules/spring-jdbc/src/main/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAO.java @@ -1,10 +1,12 @@ package com.baeldung.spring.jdbc.template.testing; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.stereotype.Repository; - import javax.sql.DataSource; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; +import org.springframework.stereotype.Repository; + @Repository public class EmployeeDAO { private JdbcTemplate jdbcTemplate; @@ -20,4 +22,21 @@ public class EmployeeDAO { public int getCountOfEmployees() { return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class); } + + public Employee getEmployeeById(int id) { + RowMapper employeeRowMapper = (rs, rowNum) -> new Employee(rs.getInt("ID"), rs.getString("FIRST_NAME"), rs.getString("LAST_NAME")); + + return jdbcTemplate.queryForObject("SELECT * FROM EMPLOYEE WHERE id=?", employeeRowMapper, id); + } + + public Employee getEmployeeByIdV2(int id) { + RowMapper employeeRowMapper = (rs, rowNum) -> new Employee(rs.getInt("ID"), rs.getString("FIRST_NAME"), rs.getString("LAST_NAME")); + + try { + return jdbcTemplate.queryForObject("SELECT * FROM EMPLOYEE WHERE id=?", employeeRowMapper, id); + } catch (EmptyResultDataAccessException e) { + return null; + } + } + } \ No newline at end of file diff --git a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAOUnitTest.java b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAOUnitTest.java index 3609300c2d..982a423996 100644 --- a/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAOUnitTest.java +++ b/persistence-modules/spring-jdbc/src/test/java/com/baeldung/spring/jdbc/template/testing/EmployeeDAOUnitTest.java @@ -1,20 +1,26 @@ package com.baeldung.spring.jdbc.template.testing; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; + +import javax.sql.DataSource; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.test.util.ReflectionTestUtils; -import javax.sql.DataSource; - -import static org.junit.jupiter.api.Assertions.assertEquals; - @RunWith(MockitoJUnitRunner.class) public class EmployeeDAOUnitTest { @Mock @@ -25,10 +31,10 @@ public class EmployeeDAOUnitTest { @Before public void setup() { dataSource = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2) - .generateUniqueName(true) - .addScript("classpath:com/baeldung/spring/jdbc/template/testing/schema.sql") - .addScript("classpath:com/baeldung/spring/jdbc/template/testing/test-data.sql") - .build(); + .generateUniqueName(true) + .addScript("classpath:com/baeldung/spring/jdbc/template/testing/schema.sql") + .addScript("classpath:com/baeldung/spring/jdbc/template/testing/test-data.sql") + .build(); } @Test @@ -36,12 +42,12 @@ public class EmployeeDAOUnitTest { EmployeeDAO employeeDAO = new EmployeeDAO(); ReflectionTestUtils.setField(employeeDAO, "jdbcTemplate", jdbcTemplate); Mockito.when(jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class)) - .thenReturn(4); + .thenReturn(4); assertEquals(4, employeeDAO.getCountOfEmployees()); Mockito.when(jdbcTemplate.queryForObject(Mockito.anyString(), Mockito.eq(Integer.class))) - .thenReturn(3); + .thenReturn(3); assertEquals(3, employeeDAO.getCountOfEmployees()); } @@ -53,4 +59,25 @@ public class EmployeeDAOUnitTest { assertEquals(4, employeeDAO.getCountOfEmployees()); } + + @Test(expected = EmptyResultDataAccessException.class) + public void whenIdNotExist_thenThrowEmptyResultDataAccessException() { + EmployeeDAO employeeDAO = new EmployeeDAO(); + ReflectionTestUtils.setField(employeeDAO, "jdbcTemplate", jdbcTemplate); + Mockito.when(jdbcTemplate.queryForObject(anyString(), ArgumentMatchers.> any(), anyInt())) + .thenThrow(EmptyResultDataAccessException.class); + + employeeDAO.getEmployeeById(1); + } + + @Test + public void whenIdNotExist_thenReturnNull() { + EmployeeDAO employeeDAO = new EmployeeDAO(); + ReflectionTestUtils.setField(employeeDAO, "jdbcTemplate", jdbcTemplate); + Mockito.when(jdbcTemplate.queryForObject(anyString(), ArgumentMatchers.> any(), anyInt())) + .thenReturn(null); + + assertNull(employeeDAO.getEmployeeByIdV2(1)); + } + } From acfdbab0e9220941d90fca232f6075a131e8e564 Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Thu, 9 Feb 2023 20:40:27 +0200 Subject: [PATCH 066/113] JAVA-17327 Fix and enable spring-roo module (#13459) Co-authored-by: timis1 --- spring-roo/pom.xml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-roo/pom.xml b/spring-roo/pom.xml index 94f9eb0c6f..fcfafcdaac 100644 --- a/spring-roo/pom.xml +++ b/spring-roo/pom.xml @@ -11,6 +11,9 @@ spring-roo jar + + + io.spring.platform platform-bom From e715386efad8de7020a54f3d6f12559cada5a7f5 Mon Sep 17 00:00:00 2001 From: Kumar Prabhash Anand Date: Fri, 10 Feb 2023 17:11:06 +0100 Subject: [PATCH 067/113] BAEL-6155 adding quarkus funqy code (#13436) * BAEL-6155 adding quarkus funqy code * BAEL-6155 removed extra files * BAEL-6155 removed unused files * BAEL-6155 updated test naming convention --- quarkus-modules/quarkus-funqy/pom.xml | 128 ++++++++++++++++++ .../src/main/docker/Dockerfile.jvm | 93 +++++++++++++ .../com/baeldung/quarkus/MyFunctions.java | 27 ++++ .../src/main/kubernetes/knative-trigger.yaml | 14 ++ .../src/main/kubernetes/knative.yaml | 11 ++ .../src/main/resources/application.properties | 0 .../baeldung/quarkus/MyFunctionsUnitTest.java | 48 +++++++ 7 files changed, 321 insertions(+) create mode 100644 quarkus-modules/quarkus-funqy/pom.xml create mode 100644 quarkus-modules/quarkus-funqy/src/main/docker/Dockerfile.jvm create mode 100644 quarkus-modules/quarkus-funqy/src/main/java/com/baeldung/quarkus/MyFunctions.java create mode 100644 quarkus-modules/quarkus-funqy/src/main/kubernetes/knative-trigger.yaml create mode 100644 quarkus-modules/quarkus-funqy/src/main/kubernetes/knative.yaml create mode 100644 quarkus-modules/quarkus-funqy/src/main/resources/application.properties create mode 100644 quarkus-modules/quarkus-funqy/src/test/java/com/baeldung/quarkus/MyFunctionsUnitTest.java diff --git a/quarkus-modules/quarkus-funqy/pom.xml b/quarkus-modules/quarkus-funqy/pom.xml new file mode 100644 index 0000000000..95d712b9fa --- /dev/null +++ b/quarkus-modules/quarkus-funqy/pom.xml @@ -0,0 +1,128 @@ + + + 4.0.0 + com.baeldung.quarkus + quarkus-funqy + 1.0.0-SNAPSHOT + + 3.10.1 + false + 17 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 2.16.0.Final + 3.0.0-M7 + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + io.quarkus + quarkus-funqy-http + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-funqy-knative-events + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + + -parameters + + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + native + + + native + + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + native + + + + diff --git a/quarkus-modules/quarkus-funqy/src/main/docker/Dockerfile.jvm b/quarkus-modules/quarkus-funqy/src/main/docker/Dockerfile.jvm new file mode 100644 index 0000000000..2119ae0891 --- /dev/null +++ b/quarkus-modules/quarkus-funqy/src/main/docker/Dockerfile.jvm @@ -0,0 +1,93 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/quarkus-funqy-project-jvm . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-funqy-project-jvm +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-funqy-project-jvm +# +# This image uses the `run-java.sh` script to run the application. +# This scripts computes the command line to execute your Java application, and +# includes memory/GC tuning. +# You can configure the behavior using the following environment properties: +# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") +# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options +# in JAVA_OPTS (example: "-Dsome.property=foo") +# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is +# used to calculate a default maximal heap memory based on a containers restriction. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio +# of the container available memory as set here. The default is `50` which means 50% +# of the available memory is used as an upper boundary. You can skip this mechanism by +# setting this value to `0` in which case no `-Xmx` option is added. +# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This +# is used to calculate a default initial heap memory based on the maximum heap memory. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio +# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx` +# is used as the initial heap size. You can skip this mechanism by setting this value +# to `0` in which case no `-Xms` option is added (example: "25") +# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS. +# This is used to calculate the maximum value of the initial heap memory. If used in +# a container without any memory constraints for the container then this option has +# no effect. If there is a memory constraint then `-Xms` is limited to the value set +# here. The default is 4096MB which means the calculated value of `-Xms` never will +# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096") +# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output +# when things are happening. This option, if set to true, will set +# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true"). +# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example: +# true"). +# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787"). +# - CONTAINER_CORE_LIMIT: A calculated core limit as described in +# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2") +# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024"). +# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion. +# (example: "20") +# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking. +# (example: "40") +# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection. +# (example: "4") +# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus +# previous GC times. (example: "90") +# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20") +# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100") +# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should +# contain the necessary JRE command-line options to specify the required GC, which +# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC). +# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080") +# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080") +# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be +# accessed directly. (example: "foo.example.com,bar.example.com") +# +### +FROM registry.access.redhat.com/ubi8/openjdk-17:1.11 + +ENV LANGUAGE='en_US:en' + + +# We make four distinct layers so if there are application changes the library layers can be re-used +COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/ +COPY --chown=185 target/quarkus-app/*.jar /deployments/ +COPY --chown=185 target/quarkus-app/app/ /deployments/app/ +COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/ + +EXPOSE 8080 +USER 185 +ENV JAVA_OPTS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" + diff --git a/quarkus-modules/quarkus-funqy/src/main/java/com/baeldung/quarkus/MyFunctions.java b/quarkus-modules/quarkus-funqy/src/main/java/com/baeldung/quarkus/MyFunctions.java new file mode 100644 index 0000000000..cf5f0ce4e4 --- /dev/null +++ b/quarkus-modules/quarkus-funqy/src/main/java/com/baeldung/quarkus/MyFunctions.java @@ -0,0 +1,27 @@ +package com.baeldung.quarkus; + +import org.jboss.logging.Logger; +import io.quarkus.funqy.Funq; + +public class MyFunctions { + private static final Logger log = Logger.getLogger(MyFunctions.class); + @Funq("GreetUser") + public String fun(FunInput input) { + log.info("Function Triggered"); + String name = input != null ? input.name : "Funqy"; + return String.format("Hello %s!", name); + } + public static class FunInput { + public String name; + public FunInput() { } + public FunInput(String name) { + this.name = name; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + } +} diff --git a/quarkus-modules/quarkus-funqy/src/main/kubernetes/knative-trigger.yaml b/quarkus-modules/quarkus-funqy/src/main/kubernetes/knative-trigger.yaml new file mode 100644 index 0000000000..8384fc42c1 --- /dev/null +++ b/quarkus-modules/quarkus-funqy/src/main/kubernetes/knative-trigger.yaml @@ -0,0 +1,14 @@ +apiVersion: eventing.knative.dev/v1 +kind: Trigger +metadata: + name: baeldung-event +spec: + broker: baeldung + filter: + attributes: + type: GreetUser + subscriber: + ref: + apiVersion: serving.knative.dev/v1 + kind: Service + name: quarkus-funqy-project \ No newline at end of file diff --git a/quarkus-modules/quarkus-funqy/src/main/kubernetes/knative.yaml b/quarkus-modules/quarkus-funqy/src/main/kubernetes/knative.yaml new file mode 100644 index 0000000000..4264053c02 --- /dev/null +++ b/quarkus-modules/quarkus-funqy/src/main/kubernetes/knative.yaml @@ -0,0 +1,11 @@ +apiVersion: serving.knative.dev/v1 +kind: Service +metadata: + name: quarkus-funqy-project +spec: + template: + metadata: + name: quarkus-funqy-project-v1 + spec: + containers: + - image: docker.io/<>/quarkus-funqy-project \ No newline at end of file diff --git a/quarkus-modules/quarkus-funqy/src/main/resources/application.properties b/quarkus-modules/quarkus-funqy/src/main/resources/application.properties new file mode 100644 index 0000000000..e69de29bb2 diff --git a/quarkus-modules/quarkus-funqy/src/test/java/com/baeldung/quarkus/MyFunctionsUnitTest.java b/quarkus-modules/quarkus-funqy/src/test/java/com/baeldung/quarkus/MyFunctionsUnitTest.java new file mode 100644 index 0000000000..c9163c81b1 --- /dev/null +++ b/quarkus-modules/quarkus-funqy/src/test/java/com/baeldung/quarkus/MyFunctionsUnitTest.java @@ -0,0 +1,48 @@ +package com.baeldung.quarkus; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.RestAssured; +import io.restassured.http.ContentType; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; + +import java.util.UUID; + +@QuarkusTest +public class MyFunctionsUnitTest { + + @Test + public void givenFunctionAPI_whenCallWithoutBody_thenShouldReturnDefault() { + given() + .post("/GreetUser") + .then() + .statusCode(200) + .body(containsString("Hello Funqy!")); + } + + @Test + public void givenFunctionAPI_whenCallWithName_thenShouldReturnName() { + given() + .contentType(ContentType.JSON) + .body("{\"name\": \"Friend\"}") + .post("/GreetUser") + .then() + .statusCode(200) + .body(containsString("Hello Friend!")); + } + + @Test + public void givenFunctionAPI_whenCallWithEvent_thenShouldReturn200() { + RestAssured.given().contentType("application/json") + .header("ce-specversion", "1.0") + .header("ce-id", UUID.randomUUID().toString()) + .header("ce-type", "GreetUser") + .header("ce-source", "test") + .body("{ \"name\": \"Baeldung\" }") + .post("/") + .then().statusCode(200); + } + +} \ No newline at end of file From 02049ead6d6d5d3887ef912fabedd92e9b5271bc Mon Sep 17 00:00:00 2001 From: Roger <587230+rojyates@users.noreply.github.com> Date: Sat, 11 Feb 2023 02:19:24 +1000 Subject: [PATCH 068/113] BAEL-5720 Java HttpClient Connection Management (#13452) * BAEL-5642 Using @NotNull as a method parameter * BAEL-5642 Add Spring Boot and bump spring and hibernate-validator versions * BAEL-5720 Java HttpClient Connection Management * BAEL-5720 Java HttpClient Connection Management * BAEL-5720 move JavaHttpClient test to core-java-httpclient module * BAEL-5720 move jetty-logging-properties to core-java-httpclient module * BAEL-5720 add wiremock to pom * Update pom.xml * Delete jetty-logging.properties --------- Co-authored-by: Loredana Crusoveanu --- apache-httpclient/pom.xml | 2 +- .../core-java-httpclient/pom.xml | 7 + ...ttpClientConnectionManagementUnitTest.java | 147 ++++++++++++++++++ .../test/resources/jetty-logging.properties | 3 + javaxval/pom.xml | 2 +- 5 files changed, 159 insertions(+), 2 deletions(-) create mode 100644 core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/HttpClientConnectionManagementUnitTest.java create mode 100644 core-java-modules/core-java-httpclient/src/test/resources/jetty-logging.properties diff --git a/apache-httpclient/pom.xml b/apache-httpclient/pom.xml index 47dd41dce7..c371d1fc06 100644 --- a/apache-httpclient/pom.xml +++ b/apache-httpclient/pom.xml @@ -120,4 +120,4 @@ 5.2 - \ No newline at end of file + diff --git a/core-java-modules/core-java-httpclient/pom.xml b/core-java-modules/core-java-httpclient/pom.xml index 57b23e96c1..3df0447ff0 100644 --- a/core-java-modules/core-java-httpclient/pom.xml +++ b/core-java-modules/core-java-httpclient/pom.xml @@ -32,6 +32,12 @@ ${assertj.version} test + + com.github.tomakehurst + wiremock + ${wiremock.version} + test + @@ -53,6 +59,7 @@ 11 3.22.0 5.11.2 + 2.27.2 \ No newline at end of file diff --git a/core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/HttpClientConnectionManagementUnitTest.java b/core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/HttpClientConnectionManagementUnitTest.java new file mode 100644 index 0000000000..3b7610276c --- /dev/null +++ b/core-java-modules/core-java-httpclient/src/test/java/com/baeldung/httpclient/HttpClientConnectionManagementUnitTest.java @@ -0,0 +1,147 @@ +package com.baeldung.httpclient.conn; + +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; +import com.github.tomakehurst.wiremock.core.WireMockConfiguration; +import com.github.tomakehurst.wiremock.stubbing.ServeEvent; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.List; + +import static java.net.URI.create; + + +public class HttpClientConnectionManagementUnitTest { + + WireMockConfiguration firstConfiguration = WireMockConfiguration + .options() + .dynamicPort(); + WireMockConfiguration secondConfiguration = WireMockConfiguration + .options() + .dynamicPort(); + WireMockServer firstServer = new WireMockServer(firstConfiguration); + WireMockServer secondServer = new WireMockServer(secondConfiguration); + private String firstUrl; + private String secondUrl; + + private HttpClient client = HttpClient.newHttpClient(); + private HttpClient secondClient = HttpClient.newHttpClient(); + + private HttpRequest getRequest; + private HttpRequest secondGet; + + @Before + public void setup() { + firstServer.start(); + secondServer.start(); + + // add some request matchers + firstServer.stubFor(WireMock + .get(WireMock.anyUrl()) + .willReturn(WireMock + .aResponse() + .withStatus(200))); + secondServer.stubFor(WireMock + .get(WireMock.anyUrl()) + .willReturn(WireMock + .aResponse() + .withStatus(200))); + + firstUrl = "http://localhost:" + firstServer.port() + "/first"; + secondUrl = "http://localhost:" + secondServer.port() + "/second"; + + getRequest = HttpRequest + .newBuilder() + .uri(create(firstUrl)) + .version(HttpClient.Version.HTTP_1_1) + .build(); + + secondGet = HttpRequest + .newBuilder() + .uri(create(secondUrl)) + .version(HttpClient.Version.HTTP_1_1) + .build(); + } + + @After + public void tearDown() { + // display all the requests that the WireMock servers handled + List firstWiremockAllServeEvents = firstServer.getAllServeEvents(); + List secondWiremockAllServeEvents = secondServer.getAllServeEvents(); + firstWiremockAllServeEvents + .stream() + .map(event -> event + .getRequest() + .getAbsoluteUrl()) + .forEach(System.out::println); + secondWiremockAllServeEvents + .stream() + .map(event -> event + .getRequest() + .getAbsoluteUrl()) + .forEach(System.out::println); + + // stop the WireMock servers + firstServer.stop(); + secondServer.stop(); + } + + // Example 1. Use an HttpClient to connect to the same endpoint - reuses a connection from the internal pool + @Test + public final void givenAnHttpClient_whenTwoConnectionsToSameEndpointMadeSequentially_thenConnectionReused() throws InterruptedException, IOException { + + // given two requests to the same destination + final HttpResponse firstResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString()); + final HttpResponse secondResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString()); + + assert (firstResponse.statusCode() == 200) && (secondResponse.statusCode() == 200); + } + + // Example 2. Use separate HttpClients to connect to the same endpoint - creates a connection per client + @Test + public final void givenTwoHttpClients_whenEachClientMakesConnectionSequentially_thenConnectionCreatedForEach() throws InterruptedException, IOException { + + // given requests from two different client to same destination + final HttpResponse firstResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString()); + final HttpResponse secondResponse = secondClient.send(getRequest, HttpResponse.BodyHandlers.ofString()); + + assert (firstResponse.statusCode() == 200) && (secondResponse.statusCode() == 200); + } + + // Example 3. Use an HttpClient to Connect to first, second, then first endpoint again. + // New connections made each time when pool size is 1, or re-used when not restricted. + // Make sure to set the JVM arg when running the test: + // -Djdk.httpclient.connectionPoolSize=1 + @Test + public final void givenAnHttpClientAndAPoolSizeOfOne_whenTwoConnectionsMadeBackToOriginal_thenFirstConnectionPurged() throws InterruptedException, IOException { + + // given 3 requests, two to the first server and one to the second server + final HttpResponse firstResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString()); + final HttpResponse secondResponse = client.send(secondGet, HttpResponse.BodyHandlers.ofString()); + final HttpResponse thirdResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString()); + + assert ((firstResponse.statusCode() == 200) && (secondResponse.statusCode() == 200) && (thirdResponse.statusCode() == 200)); + } + + // Example 4. Use an HttpClient to connect, wait for connection keepalive to pass, then connect again. New connection made for both calls. + // Make sure to set the JVM arg when running the test: + // -Djdk.httpclient.keepalive.timeout=2 + @Test + public final void givenAnHttpClientAndConnectionKeepAliveOfTwoSeconds_whenCallMadeAfterKeepaliveExpires_thenNewConnection() throws InterruptedException, IOException { + + // given 2 requests to the same destination with the second call made after the keepalive timeout has passed + final HttpResponse firstResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString()); + Thread.sleep(3000); // exceeds 2 seconds configured by JVM arg + final HttpResponse secondResponse = client.send(getRequest, HttpResponse.BodyHandlers.ofString()); + + assert ((firstResponse.statusCode() == 200) && (secondResponse.statusCode() == 200)); + } + +} + diff --git a/core-java-modules/core-java-httpclient/src/test/resources/jetty-logging.properties b/core-java-modules/core-java-httpclient/src/test/resources/jetty-logging.properties new file mode 100644 index 0000000000..a21bdbcd09 --- /dev/null +++ b/core-java-modules/core-java-httpclient/src/test/resources/jetty-logging.properties @@ -0,0 +1,3 @@ +org.eclipse.jetty.util.log.class=org.eclipse.jetty.util.log.StrErrLog +org.eclipse.jetty.LEVEL=DEBUG +jetty.logs=logs \ No newline at end of file diff --git a/javaxval/pom.xml b/javaxval/pom.xml index 76472e29fb..1feed71abb 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -46,7 +46,7 @@ test - + From ccd2599628f6db4974cfa0109b21df7b7a9f3a61 Mon Sep 17 00:00:00 2001 From: Michael Olayemi Date: Sat, 11 Feb 2023 05:19:29 +0100 Subject: [PATCH 069/113] BAEL-5729 Convert Hex to RGB Using Java (#13432) --- core-java-modules/core-java-hex/README.md | 0 core-java-modules/core-java-hex/pom.xml | 25 +++++++++++++++++++ .../baeldung/hextorgb/HexToRgbUnitTest.java | 25 +++++++++++++++++++ core-java-modules/pom.xml | 1 + 4 files changed, 51 insertions(+) create mode 100644 core-java-modules/core-java-hex/README.md create mode 100644 core-java-modules/core-java-hex/pom.xml create mode 100644 core-java-modules/core-java-hex/src/test/java/com/baeldung/hextorgb/HexToRgbUnitTest.java diff --git a/core-java-modules/core-java-hex/README.md b/core-java-modules/core-java-hex/README.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/core-java-modules/core-java-hex/pom.xml b/core-java-modules/core-java-hex/pom.xml new file mode 100644 index 0000000000..afac1c4d66 --- /dev/null +++ b/core-java-modules/core-java-hex/pom.xml @@ -0,0 +1,25 @@ + + + 4.0.0 + core-java-hex + 0.1.0-SNAPSHOT + core-java-hex + jar + + + com.baeldung.core-java-modules + core-java-modules + 0.0.1-SNAPSHOT + + + + + + + + + + + \ No newline at end of file diff --git a/core-java-modules/core-java-hex/src/test/java/com/baeldung/hextorgb/HexToRgbUnitTest.java b/core-java-modules/core-java-hex/src/test/java/com/baeldung/hextorgb/HexToRgbUnitTest.java new file mode 100644 index 0000000000..35e5b87d29 --- /dev/null +++ b/core-java-modules/core-java-hex/src/test/java/com/baeldung/hextorgb/HexToRgbUnitTest.java @@ -0,0 +1,25 @@ +package com.baeldung.hextorgb; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class HexToRgbUnitTest { + + @Test + public void givenHexCode_whenConvertedToRgb_thenCorrectRgbValuesAreReturned() { + String hexCode = "FF9933"; + int red = 255; + int green = 153; + int blue = 51; + + int resultRed = Integer.valueOf(hexCode.substring(0, 2), 16); + int resultGreen = Integer.valueOf(hexCode.substring(2, 4), 16); + int resultBlue = Integer.valueOf(hexCode.substring(4, 6), 16); + + assertEquals(red, resultRed); + assertEquals(green, resultGreen); + assertEquals(blue, resultBlue); + } + +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index bbbca6adf5..612e607a38 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -62,6 +62,7 @@ core-java-exceptions-4 core-java-function core-java-functional + core-java-hex core-java-io core-java-io-2 core-java-io-3 From 1b165262f35561f5a3816059d9b2a6aa05c2fce3 Mon Sep 17 00:00:00 2001 From: Alexandru Borza Date: Sat, 11 Feb 2023 06:38:29 +0200 Subject: [PATCH 070/113] BAEL-6195 Find the First Embedded Occurrence of an Integer in a Java String (#13448) * initialize arraylist with null or zeros * configure pom parent * move code * delete module * BAEL-6195 * first occurence of an integer * review changes --- .../FirstOccurrenceOfAnInteger.java | 18 ++++++++ .../FirstOccurrenceOfAnIntegerUnitTest.java | 46 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnInteger.java create mode 100644 core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnIntegerUnitTest.java diff --git a/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnInteger.java b/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnInteger.java new file mode 100644 index 0000000000..ca86208e59 --- /dev/null +++ b/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnInteger.java @@ -0,0 +1,18 @@ +package com.baeldung.firstocurrenceofaninteger; + +public class FirstOccurrenceOfAnInteger { + + static Integer findFirstInteger(String s) { + int i = 0; + while (i < s.length() && !Character.isDigit(s.charAt(i))) { + i++; + } + int j = i; + while (j < s.length() && Character.isDigit(s.charAt(j))) { + j++; + } + return Integer.parseInt(s.substring(i, j)); + } + +} + diff --git a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnIntegerUnitTest.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnIntegerUnitTest.java new file mode 100644 index 0000000000..ab40316708 --- /dev/null +++ b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/firstocurrenceofaninteger/FirstOccurrenceOfAnIntegerUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.firstocurrenceofaninteger; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +class FirstOccurrenceOfAnIntegerUnitTest { + + @Test + void whenUsingPatternMatcher_findFirstInteger() { + String s = "ba31dung123"; + Matcher matcher = Pattern.compile("\\d+").matcher(s); + matcher.find(); + int i = Integer.parseInt(matcher.group()); + Assertions.assertEquals(31, i); + } + + @Test + void whenUsingScanner_findFirstInteger() { + int i = new Scanner("ba31dung123").useDelimiter("\\D+").nextInt(); + Assertions.assertEquals(31, i); + } + + @Test + void whenUsingSplit_findFirstInteger() { + String str = "ba31dung123"; + List tokens = Arrays.stream(str.split("\\D+")) + .filter(s -> s.length() > 0).collect(Collectors.toList()); + Assertions.assertEquals(31, Integer.parseInt(tokens.get(0))); + } + + @Test + void whenUsingCustomMethod_findFirstInteger() { + String str = "ba31dung123"; + Integer i = FirstOccurrenceOfAnInteger.findFirstInteger(str); + Assertions.assertEquals(31, i); + } + + +} From ffa1abfc08743df0a6bb4a8a70ab53043d6f28d7 Mon Sep 17 00:00:00 2001 From: emanueltrandafir1993 Date: Sat, 11 Feb 2023 13:40:09 +0100 Subject: [PATCH 071/113] BAEL-6198: fixed spacing for line continuation --- .../src/main/java/com/baeldung/junit5/nested/Publication.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Publication.java b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Publication.java index 998419acc9..bfadbd3fe8 100644 --- a/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Publication.java +++ b/testing-modules/junit5-annotations/src/main/java/com/baeldung/junit5/nested/Publication.java @@ -13,7 +13,7 @@ public class Publication { public List getReadableArticles(User user) { return articles.stream() .filter(a -> a.getArticleLevel() - .compare(user.getMembership()) <= 0) + .compare(user.getMembership()) <= 0) .map(Article::getName) .collect(Collectors.toList()); } @@ -21,7 +21,7 @@ public class Publication { public List getLockedArticles(User user) { return articles.stream() .filter(a -> a.getArticleLevel() - .compare(user.getMembership()) > 0) + .compare(user.getMembership()) > 0) .map(Article::getName) .collect(Collectors.toList()); } From 06b4300604f07211c37bfd6b75670840e18cee4b Mon Sep 17 00:00:00 2001 From: Amit Kumatr Date: Sun, 12 Feb 2023 13:30:21 +0530 Subject: [PATCH 072/113] renamed the Test class --- ...positoryIntegrationTest.java => UserRepositoryUnitTest.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/{UserRepositoryIntegrationTest.java => UserRepositoryUnitTest.java} (97%) diff --git a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryUnitTest.java similarity index 97% rename from persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryIntegrationTest.java rename to persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryUnitTest.java index 009ace0f9c..3a0342bf41 100644 --- a/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-query-3/src/test/java/com/baeldung/spring/data/jpa/collectionsvsstream/UserRepositoryUnitTest.java @@ -16,7 +16,7 @@ import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import com.github.javafaker.Faker; @DataJpaTest -class UserRepositoryIntegrationTest { +class UserRepositoryUnitTest { @Autowired private UserRepository userRepository; From a5e9b0bd743821e0784947ac793453b8943af53c Mon Sep 17 00:00:00 2001 From: timis1 <12120641+timis1@users.noreply.github.com> Date: Sun, 12 Feb 2023 18:43:59 +0200 Subject: [PATCH 073/113] JAVA-17765 Cleanup un-committed or un-ignored artifacts - Week 6 - 2023 (#13456) Co-authored-by: timis1 --- .gitignore | 2 ++ .../baeldung/cxf/aegis/BaeldungIntegrationTest.java | 10 +++++++--- jmeter/pom.xml | 2 +- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 7b448f6cb0..5dc7abec6a 100644 --- a/.gitignore +++ b/.gitignore @@ -67,6 +67,8 @@ ethereum/logs/ jmeter/src/main/resources/*-JMeter.csv jmeter/src/main/resources/*-Basic*.csv jmeter/src/main/resources/*-JMeter*.csv +jmeter/src/main/resources/*ReportsDashboard*.csv +jmeter/src/main/resources/dashboard/*ReportsDashboard*.csv ninja/devDb.mv.db diff --git a/apache-cxf-modules/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungIntegrationTest.java b/apache-cxf-modules/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungIntegrationTest.java index b28b987cfa..9c89d769e0 100644 --- a/apache-cxf-modules/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungIntegrationTest.java +++ b/apache-cxf-modules/cxf-aegis/src/test/java/com/baeldung/cxf/aegis/BaeldungIntegrationTest.java @@ -80,16 +80,20 @@ public class BaeldungIntegrationTest { private void marshalCourseRepo(CourseRepo courseRepo) throws Exception { AegisWriter writer = context.createXMLStreamWriter(); AegisType aegisType = context.getTypeMapping().getType(CourseRepo.class); - XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileOutputStream(fileName)); + final FileOutputStream stream = new FileOutputStream(fileName); + XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(stream); writer.write(courseRepo, new QName("http://aegis.cxf.baeldung.com", "baeldung"), false, xmlWriter, aegisType); xmlWriter.close(); + stream.close(); } private CourseRepo unmarshalCourseRepo() throws Exception { AegisReader reader = context.createXMLStreamReader(); - XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(fileName)); + final FileInputStream stream = new FileInputStream(fileName); + XMLStreamReader xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(stream); CourseRepo courseRepo = (CourseRepo) reader.read(xmlReader, context.getTypeMapping().getType(CourseRepo.class)); xmlReader.close(); + stream.close(); return courseRepo; } @@ -97,7 +101,7 @@ public class BaeldungIntegrationTest { public void cleanup(){ File testFile = new File(fileName); if (testFile.exists()) { - testFile.delete(); + testFile.deleteOnExit(); } } } \ No newline at end of file diff --git a/jmeter/pom.xml b/jmeter/pom.xml index c4d09b9106..acd823b74f 100644 --- a/jmeter/pom.xml +++ b/jmeter/pom.xml @@ -136,7 +136,7 @@ ${project.basedir}/src/main/resources/dashboard true true - false + true From 9a608d8ec2db31e5f6b6610df91cd7fdaf262206 Mon Sep 17 00:00:00 2001 From: Kumar Prabhash Anand Date: Sun, 12 Feb 2023 22:33:02 +0100 Subject: [PATCH 074/113] added parent in pox.xml (#13469) --- quarkus-modules/quarkus-funqy/pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/quarkus-modules/quarkus-funqy/pom.xml b/quarkus-modules/quarkus-funqy/pom.xml index 95d712b9fa..603f458287 100644 --- a/quarkus-modules/quarkus-funqy/pom.xml +++ b/quarkus-modules/quarkus-funqy/pom.xml @@ -16,6 +16,11 @@ 2.16.0.Final 3.0.0-M7 + + com.baeldung + quarkus-modules + 1.0.0-SNAPSHOT + From 663f4582d6d56e92f05c93efaef9ca402fac4a6a Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Mon, 13 Feb 2023 06:14:55 +0100 Subject: [PATCH 075/113] [is-object-array] Check if Object is an Array in Java (#13463) --- .../CheckObjectIsArrayUnitTest.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/isobjectarray/CheckObjectIsArrayUnitTest.java diff --git a/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/isobjectarray/CheckObjectIsArrayUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/isobjectarray/CheckObjectIsArrayUnitTest.java new file mode 100644 index 0000000000..ed38ab0765 --- /dev/null +++ b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/isobjectarray/CheckObjectIsArrayUnitTest.java @@ -0,0 +1,78 @@ +package com.baeldung.array.isobjectarray; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.reflect.Array; + +import org.junit.jupiter.api.Test; + +public class CheckObjectIsArrayUnitTest { + private static final Object ARRAY_INT = new int[] { 1, 2, 3, 4, 5 }; + private static final Object ARRAY_PERSON = new Person[] { new Person("Jackie Chan", "Hong Kong"), new Person("Tom Hanks", "United States") }; + + boolean isArray(Object obj) { + return obj instanceof Object[] || obj instanceof boolean[] || obj instanceof byte[] || obj instanceof short[] || obj instanceof char[] || obj instanceof int[] || obj instanceof long[] || obj instanceof float[] || obj instanceof double[]; + } + + @Test + void givenAnArrayObject_whenUsingInstanceof_getExpectedResult() { + assertTrue(ARRAY_PERSON instanceof Object[]); + assertFalse(ARRAY_INT instanceof Object[]); + assertTrue(ARRAY_INT instanceof int[]); + } + + @Test + void givenAnArrayObject_whenUsingOurIsArray_getExpectedResult() { + assertTrue(isArray(ARRAY_PERSON)); + assertTrue(isArray(ARRAY_INT)); + } + + @Test + void givenAnArrayObject_whenUsingClassIsArray_getExpectedResult() { + assertTrue(ARRAY_INT.getClass() + .isArray()); + assertTrue(ARRAY_PERSON.getClass() + .isArray()); + + assertEquals(Person.class, ARRAY_PERSON.getClass() + .getComponentType()); + assertEquals(int.class, ARRAY_INT.getClass() + .getComponentType()); + + } + + @Test + void givenAnArrayObject_whenUsingArrayGet_getExpectedElement() { + if (ARRAY_PERSON.getClass() + .isArray() && ARRAY_PERSON.getClass() + .getComponentType() == Person.class) { + Person person = (Person) Array.get(ARRAY_PERSON, 1); + assertEquals("Tom Hanks", person.getName()); + } + if (ARRAY_INT.getClass() + .isArray() && ARRAY_INT.getClass() + .getComponentType() == int.class) { + assertEquals(2, ((int) Array.get(ARRAY_INT, 1))); + } + } +} + +class Person { + private String name; + private String Location; + + public Person(String name, String location) { + this.name = name; + this.Location = location; + } + + public String getName() { + return name; + } + + public String getLocation() { + return Location; + } +} \ No newline at end of file From e9fa31c5a5e09766d7464a56da5436cdc48fabe1 Mon Sep 17 00:00:00 2001 From: Dhawal Kapil Date: Mon, 13 Feb 2023 23:27:26 +0530 Subject: [PATCH 076/113] Added Ebook related notes in the Readme (#13472) --- spring-reactive-modules/spring-reactive/README.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/spring-reactive-modules/spring-reactive/README.md b/spring-reactive-modules/spring-reactive/README.md index 9f1852d912..7dfc7b2952 100644 --- a/spring-reactive-modules/spring-reactive/README.md +++ b/spring-reactive-modules/spring-reactive/README.md @@ -1,3 +1,7 @@ +### Spring Reactive Articles that are also part of the e-book + +This module contains articles about Spring Reactive that are also part of an Ebook. + ## Spring Reactive This module contains articles describing reactive processing in Spring. @@ -13,4 +17,8 @@ This module contains articles describing reactive processing in Spring. - [Spring WebClient Requests with Parameters](https://www.baeldung.com/webflux-webclient-parameters) - [Handling Errors in Spring WebFlux](https://www.baeldung.com/spring-webflux-errors) - [Spring Security 5 for Reactive Applications](https://www.baeldung.com/spring-security-5-reactive) -- [Concurrency in Spring WebFlux](https://www.baeldung.com/spring-webflux-concurrency) \ No newline at end of file +- [Concurrency in Spring WebFlux](https://www.baeldung.com/spring-webflux-concurrency) + +### NOTE: + +Since this is a module tied to an e-book, it should **not** be moved or used to store the code for any further article. From cfe203b69d5bfc1ef9291fa775ff090b0c124171 Mon Sep 17 00:00:00 2001 From: Daniel Strmecki Date: Mon, 13 Feb 2023 20:41:29 +0100 Subject: [PATCH 077/113] Feature/bael 6101 singleton (#13325) * BAEL-6101: singleton bean and pattern example * BAEL-6101: change package * BAEL-6101: refactor * BAEL-6101: refactor * BAEL-6101: PR comment fix --- .../sample/singleton/SingletonBeanConfig.java | 29 +++++++++++++++ .../singleton/ThreadSafeSingleInstance.java | 24 +++++++++++++ .../singleton/SingletonBeanUnitTest.java | 35 +++++++++++++++++++ .../ThreadSafeSingleInstanceUnitTest.java | 16 +++++++++ 4 files changed, 104 insertions(+) create mode 100644 spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/singleton/SingletonBeanConfig.java create mode 100644 spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/singleton/ThreadSafeSingleInstance.java create mode 100644 spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/sample/singleton/SingletonBeanUnitTest.java create mode 100644 spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/sample/singleton/ThreadSafeSingleInstanceUnitTest.java diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/singleton/SingletonBeanConfig.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/singleton/SingletonBeanConfig.java new file mode 100644 index 0000000000..1c40097ba5 --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/singleton/SingletonBeanConfig.java @@ -0,0 +1,29 @@ +package com.baeldung.sample.singleton; + +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; + +@Configuration +public class SingletonBeanConfig { + + @Bean + @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) + public SingletonBean singletonBean() { + return new SingletonBean(); + } + + @Bean + @Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON) + public SingletonBean anotherSingletonBean() { + return new SingletonBean(); + } + + static class SingletonBean { + public String getValue() { + return "test"; + } + } + +} diff --git a/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/singleton/ThreadSafeSingleInstance.java b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/singleton/ThreadSafeSingleInstance.java new file mode 100644 index 0000000000..ae6e85bf2b --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/main/java/com/baeldung/sample/singleton/ThreadSafeSingleInstance.java @@ -0,0 +1,24 @@ +package com.baeldung.sample.singleton; + +public final class ThreadSafeSingleInstance { + + private static volatile ThreadSafeSingleInstance instance = null; + + private ThreadSafeSingleInstance() {} + + public static ThreadSafeSingleInstance getInstance() { + if (instance == null) { + synchronized(ThreadSafeSingleInstance.class) { + if (instance == null) { + instance = new ThreadSafeSingleInstance(); + } + } + } + return instance; + } + + public String getValue() { + return "test"; + } + +} diff --git a/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/sample/singleton/SingletonBeanUnitTest.java b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/sample/singleton/SingletonBeanUnitTest.java new file mode 100644 index 0000000000..72c1ae4170 --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/sample/singleton/SingletonBeanUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.sample.singleton; + +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SingletonBeanUnitTest { + + @Autowired + @Qualifier("singletonBean") + private SingletonBeanConfig.SingletonBean beanOne; + + @Autowired + @Qualifier("singletonBean") + private SingletonBeanConfig.SingletonBean beanTwo; + + @Autowired + @Qualifier("anotherSingletonBean") + private SingletonBeanConfig.SingletonBean beanThree; + + @Test + void givenTwoBeansWithSameId_whenInjectingThem_thenSameInstancesAreReturned() { + assertSame(beanOne, beanTwo); + } + + @Test + void givenTwoBeansWithDifferentId_whenInjectingThem_thenDifferentInstancesAreReturned() { + assertNotSame(beanOne, beanThree); + } + +} diff --git a/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/sample/singleton/ThreadSafeSingleInstanceUnitTest.java b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/sample/singleton/ThreadSafeSingleInstanceUnitTest.java new file mode 100644 index 0000000000..0753f92e31 --- /dev/null +++ b/spring-boot-modules/spring-boot-3/src/test/java/com/baeldung/sample/singleton/ThreadSafeSingleInstanceUnitTest.java @@ -0,0 +1,16 @@ +package com.baeldung.sample.singleton; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertSame; + +class ThreadSafeSingleInstanceUnitTest { + + @Test + void givenTwoSingletonInstances_whenGettingThem_thenSameInstancesAreReturned() { + ThreadSafeSingleInstance instanceOne = ThreadSafeSingleInstance.getInstance(); + ThreadSafeSingleInstance instanceTwo = ThreadSafeSingleInstance.getInstance(); + assertSame(instanceOne, instanceTwo); + } + +} From 1015fb3b97bc0f910bda366087fc1fc077dacc0a Mon Sep 17 00:00:00 2001 From: Stef Serban-Cristian Date: Mon, 13 Feb 2023 23:42:35 +0200 Subject: [PATCH 078/113] [BAEL-5788] Accessing Private Constructor --- .../reflection/PrivateConstructorClass.java | 8 ++++++++ .../reflection/PrivateConstructorUnitTest.java | 17 +++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java create mode 100644 core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java new file mode 100644 index 0000000000..24e7d435c7 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-constructors/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java @@ -0,0 +1,8 @@ +package com.baeldung.reflection; + +public class PrivateConstructorClass { + + private PrivateConstructorClass() { + System.out.println("Used the private constructor!"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java b/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java new file mode 100644 index 0000000000..cd1f48d720 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-constructors/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java @@ -0,0 +1,17 @@ +package com.baeldung.reflection; + +import java.lang.reflect.Constructor; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class PrivateConstructorUnitTest { + + @Test + public void whenConstructorIsPrivate_thenInstanceSuccess() throws Exception { + Constructor pcc = PrivateConstructorClass.class.getDeclaredConstructor(); + pcc.setAccessible(true); + PrivateConstructorClass privateConstructorInstance = pcc.newInstance(); + Assertions.assertTrue(privateConstructorInstance instanceof PrivateConstructorClass); + } +} \ No newline at end of file From 99b634f0cf7a6c513ae9365f96e2e9362fa89b9c Mon Sep 17 00:00:00 2001 From: Ralf Ueberfuhr <40685729+ueberfuhr@users.noreply.github.com> Date: Tue, 14 Feb 2023 07:28:13 +0100 Subject: [PATCH 079/113] BAEL-6097: Pitfalls on Testing with Spring Boot (#13441) * BAEL-6097: Create project * BAEL-6097: Implement sample code and tests with custom test slices * BAEL-6097: Fix application-test.yml * BAEL-6097: Rename tests to match BDD naming strategy, add test for Mapper Integration Test --- pom.xml | 4 +- .../spring-boot-3-test-pitfalls/pom.xml | 87 +++++++++++++++++++ .../baeldung/sample/pets/PetsApplication.java | 13 +++ .../baeldung/sample/pets/boundary/PetDto.java | 10 +++ .../sample/pets/boundary/PetDtoMapper.java | 13 +++ .../sample/pets/boundary/PetsController.java | 28 ++++++ .../com/baeldung/sample/pets/domain/Pet.java | 4 + .../sample/pets/domain/PetService.java | 14 +++ .../pets/domain/PetServiceRepository.java | 13 +++ .../pets/domain/PetServiceRepositoryImpl.java | 29 +++++++ .../src/main/resources/application.yml | 1 + .../boundary/PetDtoMapperIntegrationTest.java | 47 ++++++++++ .../pets/boundary/PetsBoundaryLayer.java | 10 +++ .../PetsControllerMvcIntegrationTest.java | 36 ++++++++ .../domain/PetServiceIntegrationTest.java | 26 ++++++ .../pets/domain/PetServiceUnitTest.java | 31 +++++++ .../sample/pets/domain/PetsDomainLayer.java | 10 +++ .../sample/test/slices/PetsBoundaryTest.java | 52 +++++++++++ .../sample/test/slices/PetsDomainTest.java | 52 +++++++++++ .../src/test/resources/application-test.yml | 11 +++ 20 files changed, 490 insertions(+), 1 deletion(-) create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/pom.xml create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/PetsApplication.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/boundary/PetDto.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/boundary/PetDtoMapper.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/boundary/PetsController.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/Pet.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/PetService.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/PetServiceRepository.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/PetServiceRepositoryImpl.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/main/resources/application.yml create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/boundary/PetDtoMapperIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/boundary/PetsBoundaryLayer.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/boundary/PetsControllerMvcIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/domain/PetServiceIntegrationTest.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/domain/PetServiceUnitTest.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/domain/PetsDomainLayer.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/test/slices/PetsBoundaryTest.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/test/slices/PetsDomainTest.java create mode 100644 spring-boot-modules/spring-boot-3-test-pitfalls/src/test/resources/application-test.yml diff --git a/pom.xml b/pom.xml index 4016d669a4..83ba73229f 100644 --- a/pom.xml +++ b/pom.xml @@ -965,6 +965,7 @@ spring-boot-modules/spring-boot-3 spring-boot-modules/spring-boot-3-native spring-boot-modules/spring-boot-3-observation + spring-boot-modules/spring-boot-3-test-pitfalls spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions persistence-modules/fauna @@ -1163,6 +1164,7 @@ spring-boot-modules/spring-boot-3 spring-boot-modules/spring-boot-3-native spring-boot-modules/spring-boot-3-observation + spring-boot-modules/spring-boot-3-test-pitfalls spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions persistence-modules/fauna @@ -1283,7 +1285,7 @@ 11 - + parents diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/pom.xml b/spring-boot-modules/spring-boot-3-test-pitfalls/pom.xml new file mode 100644 index 0000000000..90e4ba022a --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + spring-boot-3-test-pitfalls + 0.0.1-SNAPSHOT + spring-boot-3-test-pitfalls + Demo project for Spring Boot Testing Pitfalls + + + com.baeldung + parent-boot-3 + 0.0.1-SNAPSHOT + ../../parent-boot-3 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + org.projectlombok + lombok + true + + + org.mapstruct + mapstruct + ${org.mapstruct.version} + true + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + ${lombok.version} + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + org.projectlombok + lombok-mapstruct-binding + 0.2.0 + + + + + + + + + + 1.5.3.Final + 3.0.0-M7 + + + + diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/PetsApplication.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/PetsApplication.java new file mode 100644 index 0000000000..17ba1abb2e --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/PetsApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.sample.pets; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PetsApplication { + + public static void main(String[] args) { + SpringApplication.run(PetsApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/boundary/PetDto.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/boundary/PetDto.java new file mode 100644 index 0000000000..62b1202ce8 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/boundary/PetDto.java @@ -0,0 +1,10 @@ +package com.baeldung.sample.pets.boundary; + +import lombok.Data; + +@Data +public class PetDto { + + private String name; + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/boundary/PetDtoMapper.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/boundary/PetDtoMapper.java new file mode 100644 index 0000000000..07fbb77f2e --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/boundary/PetDtoMapper.java @@ -0,0 +1,13 @@ +package com.baeldung.sample.pets.boundary; + +import com.baeldung.sample.pets.domain.Pet; +import org.mapstruct.Mapper; + +@Mapper(componentModel = "spring") +public interface PetDtoMapper { + + PetDto map(Pet source); + + Pet map(PetDto source); + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/boundary/PetsController.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/boundary/PetsController.java new file mode 100644 index 0000000000..d95d43028b --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/boundary/PetsController.java @@ -0,0 +1,28 @@ +package com.baeldung.sample.pets.boundary; + +import com.baeldung.sample.pets.domain.PetService; +import lombok.RequiredArgsConstructor; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Collection; +import java.util.stream.Collectors; + +@RestController +@RequestMapping("/pets") +@RequiredArgsConstructor +public class PetsController { + + private final PetService service; + private final PetDtoMapper mapper; + + @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) + public Collection readAll() { + return service.getPets().stream() + .map(mapper::map) + .collect(Collectors.toList()); + } + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/Pet.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/Pet.java new file mode 100644 index 0000000000..3dfe5e1a47 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/Pet.java @@ -0,0 +1,4 @@ +package com.baeldung.sample.pets.domain; + +public record Pet(String name) { +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/PetService.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/PetService.java new file mode 100644 index 0000000000..c5f83047b8 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/PetService.java @@ -0,0 +1,14 @@ +package com.baeldung.sample.pets.domain; + +import lombok.RequiredArgsConstructor; +import lombok.experimental.Delegate; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class PetService { + + @Delegate + private final PetServiceRepository repo; + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/PetServiceRepository.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/PetServiceRepository.java new file mode 100644 index 0000000000..1900f72a1c --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/PetServiceRepository.java @@ -0,0 +1,13 @@ +package com.baeldung.sample.pets.domain; + +import java.util.Collection; + +public interface PetServiceRepository { + + boolean add(Pet pet); + + void clear(); + + Collection getPets(); + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/PetServiceRepositoryImpl.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/PetServiceRepositoryImpl.java new file mode 100644 index 0000000000..d1d4bba175 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/java/com/baeldung/sample/pets/domain/PetServiceRepositoryImpl.java @@ -0,0 +1,29 @@ +package com.baeldung.sample.pets.domain; + +import org.springframework.stereotype.Component; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +@Component +public class PetServiceRepositoryImpl implements PetServiceRepository { + + private final Set pets = new HashSet<>(); + + @Override + public Set getPets() { + return Collections.unmodifiableSet(pets); + } + + @Override + public boolean add(Pet pet) { + return this.pets.add(pet); + } + + @Override + public void clear() { + this.pets.clear(); + } + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/resources/application.yml b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/resources/application.yml new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/main/resources/application.yml @@ -0,0 +1 @@ + diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/boundary/PetDtoMapperIntegrationTest.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/boundary/PetDtoMapperIntegrationTest.java new file mode 100644 index 0000000000..14b12cb6e9 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/boundary/PetDtoMapperIntegrationTest.java @@ -0,0 +1,47 @@ +package com.baeldung.sample.pets.boundary; + +import com.baeldung.sample.pets.domain.PetService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.mock.mockito.MockReset; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +@ExtendWith(SpringExtension.class) +public class PetDtoMapperIntegrationTest { + + @Configuration + @ComponentScan(basePackageClasses = PetDtoMapper.class) + static class PetDtoMapperTestConfig { + + /* + * This would be necessary because the controller is also initialized + * and needs the service, although we do not want to test it here. + * + * Solutions: + * - place the mapper into a separate sub package + * - do not test the mapper separately, test it integrated within the controller + * (recommended) + */ + @Bean + PetService createServiceMock() { + return mock(PetService.class, MockReset.withSettings(MockReset.AFTER)); + } + + } + + @Autowired + PetDtoMapper mapper; + + @Test + void shouldExist() { // simply test correct test setup + assertThat(mapper).isNotNull(); + } + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/boundary/PetsBoundaryLayer.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/boundary/PetsBoundaryLayer.java new file mode 100644 index 0000000000..2a83b364c3 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/boundary/PetsBoundaryLayer.java @@ -0,0 +1,10 @@ +package com.baeldung.sample.pets.boundary; + +import org.springframework.context.annotation.ComponentScan; + +/** + * Just an interface to use for compiler-checked component scanning during tests. + * @see ComponentScan#basePackageClasses() + */ +public interface PetsBoundaryLayer { +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/boundary/PetsControllerMvcIntegrationTest.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/boundary/PetsControllerMvcIntegrationTest.java new file mode 100644 index 0000000000..9a5df7b727 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/boundary/PetsControllerMvcIntegrationTest.java @@ -0,0 +1,36 @@ +package com.baeldung.sample.pets.boundary; + +import com.baeldung.sample.pets.domain.PetService; +import com.baeldung.sample.test.slices.PetsBoundaryTest; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.Collections; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@PetsBoundaryTest +class PetsControllerMvcIntegrationTest { + + @Autowired + MockMvc mvc; + @Autowired + PetService service; + + @Test + void shouldReturnEmptyArrayWhenGetPets() throws Exception { + when(service.getPets()).thenReturn(Collections.emptyList()); + mvc.perform( + get("/pets") + .accept(MediaType.APPLICATION_JSON) + ) + .andExpect(status().isOk()) + .andExpect(content().string("[]")); + } + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/domain/PetServiceIntegrationTest.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/domain/PetServiceIntegrationTest.java new file mode 100644 index 0000000000..5e2ec41089 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/domain/PetServiceIntegrationTest.java @@ -0,0 +1,26 @@ +package com.baeldung.sample.pets.domain; + +import com.baeldung.sample.test.slices.PetsDomainTest; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +@PetsDomainTest +class PetServiceIntegrationTest { + + @Autowired + PetService service; + @Autowired // Mock + PetServiceRepository repository; + + @Test + void shouldAddPetWhenNotAlreadyExisting() { + var pet = new Pet("Dog"); + when(repository.add(pet)).thenReturn(true); + var result = service.add(pet); + assertThat(result).isTrue(); + } + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/domain/PetServiceUnitTest.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/domain/PetServiceUnitTest.java new file mode 100644 index 0000000000..b0ecdfaeb7 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/domain/PetServiceUnitTest.java @@ -0,0 +1,31 @@ +package com.baeldung.sample.pets.domain; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class PetServiceUnitTest { + + PetService service = new PetService(new PetServiceRepositoryImpl()); + + @Test + void shouldAddPetWhenNotAlreadyExisting() { + var pet = new Pet("Dog"); + var result = service.add(pet); + assertThat(result).isTrue(); + assertThat(service.getPets()).hasSize(1); + } + + @Test + void shouldNotAddPetWhenAlreadyExisting() { + var pet = new Pet("Cat"); + var result = service.add(pet); + assertThat(result).isTrue(); + // try a second time + result = service.add(pet); + assertThat(result).isFalse(); + assertThat(service.getPets()).hasSize(1); + } + + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/domain/PetsDomainLayer.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/domain/PetsDomainLayer.java new file mode 100644 index 0000000000..f32fd189e0 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/pets/domain/PetsDomainLayer.java @@ -0,0 +1,10 @@ +package com.baeldung.sample.pets.domain; + +import org.springframework.context.annotation.ComponentScan; + +/** + * Just an interface to use for compiler-checked component scanning during tests. + * @see ComponentScan#basePackageClasses() + */ +public interface PetsDomainLayer { +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/test/slices/PetsBoundaryTest.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/test/slices/PetsBoundaryTest.java new file mode 100644 index 0000000000..f58239f971 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/test/slices/PetsBoundaryTest.java @@ -0,0 +1,52 @@ +package com.baeldung.sample.test.slices; + +import com.baeldung.sample.pets.boundary.PetsBoundaryLayer; +import com.baeldung.sample.pets.boundary.PetsController; +import com.baeldung.sample.pets.domain.PetService; +import org.junit.jupiter.api.Tag; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.mock.mockito.MockReset; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.test.context.ActiveProfiles; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static org.mockito.Mockito.mock; + +@Documented +@Inherited +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@WebMvcTest(controllers = PetsController.class) +@ComponentScan(basePackageClasses = PetsBoundaryLayer.class) +@Import(PetsBoundaryTest.PetBoundaryTestConfiguration.class) +// further features that can help to configure and execute tests +@ActiveProfiles({ "test", "boundary-test" }) +@Tag("integration-test") +@Tag("boundary-test") +public @interface PetsBoundaryTest { + + @TestConfiguration + class PetBoundaryTestConfiguration { + + @Primary + @Bean + PetService createPetServiceMock() { + return mock( + PetService.class, + MockReset.withSettings(MockReset.AFTER) + ); + } + + } + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/test/slices/PetsDomainTest.java b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/test/slices/PetsDomainTest.java new file mode 100644 index 0000000000..b061889135 --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/java/com/baeldung/sample/test/slices/PetsDomainTest.java @@ -0,0 +1,52 @@ +package com.baeldung.sample.test.slices; + +import com.baeldung.sample.pets.domain.PetServiceRepository; +import com.baeldung.sample.pets.domain.PetsDomainLayer; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.mock.mockito.MockReset; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Primary; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +import static org.mockito.Mockito.mock; + +@Documented +@Inherited +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +@ExtendWith(SpringExtension.class) +@ComponentScan(basePackageClasses = PetsDomainLayer.class) +@Import(PetsDomainTest.PetServiceTestConfiguration.class) +// further features that can help to configure and execute tests +@ActiveProfiles({"test", "domain-test"}) +@Tag("integration-test") +@Tag("domain-test") +public @interface PetsDomainTest { + + @TestConfiguration + class PetServiceTestConfiguration { + + @Primary + @Bean + PetServiceRepository createPetsRepositoryMock() { + return mock( + PetServiceRepository.class, + MockReset.withSettings(MockReset.AFTER) + ); + } + + } + +} diff --git a/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/resources/application-test.yml b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/resources/application-test.yml new file mode 100644 index 0000000000..9801fe9e7e --- /dev/null +++ b/spring-boot-modules/spring-boot-3-test-pitfalls/src/test/resources/application-test.yml @@ -0,0 +1,11 @@ +logging: + level: + root: info + org: + springframework: + test: + context: + cache: DEBUG +spring: + main: + allow-bean-definition-overriding: true From e0eba906f7926c7c3028549bb6797096297bd6a6 Mon Sep 17 00:00:00 2001 From: Iniubong LA Date: Wed, 15 Feb 2023 07:07:51 +0000 Subject: [PATCH 080/113] =?UTF-8?q?Difference=20Between=20Function(String?= =?UTF-8?q?=E2=80=A6=20args)=20and=20Function(String[]=20args)=20(#13473)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../argsVsvarargs/StringArrayAndVarargs.java | 19 +++++++++++++++ .../StringArrayAndVarargsUnitTest.java | 24 +++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 core-java-modules/core-java-8-2/src/main/java/com/baeldung/argsVsvarargs/StringArrayAndVarargs.java create mode 100644 core-java-modules/core-java-8-2/src/test/java/com/baeldung/argsVsvarargs/StringArrayAndVarargsUnitTest.java diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/argsVsvarargs/StringArrayAndVarargs.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/argsVsvarargs/StringArrayAndVarargs.java new file mode 100644 index 0000000000..dc9137646f --- /dev/null +++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/argsVsvarargs/StringArrayAndVarargs.java @@ -0,0 +1,19 @@ +package com.baeldung.argsVsvarargs; + +public class StringArrayAndVarargs { + public static void capitalizeNames(String[] args) { + for(int i = 0; i < args.length; i++){ + args[i] = args[i].toUpperCase(); + } + + } + + public static String[] firstLetterOfWords(String... args) { + String[] firstLetter = new String[args.length]; + for(int i = 0; i < args.length; i++){ + firstLetter[i] = String.valueOf(args[i].charAt(0)); + } + return firstLetter; + } + +} diff --git a/core-java-modules/core-java-8-2/src/test/java/com/baeldung/argsVsvarargs/StringArrayAndVarargsUnitTest.java b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/argsVsvarargs/StringArrayAndVarargsUnitTest.java new file mode 100644 index 0000000000..f917373229 --- /dev/null +++ b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/argsVsvarargs/StringArrayAndVarargsUnitTest.java @@ -0,0 +1,24 @@ +package com.baeldung.argsVsvarargs; + +import static com.baeldung.argsVsvarargs.StringArrayAndVarargs.capitalizeNames; +import static com.baeldung.argsVsvarargs.StringArrayAndVarargs.firstLetterOfWords; +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +class StringArrayAndVarargsUnitTest { + + @Test + void whenCheckingArgumentClassName_thenNameShouldBeStringArray() { + String[] names = {"john", "ade", "kofi", "imo"}; + assertNotNull(names); + assertEquals("java.lang.String[]", names.getClass().getTypeName()); + capitalizeNames(names); + } + + @Test + void whenCheckingReturnedObjectClass_thenClassShouldBeStringArray() { + assertEquals(String[].class, firstLetterOfWords("football", "basketball", "volleyball").getClass()); + assertEquals(3, firstLetterOfWords("football", "basketball", "volleyball").length); + } +} \ No newline at end of file From 61618d1fcc78c3db659e22d9fce8b45eb8e15b92 Mon Sep 17 00:00:00 2001 From: Graham Cox Date: Wed, 15 Feb 2023 07:16:43 +0000 Subject: [PATCH 081/113] BAEL-6210: Examples for RethinkDB article (#13481) --- persistence-modules/rethinkdb/pom.xml | 53 ++++++++ .../rethinkdb/InsertIntegrationTest.java | 62 ++++++++++ .../rethinkdb/QueryIntegrationTest.java | 81 ++++++++++++ .../rethinkdb/StreamingIntegrationTest.java | 117 ++++++++++++++++++ .../rethinkdb/TablesIntegrationTest.java | 39 ++++++ .../java/com/baeldung/rethinkdb/TestBase.java | 44 +++++++ .../rethinkdb/UpdateIntegrationTest.java | 55 ++++++++ 7 files changed, 451 insertions(+) create mode 100644 persistence-modules/rethinkdb/pom.xml create mode 100644 persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/InsertIntegrationTest.java create mode 100644 persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/QueryIntegrationTest.java create mode 100644 persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/StreamingIntegrationTest.java create mode 100644 persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/TablesIntegrationTest.java create mode 100644 persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/TestBase.java create mode 100644 persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/UpdateIntegrationTest.java diff --git a/persistence-modules/rethinkdb/pom.xml b/persistence-modules/rethinkdb/pom.xml new file mode 100644 index 0000000000..17c7036ed3 --- /dev/null +++ b/persistence-modules/rethinkdb/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + rethinkdb + rethinkdb + Code snippets for RethinkDB articles + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-test + test + + + com.rethinkdb + rethinkdb-driver + 2.4.4 + + + + org.projectlombok + lombok + provided + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + 17 + + + diff --git a/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/InsertIntegrationTest.java b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/InsertIntegrationTest.java new file mode 100644 index 0000000000..244959d854 --- /dev/null +++ b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/InsertIntegrationTest.java @@ -0,0 +1,62 @@ +package com.baeldung.rethinkdb; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static com.rethinkdb.RethinkDB.r; + +/** + * Some tests demonstrating inserting data. + */ +public class InsertIntegrationTest extends TestBase { + /** + * Create a table for the tests. + */ + @BeforeEach + public void createTable() { + r.db(DB_NAME).tableCreate(tableName).run(conn); + } + + /** + * Insert a single simple record into the database. + */ + @Test + public void insertSimpleRecord() { + r.db(DB_NAME).table(tableName) + .insert( + r.hashMap() + .with("name", "Baeldung") + ) + .run(conn); + } + + @Test + public void insertMap() { + r.db(DB_NAME).table(tableName) + .insert( + Map.of("name", "Baeldung") + ) + .run(conn); + } + + @Test + public void insertComplex() { + r.db(DB_NAME).table(tableName) + .insert( + r.hashMap() + .with("name", "Baeldung") + .with("articles", r.array( + r.hashMap() + .with("name", "String Interpolation in Java") + .with("url", "https://www.baeldung.com/java-string-interpolation"), + r.hashMap() + .with("name", "Access HTTPS REST Service Using Spring RestTemplate") + .with("url", "https://www.baeldung.com/spring-resttemplate-secure-https-service") + ) + ) + ) + .run(conn); + } +} diff --git a/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/QueryIntegrationTest.java b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/QueryIntegrationTest.java new file mode 100644 index 0000000000..263dda9bc6 --- /dev/null +++ b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/QueryIntegrationTest.java @@ -0,0 +1,81 @@ +package com.baeldung.rethinkdb; + +import com.rethinkdb.net.Result; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static com.rethinkdb.RethinkDB.r; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Some tests demonstrating querying data. + */ +public class QueryIntegrationTest extends TestBase { + /** + * Create a table for the tests. + */ + @BeforeEach + public void createTable() { + r.db(DB_NAME).tableCreate(tableName).run(conn); + + r.db(DB_NAME).table(tableName) + .insert( + r.hashMap() + .with("id", "article1") + .with("name", "String Interpolation in Java") + .with("url", "https://www.baeldung.com/java-string-interpolation") + ).run(conn); + r.db(DB_NAME).table(tableName) + .insert( + r.hashMap() + .with("id", "article2") + .with("name", "Access HTTPS REST Service Using Spring RestTemplate") + .with("url", "https://www.baeldung.com/spring-resttemplate-secure-https-service") + ).run(conn); + } + + @Test + public void listAll() { + Result results = r.db(DB_NAME).table(tableName).run(conn, Map.class); + + // We can't ensure the order the results come back in. + Set expected = new HashSet<>(Set.of( + "String Interpolation in Java", + "Access HTTPS REST Service Using Spring RestTemplate" + )); + + for (Map result : results) { + assertTrue(expected.remove(result.get("name"))); + } + + assertTrue(expected.isEmpty()); + } + + @Test + public void listSome() { + Result results = r.db(DB_NAME) + .table(tableName) + .filter(r -> r.g("name").eq("String Interpolation in Java")) + .run(conn, Map.class); + + // We can't ensure the order the results come back in. + Set expected = Set.of("https://www.baeldung.com/java-string-interpolation"); + + assertEquals(expected, results.stream() + .map(r -> r.get("url")) + .collect(Collectors.toSet())); + } + + @Test + public void getByKey() { + Result results = r.db(DB_NAME).table(tableName).get("article1").run(conn, Map.class); + + assertEquals("String Interpolation in Java", results.first().get("name")); + } +} diff --git a/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/StreamingIntegrationTest.java b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/StreamingIntegrationTest.java new file mode 100644 index 0000000000..4ca147cf68 --- /dev/null +++ b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/StreamingIntegrationTest.java @@ -0,0 +1,117 @@ +package com.baeldung.rethinkdb; + +import com.rethinkdb.net.Result; +import org.junit.jupiter.api.Test; + +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static com.rethinkdb.RethinkDB.r; + +/** + * Some tests demonstrating streaming live changes to data. + */ +public class StreamingIntegrationTest extends TestBase { + @Test + public void getLiveInserts() throws InterruptedException { + ExecutorService executorService = Executors.newCachedThreadPool(); + + r.db(DB_NAME).tableCreate(tableName).run(conn); + + r.db(DB_NAME).table(tableName).insert(r.hashMap().with("index", 0)).run(conn); + + executorService.submit(() -> { + Result cursor = r.db(DB_NAME).table(tableName).changes().run(conn, Map.class); + + cursor.stream().forEach(record -> System.out.println("Record: " + record)); + }); + + for (int i = 0; i < 10; ++i) { + r.db(DB_NAME).table(tableName).insert(r.hashMap().with("index", i)).run(conn); + TimeUnit.MILLISECONDS.sleep(100); + } + + executorService.shutdownNow(); + } + + @Test + public void getSomeLiveInserts() throws InterruptedException { + ExecutorService executorService = Executors.newCachedThreadPool(); + + r.db(DB_NAME).tableCreate(tableName).run(conn); + + r.db(DB_NAME).table(tableName).insert(r.hashMap().with("index", 0)).run(conn); + + executorService.submit(() -> { + Result cursor = r.db(DB_NAME).table(tableName) + .filter(r -> r.g("index").eq(5)) + .changes() + .run(conn, Map.class); + + cursor.stream().forEach(record -> System.out.println("Record: " + record)); + }); + + for (int i = 0; i < 10; ++i) { + r.db(DB_NAME).table(tableName).insert(r.hashMap().with("index", i)).run(conn); + TimeUnit.MILLISECONDS.sleep(100); + } + + executorService.shutdownNow(); + } + + @Test + public void getLiveUpdates() throws InterruptedException { + ExecutorService executorService = Executors.newCachedThreadPool(); + + r.db(DB_NAME).tableCreate(tableName).run(conn); + + r.db(DB_NAME).table(tableName).insert(r.hashMap().with("index", 0)).run(conn); + + executorService.submit(() -> { + Result cursor = r.db(DB_NAME).table(tableName).changes().run(conn, Map.class); + + cursor.stream().forEach(record -> System.out.println("Record: " + record)); + }); + + for (int i = 0; i < 10; ++i) { + r.db(DB_NAME).table(tableName).update(r.hashMap().with("index", i)).run(conn); + TimeUnit.MILLISECONDS.sleep(100); + } + + executorService.shutdownNow(); + } + + @Test + public void getLiveDeletes() throws InterruptedException { + ExecutorService executorService = Executors.newCachedThreadPool(); + + r.db(DB_NAME).tableCreate(tableName).run(conn); + + for (int i = 0; i < 10; ++i) { + r.db(DB_NAME).table(tableName).insert(r.hashMap().with("index", i)).run(conn); + } + + executorService.submit(() -> { + Result cursor = r.db(DB_NAME).table(tableName).changes().run(conn, Map.class); + + cursor.stream().forEach(record -> System.out.println("Record: " + record)); + }); + + r.db(DB_NAME).table(tableName) + .filter(r -> r.g("index").eq(1)) + .delete() + .run(conn); + r.db(DB_NAME).table(tableName) + .filter(r -> r.g("index").eq(3)) + .delete() + .run(conn); + r.db(DB_NAME).table(tableName) + .filter(r -> r.g("index").eq(5)) + .delete() + .run(conn); + + executorService.shutdownNow(); + } +} diff --git a/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/TablesIntegrationTest.java b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/TablesIntegrationTest.java new file mode 100644 index 0000000000..d60e500373 --- /dev/null +++ b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/TablesIntegrationTest.java @@ -0,0 +1,39 @@ +package com.baeldung.rethinkdb; + +import com.rethinkdb.gen.exc.ReqlOpFailedError; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static com.rethinkdb.RethinkDB.r; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Some tests demonstrating working with tables. + */ +public class TablesIntegrationTest extends TestBase { + + @Test + public void createTable() { + r.db(DB_NAME).tableCreate(tableName).run(conn); + } + + @Test + public void createTableTwice() { + r.db(DB_NAME).tableCreate(tableName).run(conn); + + Assertions.assertThrows(ReqlOpFailedError.class, () -> { + r.db(DB_NAME).tableCreate(tableName).run(conn); + }); + } + + @Test + public void listTables() { + r.db(DB_NAME).tableCreate(tableName).run(conn); + + List tables = r.db(DB_NAME).tableList().run(conn, List.class).first(); + + assertTrue(tables.contains(tableName)); + } +} diff --git a/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/TestBase.java b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/TestBase.java new file mode 100644 index 0000000000..396f6655ea --- /dev/null +++ b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/TestBase.java @@ -0,0 +1,44 @@ +package com.baeldung.rethinkdb; + +import com.rethinkdb.net.Connection; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +import java.util.UUID; + +import static com.rethinkdb.RethinkDB.r; + +/** + * Base class for RethinkDB tests. + */ +public class TestBase { + /** The database name to work with */ + protected static final String DB_NAME = "test"; + + /** A randomly generated table name so they never collide */ + protected final String tableName = UUID.randomUUID().toString().replaceAll("-",""); + + /** A database connection */ + protected Connection conn; + + /** + * Connect to the database for each test + */ + @BeforeEach + public void connect() { + conn = r.connection() + .hostname("localhost") + .port(28015) + .connect(); + } + + /** + * Disconnect from the database after each test + */ + @AfterEach + public void disconnect() { + if (this.conn != null) { + conn.close(); + } + } +} diff --git a/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/UpdateIntegrationTest.java b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/UpdateIntegrationTest.java new file mode 100644 index 0000000000..39fad3a878 --- /dev/null +++ b/persistence-modules/rethinkdb/src/test/java/com/baeldung/rethinkdb/UpdateIntegrationTest.java @@ -0,0 +1,55 @@ +package com.baeldung.rethinkdb; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static com.rethinkdb.RethinkDB.r; + +/** + * Some tests demonstrating updating data. + */ +public class UpdateIntegrationTest extends TestBase { + /** + * Create a table for the tests. + */ + @BeforeEach + public void createTable() { + r.db(DB_NAME).tableCreate(tableName).run(conn); + + r.db(DB_NAME).table(tableName) + .insert( + r.hashMap() + .with("id", "article1") + .with("name", "String Interpolation in Java") + .with("url", "https://www.baeldung.com/java-string-interpolation") + ).run(conn); + r.db(DB_NAME).table(tableName) + .insert( + r.hashMap() + .with("id", "article2") + .with("name", "Access HTTPS REST Service Using Spring RestTemplate") + .with("url", "https://www.baeldung.com/spring-resttemplate-secure-https-service") + ).run(conn); + } + + @Test + public void updateAll() { + r.db(DB_NAME).table(tableName).update(r.hashMap().with("site", "Baeldung")).run(conn); + } + + @Test + public void updateSome() { + r.db(DB_NAME).table(tableName) + .filter(r -> r.g("name").eq("String Interpolation in Java")) + .update(r.hashMap().with("category", "java")) + .run(conn); + } + + @Test + public void delete() { + r.db(DB_NAME).table(tableName) + .filter(r -> r.g("name").eq("String Interpolation in Java")) + .delete() + .run(conn); + } +} From 072b567c01cd5222633e6b63c7ba079bff6b4dd6 Mon Sep 17 00:00:00 2001 From: Anastasios Ioannidis Date: Fri, 20 Jan 2023 18:33:28 +0200 Subject: [PATCH 082/113] JAVA-17608 Restored AtomicInteger default increment method --- .../atomic/SafeCounterWithLock.java | 2 +- .../atomic/SafeCounterWithoutLock.java | 8 +----- .../ThreadSafeCounterIntegrationTest.java | 28 ++++++++++++++++--- 3 files changed, 26 insertions(+), 12 deletions(-) diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java index ef6b7ee8c8..09dfe575e6 100644 --- a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java +++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithLock.java @@ -1,7 +1,7 @@ package com.baeldung.concurrent.atomic; public class SafeCounterWithLock { - private volatile int counter; + private int counter; int getValue() { return counter; diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java index 8b2aebba7c..e1117dd842 100644 --- a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java +++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/atomic/SafeCounterWithoutLock.java @@ -10,12 +10,6 @@ public class SafeCounterWithoutLock { } void increment() { - while(true) { - int existingValue = getValue(); - int newValue = existingValue + 1; - if(counter.compareAndSet(existingValue, newValue)) { - return; - } - } + counter.incrementAndGet(); } } diff --git a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java index c3c44b40cf..9b4b628d0f 100644 --- a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java +++ b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/atomic/ThreadSafeCounterIntegrationTest.java @@ -17,8 +17,8 @@ public class ThreadSafeCounterIntegrationTest { SafeCounterWithLock safeCounter = new SafeCounterWithLock(); IntStream.range(0, 1000) - .forEach(count -> service.submit(safeCounter::increment)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); + .forEach(count -> service.execute(safeCounter::increment)); + shutdownAndAwaitTermination(service); assertEquals(1000, safeCounter.getValue()); } @@ -29,10 +29,30 @@ public class ThreadSafeCounterIntegrationTest { SafeCounterWithoutLock safeCounter = new SafeCounterWithoutLock(); IntStream.range(0, 1000) - .forEach(count -> service.submit(safeCounter::increment)); - service.awaitTermination(100, TimeUnit.MILLISECONDS); + .forEach(count -> service.execute(safeCounter::increment)); + shutdownAndAwaitTermination(service); assertEquals(1000, safeCounter.getValue()); } + + private void shutdownAndAwaitTermination(ExecutorService pool) { + // Disable new tasks from being submitted + pool.shutdown(); + try { + // Wait a while for existing tasks to terminate + if (!pool.awaitTermination(100, TimeUnit.MILLISECONDS)) { + // Cancel currently executing tasks forcefully + pool.shutdownNow(); + // Wait a while for tasks to respond to being cancelled + if (!pool.awaitTermination(100, TimeUnit.MILLISECONDS)) + System.err.println("Pool did not terminate"); + } + } catch (InterruptedException ex) { + // (Re-)Cancel if current thread also interrupted + pool.shutdownNow(); + // Preserve interrupt status + Thread.currentThread().interrupt(); + } + } } From 6f5d19cbe255d6ea9eb26e3fedf1085b7c9f4fc7 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Wed, 15 Feb 2023 16:51:33 +0200 Subject: [PATCH 083/113] =?UTF-8?q?[JAVA-16376]=20Moved=20apache-poi,=20ap?= =?UTF-8?q?ache-velocity,di-modules,asciidoctor=E2=80=A6=20(#13461)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [JAVA-16376] Moved apache-poi, apache-velocity,di-modules,asciidoctor,aws-modules to jdk9-and-above profile * [JAVA-16376] testing war plugin * [JAVA-16376] Upgraded asciidoctor dependencies * [JAVA-16376] Upgraded lombok version * [JAVA-16376] Upgraded guice version * [JAVA-16376] Clean up properties --- apache-velocity/pom.xml | 1 + asciidoctor/pom.xml | 8 ++++---- aws-modules/aws-reactive/pom.xml | 2 ++ di-modules/guice/pom.xml | 2 +- pom.xml | 23 +++++++++++------------ 5 files changed, 19 insertions(+), 17 deletions(-) diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml index f4b6de8872..a562ebeec0 100644 --- a/apache-velocity/pom.xml +++ b/apache-velocity/pom.xml @@ -63,6 +63,7 @@ 4.5.2 1.7 2.0 + 3.3.2 \ No newline at end of file diff --git a/asciidoctor/pom.xml b/asciidoctor/pom.xml index e24917f2f4..b72f050379 100644 --- a/asciidoctor/pom.xml +++ b/asciidoctor/pom.xml @@ -62,10 +62,10 @@ - 1.5.6 - 1.5.6 - 1.5.0-alpha.15 - 1.5.0-alpha.15 + 2.2.2 + 2.5.7 + 2.3.4 + 2.3.4 \ No newline at end of file diff --git a/aws-modules/aws-reactive/pom.xml b/aws-modules/aws-reactive/pom.xml index fbad5e30d0..e6b50cadb2 100644 --- a/aws-modules/aws-reactive/pom.xml +++ b/aws-modules/aws-reactive/pom.xml @@ -77,6 +77,7 @@ org.projectlombok lombok + ${lombok.version} @@ -92,6 +93,7 @@ 2.2.1.RELEASE 2.17.283 + 1.18.20 \ No newline at end of file diff --git a/di-modules/guice/pom.xml b/di-modules/guice/pom.xml index cbadf2119d..a28dbe5297 100644 --- a/di-modules/guice/pom.xml +++ b/di-modules/guice/pom.xml @@ -23,7 +23,7 @@ - 4.1.0 + 5.0.1 \ No newline at end of file diff --git a/pom.xml b/pom.xml index 83ba73229f..0b63defb49 100644 --- a/pom.xml +++ b/pom.xml @@ -332,12 +332,6 @@ apache-cxf-modules apache-libraries - apache-poi - apache-velocity - di-modules - asciidoctor - - aws-modules azure checker-plugin @@ -615,12 +609,6 @@ apache-cxf-modules apache-libraries - apache-poi - apache-velocity - di-modules - asciidoctor - - aws-modules azure checker-plugin @@ -909,6 +897,11 @@ algorithms-modules + apache-poi + apache-velocity + di-modules + asciidoctor + aws-modules core-java-modules/core-java-9 core-java-modules/core-java-9-improvements core-java-modules/core-java-9-jigsaw @@ -1108,6 +1101,12 @@ algorithms-modules + apache-poi + apache-velocity + di-modules + asciidoctor + aws-modules + core-java-modules/core-java-9 core-java-modules/core-java-9-improvements core-java-modules/core-java-9-jigsaw From 04e1d47687112199f99601102a5a845409cd37af Mon Sep 17 00:00:00 2001 From: Ulisses Lima Date: Wed, 15 Feb 2023 17:52:25 -0300 Subject: [PATCH 084/113] BAEL-6046 - MongoDB - Field Level Encryption (#13440) * bael-6046 - first draft * review 1 * review 2 * null checks and lambda --- .../boot/csfle/config/EncryptionConfig.java | 12 ---- .../boot/csfle/config/MongoClientConfig.java | 35 +++++------ .../config/converter/BinaryConverter.java | 13 ++++ .../config/converter/IntegerConverter.java | 27 -------- .../config/converter/StringConverter.java | 27 -------- .../boot/csfle/service/CitizenService.java | 61 ++++++++++++++++--- 6 files changed, 85 insertions(+), 90 deletions(-) create mode 100644 persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/BinaryConverter.java delete mode 100644 persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/IntegerConverter.java delete mode 100644 persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/StringConverter.java diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/EncryptionConfig.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/EncryptionConfig.java index 1495822bc0..0ff97eb6c1 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/EncryptionConfig.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/EncryptionConfig.java @@ -4,8 +4,6 @@ import org.bson.BsonBinary; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; -import com.mongodb.client.vault.ClientEncryption; - @Configuration public class EncryptionConfig { @@ -21,18 +19,8 @@ public class EncryptionConfig { @Value("${com.baeldung.csfle.auto-decryption:false}") private Boolean autoDecryption; - private ClientEncryption encryption; - private BsonBinary dataKeyId; - public void setEncryption(ClientEncryption encryption) { - this.encryption = encryption; - } - - public ClientEncryption getEncryption() { - return encryption; - } - public void setDataKeyId(BsonBinary dataKeyId) { this.dataKeyId = dataKeyId; } diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java index 29076f4e61..e63034a5b5 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java @@ -11,12 +11,12 @@ import org.bson.Document; import org.bson.conversions.Bson; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration; import org.springframework.data.mongodb.core.convert.MongoCustomConversions; -import com.baeldung.boot.csfle.config.converter.IntegerConverter; -import com.baeldung.boot.csfle.config.converter.StringConverter; +import com.baeldung.boot.csfle.config.converter.BinaryConverter; import com.mongodb.AutoEncryptionSettings; import com.mongodb.ClientEncryptionSettings; import com.mongodb.ConnectionString; @@ -52,16 +52,17 @@ public class MongoClientConfig extends AbstractMongoClientConfiguration { @Override public MongoCustomConversions customConversions() { - return new MongoCustomConversions(Arrays.asList(new StringConverter(encryptionConfig), new IntegerConverter(encryptionConfig))); + return new MongoCustomConversions(Arrays.asList(new BinaryConverter())); } + @Bean @Override public MongoClient mongoClient() { MongoClient client; try { client = MongoClients.create(clientSettings()); - ClientEncryption encryption = createClientEncryption(); + ClientEncryption encryption = clientEncryption(); encryptionConfig.setDataKeyId(createOrRetrieveDataKey(client, encryption)); return client; @@ -70,6 +71,19 @@ public class MongoClientConfig extends AbstractMongoClientConfiguration { } } + @Bean + public ClientEncryption clientEncryption() throws FileNotFoundException, IOException { + Map> kmsProviders = LocalKmsUtils.providersMap(encryptionConfig.getMasterKeyPath()); + + ClientEncryptionSettings encryptionSettings = ClientEncryptionSettings.builder() + .keyVaultMongoClientSettings(clientSettings()) + .keyVaultNamespace(encryptionConfig.getKeyVaultNamespace()) + .kmsProviders(kmsProviders) + .build(); + + return ClientEncryptions.create(encryptionSettings); + } + private BsonBinary createOrRetrieveDataKey(MongoClient client, ClientEncryption encryption) { MongoNamespace namespace = new MongoNamespace(encryptionConfig.getKeyVaultNamespace()); MongoCollection keyVault = client.getDatabase(namespace.getDatabaseName()) @@ -92,19 +106,6 @@ public class MongoClientConfig extends AbstractMongoClientConfiguration { } } - private ClientEncryption createClientEncryption() throws FileNotFoundException, IOException { - Map> kmsProviders = LocalKmsUtils.providersMap(encryptionConfig.getMasterKeyPath()); - - ClientEncryptionSettings encryptionSettings = ClientEncryptionSettings.builder() - .keyVaultMongoClientSettings(clientSettings()) - .keyVaultNamespace(encryptionConfig.getKeyVaultNamespace()) - .kmsProviders(kmsProviders) - .build(); - - encryptionConfig.setEncryption(ClientEncryptions.create(encryptionSettings)); - return encryptionConfig.getEncryption(); - } - private MongoClientSettings clientSettings() throws FileNotFoundException, IOException { Builder settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString(uri)); diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/BinaryConverter.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/BinaryConverter.java new file mode 100644 index 0000000000..15231551fc --- /dev/null +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/BinaryConverter.java @@ -0,0 +1,13 @@ +package com.baeldung.boot.csfle.config.converter; + +import org.bson.BsonBinary; +import org.bson.types.Binary; +import org.springframework.core.convert.converter.Converter; + +public class BinaryConverter implements Converter { + + @Override + public BsonBinary convert(Binary source) { + return new BsonBinary(source.getType(), source.getData()); + } +} diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/IntegerConverter.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/IntegerConverter.java deleted file mode 100644 index 020513ebff..0000000000 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/IntegerConverter.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.boot.csfle.config.converter; - -import org.bson.BsonBinary; -import org.bson.BsonValue; -import org.bson.types.Binary; -import org.springframework.core.convert.converter.Converter; - -import com.baeldung.boot.csfle.config.EncryptionConfig; - -public class IntegerConverter implements Converter { - - private EncryptionConfig encryptionConfig; - - public IntegerConverter(EncryptionConfig config) { - this.encryptionConfig = config; - } - - @Override - public Integer convert(Binary source) { - BsonBinary bin = new BsonBinary(source.getType(), source.getData()); - BsonValue value = encryptionConfig.getEncryption() - .decrypt(bin); - - return value.asInt32() - .getValue(); - } -} diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/StringConverter.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/StringConverter.java deleted file mode 100644 index 7f8193ce43..0000000000 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/StringConverter.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.boot.csfle.config.converter; - -import org.bson.BsonBinary; -import org.bson.BsonValue; -import org.bson.types.Binary; -import org.springframework.core.convert.converter.Converter; - -import com.baeldung.boot.csfle.config.EncryptionConfig; - -public class StringConverter implements Converter { - - private EncryptionConfig encryptionConfig; - - public StringConverter(EncryptionConfig config) { - this.encryptionConfig = config; - } - - @Override - public String convert(Binary source) { - BsonBinary bin = new BsonBinary(source.getType(), source.getData()); - BsonValue value = encryptionConfig.getEncryption() - .decrypt(bin); - - return value.asString() - .getValue(); - } -} diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java index 9cc0753289..91b5940b25 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java @@ -1,6 +1,7 @@ package com.baeldung.boot.csfle.service; import java.util.List; +import java.util.stream.Collectors; import org.bson.BsonBinary; import org.bson.BsonInt32; @@ -16,6 +17,7 @@ import com.baeldung.boot.csfle.config.EncryptionConfig; import com.baeldung.boot.csfle.data.Citizen; import com.baeldung.boot.csfle.data.EncryptedCitizen; import com.mongodb.client.model.vault.EncryptOptions; +import com.mongodb.client.vault.ClientEncryption; @Service public class CitizenService { @@ -29,6 +31,9 @@ public class CitizenService { @Autowired private EncryptionConfig encryptionConfig; + @Autowired + private ClientEncryption clientEncryption; + public EncryptedCitizen save(Citizen citizen) { EncryptedCitizen encryptedCitizen = new EncryptedCitizen(citizen); encryptedCitizen.setEmail(encrypt(citizen.getEmail(), DETERMINISTIC_ALGORITHM)); @@ -38,26 +43,68 @@ public class CitizenService { } public List findAll() { - return mongo.findAll(Citizen.class); + if (!encryptionConfig.getAutoDecryption()) { + List allEncrypted = mongo.findAll(EncryptedCitizen.class); + + return allEncrypted.stream() + .map(this::decrypt) + .collect(Collectors.toList()); + } else { + return mongo.findAll(Citizen.class); + } } public Citizen findByEmail(String email) { Query byEmail = new Query(Criteria.where("email") .is(encrypt(email, DETERMINISTIC_ALGORITHM))); - return mongo.findOne(byEmail, Citizen.class); + if (!encryptionConfig.getAutoDecryption()) { + EncryptedCitizen encryptedCitizen = mongo.findOne(byEmail, EncryptedCitizen.class); + return decrypt(encryptedCitizen); + } else { + return mongo.findOne(byEmail, Citizen.class); + } } public BsonBinary encrypt(Object value, String algorithm) { if (value == null) return null; - BsonValue bsonValue = value instanceof Integer - ? new BsonInt32((Integer) value) - : new BsonString(value.toString()); + BsonValue bsonValue; + if (value instanceof Integer) { + bsonValue = new BsonInt32((Integer) value); + } else if (value instanceof String) { + bsonValue = new BsonString((String) value); + } else { + throw new IllegalArgumentException("unsupported type: " + value.getClass()); + } EncryptOptions options = new EncryptOptions(algorithm); options.keyId(encryptionConfig.getDataKeyId()); - return encryptionConfig.getEncryption() - .encrypt(bsonValue, options); + return clientEncryption.encrypt(bsonValue, options); + } + + public BsonValue decryptProperty(BsonBinary value) { + if (value == null) + return null; + + return clientEncryption.decrypt(value); + } + + private Citizen decrypt(EncryptedCitizen encrypted) { + Citizen citizen = new Citizen(encrypted); + + BsonValue decryptedBirthYear = decryptProperty(encrypted.getBirthYear()); + if (decryptedBirthYear != null) { + citizen.setBirthYear(decryptedBirthYear.asInt32() + .intValue()); + } + + BsonValue decryptedEmail = decryptProperty(encrypted.getEmail()); + if (decryptedEmail != null) { + citizen.setEmail(decryptedEmail.asString() + .getValue()); + } + + return citizen; } } From 452d3fdddb3e65a2b99e2a653119c96b13182ae6 Mon Sep 17 00:00:00 2001 From: Michael Pratt Date: Thu, 16 Feb 2023 01:41:00 +0000 Subject: [PATCH 085/113] BAEL-6162: Code examples from article (#13458) * Code example from article * BAEL-6162: Add unit tests * Rename test class --- .../spring-resttemplate-3/README.md | 1 + .../spring-resttemplate-3/pom.xml | 2 +- .../RestTemplateMethodsApplication.java | 102 ++++++++++++++++++ .../methods/RestTemplateMethodsUnitTest.java | 86 +++++++++++++++ 4 files changed, 190 insertions(+), 1 deletion(-) create mode 100644 spring-web-modules/spring-resttemplate-3/src/main/java/com/baeldung/resttemplate/methods/RestTemplateMethodsApplication.java create mode 100644 spring-web-modules/spring-resttemplate-3/src/test/java/com/baeldung/resttemplate/methods/RestTemplateMethodsUnitTest.java diff --git a/spring-web-modules/spring-resttemplate-3/README.md b/spring-web-modules/spring-resttemplate-3/README.md index 52eba522a5..3add0073b2 100644 --- a/spring-web-modules/spring-resttemplate-3/README.md +++ b/spring-web-modules/spring-resttemplate-3/README.md @@ -11,3 +11,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Download a Large File Through a Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-download-large-file) - [Access HTTPS REST Service Using Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-secure-https-service) - [Encoding of URI Variables on RestTemplate](https://www.baeldung.com/spring-resttemplate-uri-variables-encode) +- [Difference Between exchange(), postForEntity() and execute() in RestTemplate](https://www.baeldung.com/difference-between-exchange-postForEntity-and-execute) diff --git a/spring-web-modules/spring-resttemplate-3/pom.xml b/spring-web-modules/spring-resttemplate-3/pom.xml index b036a5ffcb..5ce7d348a2 100644 --- a/spring-web-modules/spring-resttemplate-3/pom.xml +++ b/spring-web-modules/spring-resttemplate-3/pom.xml @@ -26,4 +26,4 @@ - \ No newline at end of file + diff --git a/spring-web-modules/spring-resttemplate-3/src/main/java/com/baeldung/resttemplate/methods/RestTemplateMethodsApplication.java b/spring-web-modules/spring-resttemplate-3/src/main/java/com/baeldung/resttemplate/methods/RestTemplateMethodsApplication.java new file mode 100644 index 0000000000..72201aa5c9 --- /dev/null +++ b/spring-web-modules/spring-resttemplate-3/src/main/java/com/baeldung/resttemplate/methods/RestTemplateMethodsApplication.java @@ -0,0 +1,102 @@ +package com.baeldung.resttemplate.methods; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.ClientHttpRequest; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.web.client.RequestCallback; +import org.springframework.web.client.ResponseExtractor; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; + +/** + * Examples of making the same call with RestTemplate + * using postForEntity(), exchange(), and execute(). + */ +@SpringBootApplication +public class RestTemplateMethodsApplication { + private final static RestTemplate restTemplate = new RestTemplate(); + + public static void main(String[] args) { + + } + + private static void postForEntity() { + Book book = new Book( + "Cruising Along with Java", + "Venkat Subramaniam", + 2023); + + ResponseEntity response = restTemplate.postForEntity( + "https://api.bookstore.com", + book, + Book.class); + } + + private static void exchange() { + Book book = new Book( + "Effective Java", + "Joshua Bloch", + 2001); + + HttpHeaders headers = new HttpHeaders(); + headers.setBasicAuth("username", "password"); + + ResponseEntity response = restTemplate.exchange( + "https://api.bookstore.com", + HttpMethod.POST, + new HttpEntity<>(book, headers), + Book.class); + } + + private static void execute() { + ResponseEntity response = restTemplate.execute( + "https://api.bookstore.com", + HttpMethod.POST, + new RequestCallback() { + @Override + public void doWithRequest(ClientHttpRequest request) throws IOException { + // Create or decorate the request object as needed + } + }, + new ResponseExtractor>() { + @Override + public ResponseEntity extractData(ClientHttpResponse response) throws IOException { + // extract required data from response + return null; + } + } + ); + + // Could also use some factory methods in RestTemplate for + // the request callback and/or response extractor + + Book book = new Book( + "Reactive Spring", + "Josh Long", + 2020); + + response = restTemplate.execute( + "https://api.bookstore.com", + HttpMethod.POST, + restTemplate.httpEntityCallback(book), + restTemplate.responseEntityExtractor(Book.class) + ); + } + + private static class Book { + String title; + String author; + int yearPublished; + + public Book(String title, String author, int yearPublished) { + this.title = title; + this.author = author; + this.yearPublished = yearPublished; + } + } +} diff --git a/spring-web-modules/spring-resttemplate-3/src/test/java/com/baeldung/resttemplate/methods/RestTemplateMethodsUnitTest.java b/spring-web-modules/spring-resttemplate-3/src/test/java/com/baeldung/resttemplate/methods/RestTemplateMethodsUnitTest.java new file mode 100644 index 0000000000..c7a2880f9d --- /dev/null +++ b/spring-web-modules/spring-resttemplate-3/src/test/java/com/baeldung/resttemplate/methods/RestTemplateMethodsUnitTest.java @@ -0,0 +1,86 @@ +package com.baeldung.resttemplate.methods; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.*; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.test.web.client.response.MockRestResponseCreators; +import org.springframework.web.client.RestTemplate; + +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; + +/** + * Unit tests for different ways to send POST with RestTemplate. + */ +public class RestTemplateMethodsUnitTest +{ + + private final RestTemplate restTemplate = new RestTemplate(); + + private final String URL = "https://localhost:8080"; + + private MockRestServiceServer mockServer; + + @BeforeEach + public void setup() { + mockServer = MockRestServiceServer.createServer(restTemplate); + } + + /** + * Test that postForEntity sends a POST to the desired URL. + */ + @Test + public void testPostForEntity() { + + mockServer.expect(requestTo(URL)) + .andExpect(method(HttpMethod.POST)) + .andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK) + .contentType(MediaType.TEXT_PLAIN) + .body("Ok")); + + restTemplate.postForEntity( + URL, + "Test Body", + String.class); + + mockServer.verify(); + } + + /** + * Test that exchange with POST method sends a POST to the desired URL. + */ + @Test + public void testPostExchange() { + mockServer.expect(requestTo(URL)) + .andExpect(method(HttpMethod.POST)) + .andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK) + .contentType(MediaType.TEXT_PLAIN) + .body("Ok")); + + restTemplate.exchange( + URL, + HttpMethod.POST, + new HttpEntity<>("Test Body"), + String.class); + + mockServer.verify(); + } + + @Test + public void testPostExecute() { + mockServer.expect(requestTo(URL)) + .andExpect(method(HttpMethod.POST)) + .andRespond(MockRestResponseCreators.withStatus(HttpStatus.OK) + .contentType(MediaType.TEXT_PLAIN) + .body("Ok")); + + restTemplate.execute( + URL, + HttpMethod.POST, + restTemplate.httpEntityCallback("Test body"), + restTemplate.responseEntityExtractor(String.class)); + + mockServer.verify(); + } +} From d604623892faebb46cfe4e2d54a28508cee9f589 Mon Sep 17 00:00:00 2001 From: panos-kakos <102670093+panos-kakos@users.noreply.github.com> Date: Thu, 16 Feb 2023 17:57:31 +0200 Subject: [PATCH 086/113] [JAVA-16376] Moved spring-reactive-modules to jdk9-and-above profile (#13470) * [JAVA-16376] Moved spring-reactive-modules to jdk9-and-above profile * [JAVA-16376] Upgraded geotools dependencies and moved module to jdk9-and-above profile * [JAVA-16376] Replaced vividsolutions artifact with locationtech * [JAVA-16376] Moved data-structures to jdk9-and-above profile * [JAVA-16376] Moved deeplearning4j module to jdk9-and-above profile --------- Co-authored-by: Dhawal Kapil --- deeplearning4j/pom.xml | 9 +++++++ geotools/pom.xml | 13 ++++++--- .../java/com/baeldung/geotools/ShapeFile.java | 8 +++--- pom.xml | 27 +++++++------------ 4 files changed, 32 insertions(+), 25 deletions(-) diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml index c63e67d573..01bac93214 100644 --- a/deeplearning4j/pom.xml +++ b/deeplearning4j/pom.xml @@ -57,11 +57,20 @@ httpclient ${httpclient.version} + + + org.projectlombok + lombok + ${lombok.version} + provided + + 0.9.1 4.3.5 + 1.18.20 \ No newline at end of file diff --git a/geotools/pom.xml b/geotools/pom.xml index 05cae922a4..6edb344c8c 100644 --- a/geotools/pom.xml +++ b/geotools/pom.xml @@ -39,12 +39,19 @@ gt-swing ${geotools-swing.version} + + org.locationtech.jts + jts-core + 1.19.0 + + + - 15.2 - 15.2 - 15.2 + 28.1 + 28.1 + 28.1 \ No newline at end of file diff --git a/geotools/src/main/java/com/baeldung/geotools/ShapeFile.java b/geotools/src/main/java/com/baeldung/geotools/ShapeFile.java index de789918cd..64650fb486 100644 --- a/geotools/src/main/java/com/baeldung/geotools/ShapeFile.java +++ b/geotools/src/main/java/com/baeldung/geotools/ShapeFile.java @@ -1,8 +1,8 @@ package com.baeldung.geotools; -import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.GeometryFactory; -import com.vividsolutions.jts.geom.Point; +import org.locationtech.jts.geom.Coordinate; +import org.locationtech.jts.geom.GeometryFactory; +import org.locationtech.jts.geom.Point; import org.geotools.data.DataUtilities; import org.geotools.data.DefaultTransaction; import org.geotools.data.Transaction; @@ -35,7 +35,7 @@ public class ShapeFile { DefaultFeatureCollection collection = new DefaultFeatureCollection(); - GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); + GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); SimpleFeatureType TYPE = DataUtilities.createType("Location", "location:Point:srid=4326," + "name:String"); diff --git a/pom.xml b/pom.xml index 0b63defb49..8b395d44f1 100644 --- a/pom.xml +++ b/pom.xml @@ -341,16 +341,9 @@ core-java-modules couchbase custom-pmd - data-structures - deeplearning4j + drools - - - - - geotools - gradle-modules/gradle/maven-to-gradle @@ -470,7 +463,6 @@ server-modules spf4j spring-4 - spring-reactive-modules spring-aop spring-aop-2 spring-batch @@ -618,16 +610,8 @@ core-java-modules couchbase custom-pmd - data-structures - deeplearning4j drools - - - - - geotools - gradle-modules/gradle/maven-to-gradle @@ -739,7 +723,6 @@ server-modules spf4j spring-4 - spring-reactive-modules spring-aop spring-aop-2 spring-batch @@ -940,7 +923,9 @@ core-java-modules/core-java-strings core-java-modules/core-java-httpclient spring-core-6 + data-structures ddd-contexts + deeplearning4j docker-modules apache-httpclient-2 kubernetes-modules/kubernetes-spring @@ -959,11 +944,13 @@ spring-boot-modules/spring-boot-3-native spring-boot-modules/spring-boot-3-observation spring-boot-modules/spring-boot-3-test-pitfalls + spring-reactive-modules spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions persistence-modules/fauna lightrun tablesaw + geotools @@ -1145,7 +1132,9 @@ core-java-modules/core-java-strings core-java-modules/core-java-httpclient spring-core-6 + data-structures ddd-contexts + deeplearning4j docker-modules apache-httpclient-2 kubernetes-modules/kubernetes-spring @@ -1164,11 +1153,13 @@ spring-boot-modules/spring-boot-3-native spring-boot-modules/spring-boot-3-observation spring-boot-modules/spring-boot-3-test-pitfalls + spring-reactive-modules spring-swagger-codegen/custom-validations-opeanpi-codegen testing-modules/testing-assertions persistence-modules/fauna lightrun tablesaw + geotools From a3809635ffc46345d2a4e4c1b02562e99003fba7 Mon Sep 17 00:00:00 2001 From: thibaultfaure Date: Fri, 17 Feb 2023 02:16:55 +0100 Subject: [PATCH 087/113] BAEL-5288 Code for the Map Date Types With openapi generator article (#13467) Co-authored-by: thibault.faure --- .../spring-boot-swagger-2/pom.xml | 59 +++++++++++++++++++ .../src/main/resources/static/event.yaml | 23 ++++++++ .../com/baeldung/dates/EventUnitTest.java | 33 +++++++++++ 3 files changed, 115 insertions(+) create mode 100644 spring-boot-modules/spring-boot-swagger-2/src/main/resources/static/event.yaml create mode 100644 spring-boot-modules/spring-boot-swagger-2/src/test/java/com/baeldung/dates/EventUnitTest.java diff --git a/spring-boot-modules/spring-boot-swagger-2/pom.xml b/spring-boot-modules/spring-boot-swagger-2/pom.xml index 1cd8e5b850..d2d1d10ad9 100644 --- a/spring-boot-modules/spring-boot-swagger-2/pom.xml +++ b/spring-boot-modules/spring-boot-swagger-2/pom.xml @@ -20,6 +20,10 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-validation + org.springdoc springdoc-openapi-ui @@ -59,6 +63,7 @@ ${swagger-codegen-maven-plugin.version} + two-responses generate @@ -71,6 +76,59 @@ + + dates + + generate + + + ${project.basedir}/src/main/resources/static/event.yaml + spring + + true + custom + + + DateTime=Instant + Date=Date + + + Instant=java.time.Instant + Date=java.util.Date + + + + + + + org.openapitools + openapi-generator-maven-plugin + ${openapi-generator.version} + + + + generate + + + true + ${project.basedir}/src/main/resources/static/event.yaml + spring + + true + custom + false + true + + + DateTime=Instant + Date=Date + + + Instant=java.time.Instant + Date=java.util.Date + + + @@ -84,6 +142,7 @@ + 6.2.1 3.0.0 3.0.34 1.6.10 diff --git a/spring-boot-modules/spring-boot-swagger-2/src/main/resources/static/event.yaml b/spring-boot-modules/spring-boot-swagger-2/src/main/resources/static/event.yaml new file mode 100644 index 0000000000..f8a7b01b43 --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger-2/src/main/resources/static/event.yaml @@ -0,0 +1,23 @@ +openapi: 3.0.0 +info: + title: an example api with dates + version: 0.1.0 +paths: +components: + schemas: + Event: + type: object + properties: + organizer: + type: string + startDate: + type: string + format: date + endDate: + type: string + format: date-time + ticketSales: + type: string + description: Beginning of the ticket sales + example: "01-01-2023" + pattern: "[0-9]{2}-[0-9]{2}-[0-9]{4}" \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-swagger-2/src/test/java/com/baeldung/dates/EventUnitTest.java b/spring-boot-modules/spring-boot-swagger-2/src/test/java/com/baeldung/dates/EventUnitTest.java new file mode 100644 index 0000000000..378882c964 --- /dev/null +++ b/spring-boot-modules/spring-boot-swagger-2/src/test/java/com/baeldung/dates/EventUnitTest.java @@ -0,0 +1,33 @@ +package com.baeldung.dates; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; + +import org.junit.jupiter.api.Test; + +import io.swagger.model.Event; + +class EventUnitTest { + + private static final Validator VALIDATOR = Validation.buildDefaultValidatorFactory() + .getValidator(); + + @Test + void givenACorrectlyFormattedTicketSales_WhenBuildingEvent_ThenSuccess() { + Set> violations = VALIDATOR.validate(new Event().ticketSales("01-01-2024")); + assertTrue(violations.isEmpty()); + } + + @Test + void givenAWronglyFormattedTicketSales_WhenBuildingEvent_ThenSuccess() { + Set> violations = VALIDATOR.validate(new Event().ticketSales("2024-01-01")); + assertEquals(1, violations.size()); + } + +} From 2ddd883538016f507929012da4ff814c79736096 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 17:01:56 +0800 Subject: [PATCH 088/113] Update README.md [skip ci] --- core-java-modules/core-java-functional/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-functional/README.md b/core-java-modules/core-java-functional/README.md index 51185f13a1..addb312542 100644 --- a/core-java-modules/core-java-functional/README.md +++ b/core-java-modules/core-java-functional/README.md @@ -2,3 +2,4 @@ - [Functional Programming in Java](https://www.baeldung.com/java-functional-programming) - [Functors in Java](https://www.baeldung.com/java-functors) +- [Callback Functions in Java](https://www.baeldung.com/java-callback-functions) From 8dd22c39e6a6f78027058eba12e1708f8f6422cb Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 17:05:09 +0800 Subject: [PATCH 089/113] Update README.md [skip ci] --- spring-core-6/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-core-6/README.md b/spring-core-6/README.md index 90e2dfed01..e10db19a54 100644 --- a/spring-core-6/README.md +++ b/spring-core-6/README.md @@ -4,3 +4,4 @@ - [Using Environment Variables in Spring Boot’s application.properties](https://www.baeldung.com/spring-boot-properties-env-variables) - [Reinitialize Singleton Bean in Spring Context](https://www.baeldung.com/spring-reinitialize-singleton-bean) - [HTTP Interface in Spring 6](https://www.baeldung.com/spring-6-http-interface) +- [Getting the Current ApplicationContext in Spring](https://www.baeldung.com/spring-get-current-applicationcontext) From ffb997fdbc3717e4dbba8ff71a7662d119e26c35 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 17:10:23 +0800 Subject: [PATCH 090/113] Update README.md [skip ci] --- persistence-modules/spring-data-jpa-repo-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md index 6f19577606..23134ec02d 100644 --- a/persistence-modules/spring-data-jpa-repo-2/README.md +++ b/persistence-modules/spring-data-jpa-repo-2/README.md @@ -8,4 +8,5 @@ - [How to Access EntityManager with Spring Data](https://www.baeldung.com/spring-data-entitymanager) - [Difference Between JPA and Spring Data JPA](https://www.baeldung.com/spring-data-jpa-vs-jpa) - [Differences Between Spring Data JPA findFirst() and findTop()](https://www.baeldung.com/spring-data-jpa-findfirst-vs-findtop) +- [Difference Between findBy and findAllBy in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-find-by-vs-find-all-by) - More articles: [[<-- prev]](../spring-data-jpa-repo) From 0852bfaacec4c79dc96f12d09a2edf5c36d37026 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 17:13:47 +0800 Subject: [PATCH 091/113] Update README.md [skip ci] --- messaging-modules/rabbitmq/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/messaging-modules/rabbitmq/README.md b/messaging-modules/rabbitmq/README.md index 6a74c297fc..93bb795d7b 100644 --- a/messaging-modules/rabbitmq/README.md +++ b/messaging-modules/rabbitmq/README.md @@ -7,5 +7,5 @@ This module contains articles about RabbitMQ. - [Exchanges, Queues, and Bindings in RabbitMQ](https://www.baeldung.com/java-rabbitmq-exchanges-queues-bindings) - [Pub-Sub vs. Message Queues](https://www.baeldung.com/pub-sub-vs-message-queues) - [Channels and Connections in RabbitMQ](https://www.baeldung.com/java-rabbitmq-channels-connections) - +- [Create Dynamic Queues in RabbitMQ](https://www.baeldung.com/rabbitmq-dynamic-queues) From 9aaf6054110939208fe688ad708d194990a75c76 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 17:22:14 +0800 Subject: [PATCH 092/113] Update README.md [skip ci] --- persistence-modules/spring-jdbc/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-jdbc/README.md b/persistence-modules/spring-jdbc/README.md index 22f7fb3d63..21d25915de 100644 --- a/persistence-modules/spring-jdbc/README.md +++ b/persistence-modules/spring-jdbc/README.md @@ -6,3 +6,4 @@ - [Using a List of Values in a JdbcTemplate IN Clause](https://www.baeldung.com/spring-jdbctemplate-in-list) - [Obtaining Auto-generated Keys in Spring JDBC](https://www.baeldung.com/spring-jdbc-autogenerated-keys) - [Spring JDBC Batch Inserts](https://www.baeldung.com/spring-jdbc-batch-inserts) +- [Fix EmptyResultDataAccessException When Using JdbcTemplate](https://www.baeldung.com/jdbctemplate-fix-emptyresultdataaccessexception) From cf50bc7f1016fdd27844936fd59f77b2dd969e72 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 17:27:55 +0800 Subject: [PATCH 093/113] Update README.md [skip ci] --- core-java-modules/core-java-hex/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core-java-modules/core-java-hex/README.md b/core-java-modules/core-java-hex/README.md index e69de29bb2..0ba4d1372f 100644 --- a/core-java-modules/core-java-hex/README.md +++ b/core-java-modules/core-java-hex/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Convert Hex to RGB Using Java](https://www.baeldung.com/java-convert-hex-to-rgb) From 7e87aefa2bb72f2f83db5a50c092f6c47f41b9ae Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 18:27:38 +0800 Subject: [PATCH 094/113] Update README.md [skip ci] --- core-java-modules/core-java-string-algorithms-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-string-algorithms-3/README.md b/core-java-modules/core-java-string-algorithms-3/README.md index 622730c834..d2863be8e5 100644 --- a/core-java-modules/core-java-string-algorithms-3/README.md +++ b/core-java-modules/core-java-string-algorithms-3/README.md @@ -9,3 +9,4 @@ This module contains articles about string-related algorithms. - [Email Validation in Java](https://www.baeldung.com/java-email-validation-regex) - [Check if the First Letter of a String is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase) - [Find the First Non Repeating Character in a String in Java](https://www.baeldung.com/java-find-the-first-non-repeating-character) +- [Find the First Embedded Occurrence of an Integer in a Java String](https://www.baeldung.com/java-string-find-embedded-integer) From 17f4a4b82ca5be25433f957feebcea31bf1582d6 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 18:32:41 +0800 Subject: [PATCH 095/113] Update README.md [skip ci] --- testing-modules/junit5-annotations/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/junit5-annotations/README.md b/testing-modules/junit5-annotations/README.md index 6fd524592b..49d596607c 100644 --- a/testing-modules/junit5-annotations/README.md +++ b/testing-modules/junit5-annotations/README.md @@ -8,3 +8,4 @@ This module contains articles about JUnit 5 Annotations - [JUnit5 Programmatic Extension Registration with @RegisterExtension](https://www.baeldung.com/junit-5-registerextension-annotation) - [Guide to JUnit 5 Parameterized Tests](https://www.baeldung.com/parameterized-tests-junit-5) - [Writing Templates for Test Cases Using JUnit 5](https://www.baeldung.com/junit5-test-templates) +- [JUnit 5 @Nested Test Classes](https://www.baeldung.com/junit-5-nested-test-classes) From 06c320534a62f636efc6821ca732903e50155bba Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 18:36:58 +0800 Subject: [PATCH 096/113] Update README.md [skip ci] --- core-java-modules/core-java-14/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-14/README.md b/core-java-modules/core-java-14/README.md index 00fd2fa320..97be9391fb 100644 --- a/core-java-modules/core-java-14/README.md +++ b/core-java-modules/core-java-14/README.md @@ -12,3 +12,4 @@ This module contains articles about Java 14. - [Java 14 Record Keyword](https://www.baeldung.com/java-record-keyword) - [New Features in Java 14](https://www.baeldung.com/java-14-new-features) - [Java 14 Record vs. Lombok](https://www.baeldung.com/java-record-vs-lombok) +- [Record vs. Final Class in Java](https://www.baeldung.com/java-record-vs-final-class) From 76ad5be7ad44b45fa000c9f8420ef3914670896e Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 18:44:12 +0800 Subject: [PATCH 097/113] Update README.md [skip ci] --- core-java-modules/core-java-httpclient/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-httpclient/README.md b/core-java-modules/core-java-httpclient/README.md index 68f828e81b..5dbb7a08ef 100644 --- a/core-java-modules/core-java-httpclient/README.md +++ b/core-java-modules/core-java-httpclient/README.md @@ -5,3 +5,4 @@ This module contains articles about Java HttpClient ### Relevant articles - [Posting with Java HttpClient](https://www.baeldung.com/java-httpclient-post) - [Custom HTTP Header With the Java HttpClient](https://www.baeldung.com/java-http-client-custom-header) +- [Java HttpClient Connection Management](https://www.baeldung.com/java-httpclient-connection-management) From 0a3eb4f2ad90d937074e359017b6cce1079314a0 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 18:46:55 +0800 Subject: [PATCH 098/113] Create README.md [skip ci] --- quarkus-modules/quarkus-funqy/README.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 quarkus-modules/quarkus-funqy/README.md diff --git a/quarkus-modules/quarkus-funqy/README.md b/quarkus-modules/quarkus-funqy/README.md new file mode 100644 index 0000000000..a97005bb00 --- /dev/null +++ b/quarkus-modules/quarkus-funqy/README.md @@ -0,0 +1,2 @@ +## Relevant Articles +- [Guide to Quarkus Funqy](https://www.baeldung.com/java-quarkus-funqy) From c927cc4dcd274289547684dabf0aad05ab628026 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 18:49:11 +0800 Subject: [PATCH 099/113] Update README.md [skip ci] --- core-java-modules/core-java-streams-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-streams-4/README.md b/core-java-modules/core-java-streams-4/README.md index b0b42324d6..67b16ac153 100644 --- a/core-java-modules/core-java-streams-4/README.md +++ b/core-java-modules/core-java-streams-4/README.md @@ -8,3 +8,4 @@ - [Batch Processing of Stream Data in Java](https://www.baeldung.com/java-stream-batch-processing) - [Stream to Iterable in Java](https://www.baeldung.com/java-stream-to-iterable) - [Understanding the Difference Between Stream.of() and IntStream.range()](https://www.baeldung.com/java-stream-of-and-intstream-range) +- [Check if Object Is an Array in Java](https://www.baeldung.com/java-check-if-object-is-an-array) From f8fe4da66dce94a1e0e20f3cc9d7493ee04f7bd2 Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 18:52:43 +0800 Subject: [PATCH 100/113] Update README.md [skip ci] --- spring-boot-modules/spring-boot-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-boot-modules/spring-boot-3/README.md b/spring-boot-modules/spring-boot-3/README.md index ea30573163..0d79f006e1 100644 --- a/spring-boot-modules/spring-boot-3/README.md +++ b/spring-boot-modules/spring-boot-3/README.md @@ -2,3 +2,4 @@ ### Relevant Articles: - [Spring Boot 3 and Spring Framework 6.0 – What’s New](https://www.baeldung.com/spring-boot-3-spring-6-new) +- [Singleton Design Pattern vs Singleton Beans in Spring Boot](https://www.baeldung.com/spring-boot-singleton-vs-beans) From d2f26b6cb8f8a28cf2f3c193c7f573e2dbdea25e Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 18:57:00 +0800 Subject: [PATCH 101/113] Update README.md [skip ci] --- persistence-modules/spring-data-jpa-query-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-query-3/README.md b/persistence-modules/spring-data-jpa-query-3/README.md index f49bb19217..c0cc4f6511 100644 --- a/persistence-modules/spring-data-jpa-query-3/README.md +++ b/persistence-modules/spring-data-jpa-query-3/README.md @@ -7,6 +7,7 @@ This module contains articles about querying data using Spring Data JPA. - [JPA and Hibernate – Criteria vs. JPQL vs. HQL Query](https://www.baeldung.com/jpql-hql-criteria-query) - [Joining Tables With Spring Data JPA Specifications](https://www.baeldung.com/spring-jpa-joining-tables) - [NonUniqueResultException in Spring Data JPA](https://www.baeldung.com/spring-jpa-non-unique-result-exception) +- [Spring Data Repositories – Collections vs. Stream](https://www.baeldung.com/spring-data-collections-vs-stream) - More articles: [[<-- prev]](../spring-data-jpa-query-2) ### Eclipse Config From 533238620b63b30103e93f5cf241526bed3f007b Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Fri, 17 Feb 2023 19:00:43 +0800 Subject: [PATCH 102/113] Update README.md [skip ci] --- spring-web-modules/spring-resttemplate-3/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-web-modules/spring-resttemplate-3/README.md b/spring-web-modules/spring-resttemplate-3/README.md index 3add0073b2..1944221138 100644 --- a/spring-web-modules/spring-resttemplate-3/README.md +++ b/spring-web-modules/spring-resttemplate-3/README.md @@ -11,4 +11,4 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring - [Download a Large File Through a Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-download-large-file) - [Access HTTPS REST Service Using Spring RestTemplate](https://www.baeldung.com/spring-resttemplate-secure-https-service) - [Encoding of URI Variables on RestTemplate](https://www.baeldung.com/spring-resttemplate-uri-variables-encode) -- [Difference Between exchange(), postForEntity() and execute() in RestTemplate](https://www.baeldung.com/difference-between-exchange-postForEntity-and-execute) +- [Difference Between exchange(), postForEntity() and execute() in RestTemplate](https://www.baeldung.com/spring-resttemplate-exchange-postforentity-execute) From d64e32ea0b7ae3a896604ed89091bcbdf20f0c72 Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Fri, 17 Feb 2023 17:04:37 +0100 Subject: [PATCH 103/113] [2lists-to-map] Combining Two Lists into a Map in Java (#13484) * [2lists-to-map] Combining Two Lists into a Map in Java * [2lists-to-map] rename package --- .../CombineTwoListsInAMapUnitTest.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/combine2liststomap/CombineTwoListsInAMapUnitTest.java diff --git a/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/combine2liststomap/CombineTwoListsInAMapUnitTest.java b/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/combine2liststomap/CombineTwoListsInAMapUnitTest.java new file mode 100644 index 0000000000..501ec16a21 --- /dev/null +++ b/core-java-modules/core-java-collections-conversions-2/src/test/java/com/baeldung/combine2liststomap/CombineTwoListsInAMapUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.combine2liststomap; + +import static java.lang.Math.min; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import org.junit.jupiter.api.Test; + +public class CombineTwoListsInAMapUnitTest { + private static final List KEY_LIST = Arrays.asList("Number One", "Number Two", "Number Three", "Number Four", "Number Five"); + private static final List VALUE_LIST = Arrays.asList(1, 2, 3, 4, 5); + private static final Map EXPECTED_MAP = new HashMap() {{ + put("Number One", 1); + put("Number Two", 2); + put("Number Three", 3); + put("Number Four", 4); + put("Number Five", 5); + }}; + + @Test + void givenTwoLists_whenUsingLoopAndListGet_shouldGetExpectedMap() { + Map result = new HashMap<>(); + int size = KEY_LIST.size(); + if (KEY_LIST.size() != VALUE_LIST.size()) { + // throw an exception or print a warning + size = min(KEY_LIST.size(), VALUE_LIST.size()); + } + for (int i = 0; i < size; i++) { + result.put(KEY_LIST.get(i), VALUE_LIST.get(i)); + } + assertEquals(EXPECTED_MAP, result); + } + + @Test + void givenTwoLists_whenUsingStreamApiAndListGet_shouldGetExpectedMap() { + Map result = IntStream.range(0, KEY_LIST.size()) + .boxed() + .collect(Collectors.toMap(KEY_LIST::get, VALUE_LIST::get)); + assertEquals(EXPECTED_MAP, result); + } + + @Test + void givenTwoLists_whenUsingIterators_shouldGetExpectedMap() { + Map result = new HashMap<>(); + + Iterator ik = KEY_LIST.iterator(); + Iterator iv = VALUE_LIST.iterator(); + while (ik.hasNext() && iv.hasNext()) { + result.put(ik.next(), iv.next()); + } + + assertEquals(EXPECTED_MAP, result); + } + +} \ No newline at end of file From a3ff046a726c4304a72cd770844abf3e0dfcfb28 Mon Sep 17 00:00:00 2001 From: Anastasios Ioannidis <121166333+anastasiosioannidis@users.noreply.github.com> Date: Fri, 17 Feb 2023 18:47:01 +0200 Subject: [PATCH 104/113] JAVA-17429 Upgrade to latest spring-boot-2 (#13480) --- azure/pom.xml | 4 ++-- ddd/pom.xml | 4 ++-- jhipster-5/bookstore-monolith/pom.xml | 6 +----- libraries-data-db/pom.xml | 4 ++-- parent-boot-2/pom.xml | 8 +++++++- .../quarkus-vs-springboot/spring-project/pom.xml | 4 ++-- spring-boot-modules/spring-boot-autoconfiguration/pom.xml | 4 ++-- spring-boot-modules/spring-boot-bootstrap/pom.xml | 4 ++-- spring-boot-modules/spring-boot-data-3/pom.xml | 4 ++-- spring-boot-modules/spring-boot-mvc/pom.xml | 4 ++-- spring-core-2/pom.xml | 4 ++-- 11 files changed, 26 insertions(+), 24 deletions(-) diff --git a/azure/pom.xml b/azure/pom.xml index ae20ae7785..6a06282a71 100644 --- a/azure/pom.xml +++ b/azure/pom.xml @@ -36,8 +36,8 @@ runtime - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime diff --git a/ddd/pom.xml b/ddd/pom.xml index 3beb43bb35..6128bb1cd9 100644 --- a/ddd/pom.xml +++ b/ddd/pom.xml @@ -59,8 +59,8 @@ runtime - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-5/bookstore-monolith/pom.xml index ccf7a3c85e..ccaa802a39 100644 --- a/jhipster-5/bookstore-monolith/pom.xml +++ b/jhipster-5/bookstore-monolith/pom.xml @@ -94,10 +94,6 @@ org.apache.commons commons-lang3 - - mysql - mysql-connector-java - org.assertj assertj-core @@ -1175,7 +1171,7 @@ 2.1.1 - 2.0.8.RELEASE + 2.7.8 5.2.17.Final diff --git a/libraries-data-db/pom.xml b/libraries-data-db/pom.xml index 8e5140458e..6c72a4902c 100644 --- a/libraries-data-db/pom.xml +++ b/libraries-data-db/pom.xml @@ -127,8 +127,8 @@ - mysql - mysql-connector-java + com.mysql + mysql-connector-j diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml index 115589b1b0..a1f16c4a64 100644 --- a/parent-boot-2/pom.xml +++ b/parent-boot-2/pom.xml @@ -24,6 +24,11 @@ pom import + + mysql + mysql-connector-java + ${mysql-connector-java.version} + org.springframework.boot spring-boot-dependencies @@ -89,8 +94,9 @@ 3.3.0 1.0.22.RELEASE - 2.7.5 + 2.7.8 1.9.1 + 8.0.31 \ No newline at end of file diff --git a/quarkus-modules/quarkus-vs-springboot/spring-project/pom.xml b/quarkus-modules/quarkus-vs-springboot/spring-project/pom.xml index 69e1dc3ab0..13508d7086 100644 --- a/quarkus-modules/quarkus-vs-springboot/spring-project/pom.xml +++ b/quarkus-modules/quarkus-vs-springboot/spring-project/pom.xml @@ -71,8 +71,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j test diff --git a/spring-boot-modules/spring-boot-autoconfiguration/pom.xml b/spring-boot-modules/spring-boot-autoconfiguration/pom.xml index ef5d4f66dd..7a3f9f01e8 100644 --- a/spring-boot-modules/spring-boot-autoconfiguration/pom.xml +++ b/spring-boot-modules/spring-boot-autoconfiguration/pom.xml @@ -38,8 +38,8 @@ test - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.springframework.boot diff --git a/spring-boot-modules/spring-boot-bootstrap/pom.xml b/spring-boot-modules/spring-boot-bootstrap/pom.xml index efcfcb71ee..4ceae26f60 100644 --- a/spring-boot-modules/spring-boot-bootstrap/pom.xml +++ b/spring-boot-modules/spring-boot-bootstrap/pom.xml @@ -32,8 +32,8 @@ h2 - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.springframework.boot diff --git a/spring-boot-modules/spring-boot-data-3/pom.xml b/spring-boot-modules/spring-boot-data-3/pom.xml index cac5016ebd..cf53c25697 100644 --- a/spring-boot-modules/spring-boot-data-3/pom.xml +++ b/spring-boot-modules/spring-boot-data-3/pom.xml @@ -25,8 +25,8 @@ spring-boot-starter-data-jpa - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime diff --git a/spring-boot-modules/spring-boot-mvc/pom.xml b/spring-boot-modules/spring-boot-mvc/pom.xml index 6d3f722146..d5ec7742c9 100644 --- a/spring-boot-modules/spring-boot-mvc/pom.xml +++ b/spring-boot-modules/spring-boot-mvc/pom.xml @@ -41,8 +41,8 @@ spring-boot-starter-data-rest - mysql - mysql-connector-java + com.mysql + mysql-connector-j org.hsqldb diff --git a/spring-core-2/pom.xml b/spring-core-2/pom.xml index 719bf56e0b..3cd9adf451 100644 --- a/spring-core-2/pom.xml +++ b/spring-core-2/pom.xml @@ -92,8 +92,8 @@ ${javassist.version} - mysql - mysql-connector-java + com.mysql + mysql-connector-j runtime From 62f75e38593b62a0814303e2ead59daf0bc54bb8 Mon Sep 17 00:00:00 2001 From: AttilaUhrin Date: Sat, 18 Feb 2023 04:04:25 +0100 Subject: [PATCH 105/113] [BAEL-6027] Add example for Awaitility and Thread.sleep comparison (#13450) * Add example for Awaitility and Thread.sleep comparison * Fix unit test method name and indentation. * Use property in pom.xml for awaitility dependency version. --------- Co-authored-by: Uhrin Attila --- .../core-java-concurrency-basic-3/pom.xml | 12 ++++++ .../baeldung/concurrent/RequestProcessor.java | 35 ++++++++++++++++ .../concurrent/RequestProcessorUnitTest.java | 41 +++++++++++++++++++ 3 files changed, 88 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/RequestProcessor.java create mode 100644 core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java diff --git a/core-java-modules/core-java-concurrency-basic-3/pom.xml b/core-java-modules/core-java-concurrency-basic-3/pom.xml index 7771d1200c..7289877550 100644 --- a/core-java-modules/core-java-concurrency-basic-3/pom.xml +++ b/core-java-modules/core-java-concurrency-basic-3/pom.xml @@ -24,4 +24,16 @@ + + 4.2.0 + + + + + org.awaitility + awaitility + ${awaitility.version} + test + + \ No newline at end of file diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/RequestProcessor.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/RequestProcessor.java new file mode 100644 index 0000000000..9557a27f2a --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/RequestProcessor.java @@ -0,0 +1,35 @@ +package com.baeldung.concurrent; + +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +public class RequestProcessor { + + private Map requestStatuses = new HashMap<>(); + + public String processRequest() { + String requestId = UUID.randomUUID().toString(); + requestStatuses.put(requestId, "PROCESSING"); + + ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + executorService.schedule((() -> { + requestStatuses.put(requestId, "DONE"); + }), getRandomNumberBetween(500, 2000), TimeUnit.MILLISECONDS); + + return requestId; + } + + public String getStatus(String requestId) { + return requestStatuses.get(requestId); + } + + private int getRandomNumberBetween(int min, int max) { + Random random = new Random(); + return random.nextInt(max - min) + min; + } +} diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java new file mode 100644 index 0000000000..c437b08b34 --- /dev/null +++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java @@ -0,0 +1,41 @@ +package com.baeldung.concurrent; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.concurrent.TimeUnit; + +import org.awaitility.Awaitility; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +@DisplayName("Request processor") +public class RequestProcessorUnitTest { + + RequestProcessor requestProcessor = new RequestProcessor(); + + @Test + @DisplayName("Wait for completion using Thread.sleep") + void whenWaitingWithThreadSleep_thenStatusIsDone() throws InterruptedException { + String requestId = requestProcessor.processRequest(); + + Thread.sleep(2000); + + assertEquals("DONE", requestProcessor.getStatus(requestId)); + } + + @Test + @DisplayName("Wait for completion using Awaitility") + void whenWaitingWithAwaitility_thenStatusIsDone() { + String requestId = requestProcessor.processRequest(); + + Awaitility.await() + .atMost(2, TimeUnit.SECONDS) + .pollDelay(500, TimeUnit.MILLISECONDS) + .until(() -> requestProcessor.getStatus(requestId), not(equalTo("PROCESSING"))); + + assertEquals("DONE", requestProcessor.getStatus(requestId)); + } + +} From bd2ed439612a0e96e25a4a05ad684f838e72fdea Mon Sep 17 00:00:00 2001 From: sam-gardner <53271849+sam-gardner@users.noreply.github.com> Date: Sat, 18 Feb 2023 04:23:54 +0000 Subject: [PATCH 106/113] =?UTF-8?q?BAEL-6100-Add-example-code-for-integer-?= =?UTF-8?q?array-to-strings-using-streams=E2=80=A6=20(#13375)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * BAEL-6100-Add-example-code-for-integer-array-to-strings-using-streams-tutorial * BAEL-6100 remove wrongly added README update * BAEL-6100 Add interger array to single string example * BAEL-6100 Correct typo in test class name --- .../ArrayConversionUtils.java | 43 +++++++++++++++ .../IntArrayToStringUnitTest.java | 52 +++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/intarraytostrings/ArrayConversionUtils.java create mode 100644 core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/intarraytostrings/IntArrayToStringUnitTest.java diff --git a/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/intarraytostrings/ArrayConversionUtils.java b/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/intarraytostrings/ArrayConversionUtils.java new file mode 100644 index 0000000000..3bb58b43d2 --- /dev/null +++ b/core-java-modules/core-java-streams-4/src/main/java/com/baeldung/streams/intarraytostrings/ArrayConversionUtils.java @@ -0,0 +1,43 @@ +package com.baeldung.streams.intarraytostrings; + +import java.util.Arrays; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +public class ArrayConversionUtils { + + public static void createStreamExample() { + int[] intArray = { 1, 2, 3, 4, 5 }; + IntStream intStream = Arrays.stream(intArray); + + Integer[] integerArray = { 1, 2, 3, 4, 5 }; + Stream integerStream = Arrays.stream(integerArray); + } + + public static String[] convertToStringArray(Integer[] input) { + return Arrays.stream(input) + .map(Object::toString) + .toArray(String[]::new); + } + + public static String[] convertToStringArray(int[] input) { + return Arrays.stream(input) + .mapToObj(Integer::toString) + .toArray(String[]::new); + } + + public static String[] convertToStringArrayWithBoxing(int[] input) { + return Arrays.stream(input) + .boxed() + .map(Object::toString) + .toArray(String[]::new); + } + + public static String convertToString(int[] input){ + return Arrays.stream(input) + .mapToObj(Integer::toString) + .collect(Collectors.joining(", ")); + } + +} diff --git a/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/intarraytostrings/IntArrayToStringUnitTest.java b/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/intarraytostrings/IntArrayToStringUnitTest.java new file mode 100644 index 0000000000..3f6fb0be8e --- /dev/null +++ b/core-java-modules/core-java-streams-4/src/test/java/com/baeldung/streams/intarraytostrings/IntArrayToStringUnitTest.java @@ -0,0 +1,52 @@ +package com.baeldung.streams.intarraytostrings; + +import static com.baeldung.streams.intarraytostrings.ArrayConversionUtils.convertToString; +import static com.baeldung.streams.intarraytostrings.ArrayConversionUtils.convertToStringArray; +import static com.baeldung.streams.intarraytostrings.ArrayConversionUtils.convertToStringArrayWithBoxing; + +import org.junit.Assert; +import org.junit.Test; + +public class IntArrayToStringUnitTest { + + @Test + public void whenConvertingIntegers_thenHandleStreamOfIntegers() { + Integer[] integerNumbers = { 1, 2, 3, 4, 5 }; + String[] expectedOutput = { "1", "2", "3", "4", "5" }; + + String[] strings = convertToStringArray(integerNumbers); + + Assert.assertArrayEquals(expectedOutput, strings); + } + + @Test + public void whenConvertingInts_thenHandleIntStream() { + int[] intNumbers = { 1, 2, 3, 4, 5 }; + String[] expectedOutput = { "1", "2", "3", "4", "5" }; + + String[] strings = convertToStringArray(intNumbers); + + Assert.assertArrayEquals(expectedOutput, strings); + } + + @Test + public void givenAnIntArray_whenBoxingToInteger_thenHandleStreamOfIntegers() { + int[] intNumbers = { 1, 2, 3, 4, 5 }; + String[] expectedOutput = { "1", "2", "3", "4", "5" }; + + String[] strings = convertToStringArrayWithBoxing(intNumbers); + + Assert.assertArrayEquals(expectedOutput, strings); + } + + @Test + public void givenAnIntArray_whenUsingCollectorsJoining_thenReturnCommaSeparatedString(){ + int[] intNumbers = { 1, 2, 3, 4, 5 }; + String expectedOutput = "1, 2, 3, 4, 5"; + + String string = convertToString(intNumbers); + + Assert.assertEquals(expectedOutput, string); + } + +} From 489a570f4bd1322dc4cb9e0b92d633faddf13bb7 Mon Sep 17 00:00:00 2001 From: Shaun Phillips <61982125+ShaPhi7@users.noreply.github.com> Date: Sat, 18 Feb 2023 12:09:04 +0000 Subject: [PATCH 107/113] BAEL-4487 remove padding that causes non-deterministic behaviour (#13425) --- .../com/baeldung/crypto/exception/BadPaddingExamples.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core-java-modules/core-java-security-3/src/main/java/com/baeldung/crypto/exception/BadPaddingExamples.java b/core-java-modules/core-java-security-3/src/main/java/com/baeldung/crypto/exception/BadPaddingExamples.java index 3fff4410e3..135510785f 100644 --- a/core-java-modules/core-java-security-3/src/main/java/com/baeldung/crypto/exception/BadPaddingExamples.java +++ b/core-java-modules/core-java-security-3/src/main/java/com/baeldung/crypto/exception/BadPaddingExamples.java @@ -16,7 +16,7 @@ public class BadPaddingExamples { SecretKey encryptionKey = CryptoUtils.getKeyForText("BaeldungIsASuperCoolSite"); SecretKey differentKey = CryptoUtils.getKeyForText("ThisGivesUsAnAlternative"); - Cipher cipher = Cipher.getInstance("AES/ECB/ISO10126Padding"); + Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, encryptionKey); byte[] cipherTextBytes = cipher.doFinal(plainTextBytes); @@ -28,12 +28,12 @@ public class BadPaddingExamples { public static byte[] encryptAndDecryptUsingDifferentAlgorithms(SecretKey key, IvParameterSpec ivParameterSpec, byte[] plainTextBytes) throws InvalidKeyException, GeneralSecurityException { - Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding"); + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec); byte[] cipherTextBytes = cipher.doFinal(plainTextBytes); - cipher = Cipher.getInstance("AES/ECB/ISO10126Padding"); + cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key); From 35f7dbfcc8d0f03a591075a423801f49b639e2a4 Mon Sep 17 00:00:00 2001 From: Ulisses Lima Date: Sat, 18 Feb 2023 10:27:12 -0300 Subject: [PATCH 108/113] BAEL-6046 - MongoDB - Field Level Encryption (#13494) --- .../boot/csfle/config/MongoClientConfig.java | 7 ------- .../csfle/config/converter/BinaryConverter.java | 13 ------------- .../java/com/baeldung/boot/csfle/data/Citizen.java | 4 +++- .../baeldung/boot/csfle/data/EncryptedCitizen.java | 14 +++++++------- .../boot/csfle/service/CitizenService.java | 14 ++++++++++---- .../boot/csfle/CitizenServiceLiveTest.java | 8 +++++--- .../src/main/resources/application.properties | 7 ++++++- 7 files changed, 31 insertions(+), 36 deletions(-) delete mode 100644 persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/BinaryConverter.java diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java index e63034a5b5..0dff1ec86d 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java @@ -14,9 +14,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration; -import org.springframework.data.mongodb.core.convert.MongoCustomConversions; -import com.baeldung.boot.csfle.config.converter.BinaryConverter; import com.mongodb.AutoEncryptionSettings; import com.mongodb.ClientEncryptionSettings; import com.mongodb.ConnectionString; @@ -50,11 +48,6 @@ public class MongoClientConfig extends AbstractMongoClientConfiguration { return db; } - @Override - public MongoCustomConversions customConversions() { - return new MongoCustomConversions(Arrays.asList(new BinaryConverter())); - } - @Bean @Override public MongoClient mongoClient() { diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/BinaryConverter.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/BinaryConverter.java deleted file mode 100644 index 15231551fc..0000000000 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/converter/BinaryConverter.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.boot.csfle.config.converter; - -import org.bson.BsonBinary; -import org.bson.types.Binary; -import org.springframework.core.convert.converter.Converter; - -public class BinaryConverter implements Converter { - - @Override - public BsonBinary convert(Binary source) { - return new BsonBinary(source.getType(), source.getData()); - } -} diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/Citizen.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/Citizen.java index 9d6496a17b..11e776123a 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/Citizen.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/Citizen.java @@ -13,7 +13,9 @@ public class Citizen { } public Citizen(EncryptedCitizen encryptedCitizen) { - this.name = encryptedCitizen.getName(); + if (encryptedCitizen != null) { + this.name = encryptedCitizen.getName(); + } } public String getName() { diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/EncryptedCitizen.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/EncryptedCitizen.java index 01c9245fbf..c7ca5566a9 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/EncryptedCitizen.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/data/EncryptedCitizen.java @@ -1,14 +1,14 @@ package com.baeldung.boot.csfle.data; -import org.bson.BsonBinary; +import org.bson.types.Binary; import org.springframework.data.mongodb.core.mapping.Document; @Document("citizens") public class EncryptedCitizen { private String name; - private BsonBinary email; - private BsonBinary birthYear; + private Binary email; + private Binary birthYear; public EncryptedCitizen() { } @@ -25,19 +25,19 @@ public class EncryptedCitizen { this.name = name; } - public BsonBinary getEmail() { + public Binary getEmail() { return email; } - public void setEmail(BsonBinary email) { + public void setEmail(Binary email) { this.email = email; } - public BsonBinary getBirthYear() { + public Binary getBirthYear() { return birthYear; } - public void setBirthYear(BsonBinary birthYear) { + public void setBirthYear(Binary birthYear) { this.birthYear = birthYear; } diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java index 91b5940b25..6b3c463d0d 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java @@ -7,6 +7,7 @@ import org.bson.BsonBinary; import org.bson.BsonInt32; import org.bson.BsonString; import org.bson.BsonValue; +import org.bson.types.Binary; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; @@ -65,7 +66,7 @@ public class CitizenService { } } - public BsonBinary encrypt(Object value, String algorithm) { + public Binary encrypt(Object value, String algorithm) { if (value == null) return null; @@ -80,17 +81,22 @@ public class CitizenService { EncryptOptions options = new EncryptOptions(algorithm); options.keyId(encryptionConfig.getDataKeyId()); - return clientEncryption.encrypt(bsonValue, options); + + BsonBinary encryptedValue = clientEncryption.encrypt(bsonValue, options); + return new Binary(encryptedValue.getType(), encryptedValue.getData()); } - public BsonValue decryptProperty(BsonBinary value) { + public BsonValue decryptProperty(Binary value) { if (value == null) return null; - return clientEncryption.decrypt(value); + return clientEncryption.decrypt(new BsonBinary(value.getType(), value.getData())); } private Citizen decrypt(EncryptedCitizen encrypted) { + if (encrypted == null) + return null; + Citizen citizen = new Citizen(encrypted); BsonValue decryptedBirthYear = decryptProperty(encrypted.getBirthYear()); diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/csfle/CitizenServiceLiveTest.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/csfle/CitizenServiceLiveTest.java index 5d0a931bb9..471cb2883a 100644 --- a/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/csfle/CitizenServiceLiveTest.java +++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/csfle/CitizenServiceLiveTest.java @@ -1,8 +1,10 @@ package com.baeldung.boot.csfle; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; -import org.bson.BsonBinary; +import org.bson.types.Binary; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; @@ -36,7 +38,7 @@ public class CitizenServiceLiveTest { citizen.setName("Foo"); citizen.setEmail("foo@citizen.com"); - BsonBinary encryptedEmail = service.encrypt(citizen.getEmail(), CitizenService.DETERMINISTIC_ALGORITHM); + Binary encryptedEmail = service.encrypt(citizen.getEmail(), CitizenService.DETERMINISTIC_ALGORITHM); EncryptedCitizen saved = service.save(citizen); assertEquals(encryptedEmail, saved.getEmail()); diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties index 3ca0cc1242..db4837d8d2 100644 --- a/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties +++ b/persistence-modules/spring-data-jpa-repo-2/src/main/resources/application.properties @@ -3,4 +3,9 @@ spring.datasource.username=sa spring.datasource.password=sa spring.jpa.properties.hibernate.globally_quoted_identifiers=true -logging.level.com.baeldung.spring.data.persistence.search=debug \ No newline at end of file +logging.level.com.baeldung.spring.data.persistence.search=debug + +spring.jpa.show-sql=true +logging.level.org.hibernate.SQL=DEBUG +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE +spring.jpa.properties.hibernate.format_sql=true From 56dfdabe63d0c6f9d594883b7e66bb4b4f14b25f Mon Sep 17 00:00:00 2001 From: Bhaskar Ghosh Dastidar Date: Sat, 18 Feb 2023 22:27:14 +0530 Subject: [PATCH 109/113] [JAVA-6143] java copy from one hashmap to another (#13497) Co-authored-by: Bhaskar --- .../core-java-collections-maps-6/pom.xml | 20 ++++++ .../hashmapcopy/CopyingAHashMapToAnother.java | 47 +++++++++++++ .../CopyHashMapIntoAnotherUnitTest.java | 68 +++++++++++++++++++ core-java-modules/pom.xml | 1 + 4 files changed, 136 insertions(+) create mode 100644 core-java-modules/core-java-collections-maps-6/pom.xml create mode 100644 core-java-modules/core-java-collections-maps-6/src/main/java/com/baeldung/map/hashmapcopy/CopyingAHashMapToAnother.java create mode 100644 core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/hashmapcopy/CopyHashMapIntoAnotherUnitTest.java diff --git a/core-java-modules/core-java-collections-maps-6/pom.xml b/core-java-modules/core-java-collections-maps-6/pom.xml new file mode 100644 index 0000000000..9910d08691 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-6/pom.xml @@ -0,0 +1,20 @@ + + + core-java-collections-maps-6 + 0.1.0-SNAPSHOT + core-java-collections-maps-6 + jar + + core-java-modules + com.baeldung.core-java-modules + 0.0.1-SNAPSHOT + + 4.0.0 + + + 5.2.5.RELEASE + + + \ No newline at end of file diff --git a/core-java-modules/core-java-collections-maps-6/src/main/java/com/baeldung/map/hashmapcopy/CopyingAHashMapToAnother.java b/core-java-modules/core-java-collections-maps-6/src/main/java/com/baeldung/map/hashmapcopy/CopyingAHashMapToAnother.java new file mode 100644 index 0000000000..77a6402a75 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-6/src/main/java/com/baeldung/map/hashmapcopy/CopyingAHashMapToAnother.java @@ -0,0 +1,47 @@ +package com.baeldung.map.hashmapcopy; + +import java.util.Map; + +import com.google.common.collect.MapDifference; +import com.google.common.collect.Maps; + +public class CopyingAHashMapToAnother { + public Map copyByIteration(Map sourceMap, Map targetMap) { + for (Map.Entry entry : sourceMap.entrySet()) { + if (!targetMap.containsKey(entry.getKey())) { + targetMap.put(entry.getKey(), entry.getValue()); + } + } + return targetMap; + } + + public Map copyUsingPutAll(Map sourceMap, Map targetMap) { + sourceMap.keySet() + .removeAll(targetMap.keySet()); + targetMap.putAll(sourceMap); + return targetMap; + } + + public Map copyUsingPutIfAbsent(Map sourceMap, Map targetMap) { + for (Map.Entry entry : sourceMap.entrySet()) { + targetMap.putIfAbsent(entry.getKey(), entry.getValue()); + } + return targetMap; + } + + public Map copyUsingPutIfAbsentForEach(Map sourceMap, Map targetMap) { + sourceMap.forEach(targetMap::putIfAbsent); + return targetMap; + } + + public Map copyUsingMapMerge(Map sourceMap, Map targetMap) { + sourceMap.forEach((key, value) -> targetMap.merge(key, value, (oldVal, newVal) -> oldVal)); + return targetMap; + } + + public Map copyUsingGuavaMapDifference(Map sourceMap, Map targetMap) { + MapDifference differenceMap = Maps.difference(sourceMap, targetMap); + targetMap.putAll(differenceMap.entriesOnlyOnLeft()); + return targetMap; + } +} diff --git a/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/hashmapcopy/CopyHashMapIntoAnotherUnitTest.java b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/hashmapcopy/CopyHashMapIntoAnotherUnitTest.java new file mode 100644 index 0000000000..b11f470eb3 --- /dev/null +++ b/core-java-modules/core-java-collections-maps-6/src/test/java/com/baeldung/map/hashmapcopy/CopyHashMapIntoAnotherUnitTest.java @@ -0,0 +1,68 @@ +package com.baeldung.map.hashmapcopy; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; + +import com.baeldung.map.hashmapcopy.CopyingAHashMapToAnother; + +public class CopyHashMapIntoAnotherUnitTest { + @Test + public void givenSourceAndTargetMapsWhenIteratedOverThenCopyingSuccess(){ + CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother(); + Assert.assertEquals(generateExpectedResultMap(), obj.copyByIteration(generateSourceMap(), generateTargetMap())); + } + + @Test + public void givenSourceAndTargetMapsWhenUsedPutAllThenCopyingSuccess(){ + CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother(); + Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingPutAll(generateSourceMap(), generateTargetMap())); + } + + @Test + public void givenSourceAndTargetMapsWhenUsedPutIfAbsentThenCopyingSuccess(){ + CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother(); + Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingPutIfAbsent(generateSourceMap(), generateTargetMap())); + Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingPutIfAbsentForEach(generateSourceMap(), generateTargetMap())); + } + + @Test + public void givenSourceAndTargetMapsWhenUsedMapMergeThenCopyingSuccess(){ + CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother(); + Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingMapMerge(generateSourceMap(), generateTargetMap())); + } + + @Test + public void givenSourceAndTargetMapsWhenMapDifferenceUsedThenCopyingSuccess(){ + CopyingAHashMapToAnother obj = new CopyingAHashMapToAnother(); + Assert.assertEquals(generateExpectedResultMap(), obj.copyUsingGuavaMapDifference(generateSourceMap(), generateTargetMap())); + } + + private Map generateSourceMap(){ + Map sourceMap = new HashMap<>(); + sourceMap.put("India", "Delhi"); + sourceMap.put("United States", "Washington D.C."); + sourceMap.put("United Kingdom", "London DC"); + return sourceMap; + } + + private Map generateTargetMap(){ + Map targetMap = new HashMap<>(); + targetMap.put("Zimbabwe", "Harare"); + targetMap.put("Norway", "Oslo"); + targetMap.put("United Kingdom", "London"); + return targetMap; + } + + private Map generateExpectedResultMap(){ + Map resultMap = new HashMap<>(); + resultMap.put("India", "Delhi"); + resultMap.put("United States", "Washington D.C."); + resultMap.put("United Kingdom", "London"); + resultMap.put("Zimbabwe", "Harare"); + resultMap.put("Norway", "Oslo"); + return resultMap; + } +} diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 612e607a38..1033213cd1 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -132,6 +132,7 @@ core-java-regex-2 core-java-uuid pre-jpms + core-java-collections-maps-6 From 66df38979081c3bc77e12635ecdb8ae453757aca Mon Sep 17 00:00:00 2001 From: edizor <113095366+edizor@users.noreply.github.com> Date: Sun, 19 Feb 2023 08:02:49 +0800 Subject: [PATCH 110/113] Update README.md [skip ci] --- core-java-modules/core-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md index 0000962164..6d9bbe03c2 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -10,3 +10,4 @@ - [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) - [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error) - [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class) +- [Difference Between Class.forName() and Class.forName().newInstance()](https://www.baeldung.com/java-class-forname-vs-class-forname-newinstance) From 39283b7aae53a028849deb08f70318b324d01380 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 19 Feb 2023 13:21:39 +0200 Subject: [PATCH 111/113] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3c31b7fba1..697d96c4fa 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ The projects are broadly divided into 3 lists: first, second and heavy. Next, they are segregated further on the basis of the tests that we want to execute. -Additionally, there are 2 profiles dedicated for JDK9 and above builds. +Additionally, there are 2 profiles dedicated for JDK9 and above builds - *which require JDK 17*. We also have a parents profile to build only parent modules. From e06cd8cea1c96883048d892549f1218a8103a8b9 Mon Sep 17 00:00:00 2001 From: Loredana Crusoveanu Date: Sun, 19 Feb 2023 13:22:44 +0200 Subject: [PATCH 112/113] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 697d96c4fa..7ed1e6990a 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ The projects are broadly divided into 3 lists: first, second and heavy. Next, they are segregated further on the basis of the tests that we want to execute. -Additionally, there are 2 profiles dedicated for JDK9 and above builds - *which require JDK 17*. +Additionally, there are 2 profiles dedicated for JDK9 and above builds - **which require JDK 17**. We also have a parents profile to build only parent modules. From 471433c41c250b3a626b9514ceb74679e4d66742 Mon Sep 17 00:00:00 2001 From: Hamid Reza Sharifi Date: Sun, 19 Feb 2023 17:53:38 +0330 Subject: [PATCH 113/113] Bael 5190: Verify Digital Signatures in Java article (#13439) * #BAEL-5190: add keystore and certificate files * #BAEL-5190: add keystore address * #BAEL-5190: update hashing * #BAEL-5190: delete main classes * #BAEL-5190: move keystore files to test directory * #BAEL-5190: rename to DigitalSignatureUtils * #BAEL-5190: main source code * #BAEL-5190: main test source * #BAEL-5190: update for testing * #BAEL-5190: update keystore type * #BAEL-5190: remove p12 keystores * #BAEL-5190: add jks keystores --------- Co-authored-by: h_sharifi --- .../DigitalSignatureUtils.java | 86 ++++++++++++++++++ .../com/baeldung/digitalsignature/Utils.java | 33 ------- ...tureWithMessageDigestAndCipherSigning.java | 28 ------ ...reWithMessageDigestAndCipherVerifying.java | 33 ------- .../DigitalSignatureWithSignatureSigning.java | 27 ------ ...igitalSignatureWithSignatureVerifying.java | 28 ------ .../DigitalSignatureUnitTest.java | 76 ++++++++++++++++ .../digitalsignature/receiver_keystore.jks | Bin 0 -> 785 bytes .../digitalsignature/sender_certificate.cer | 17 ++++ .../digitalsignature/sender_keystore.jks | Bin 0 -> 2072 bytes 10 files changed, 179 insertions(+), 149 deletions(-) create mode 100644 libraries-security/src/main/java/com/baeldung/digitalsignature/DigitalSignatureUtils.java delete mode 100644 libraries-security/src/main/java/com/baeldung/digitalsignature/Utils.java delete mode 100644 libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherSigning.java delete mode 100644 libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherVerifying.java delete mode 100644 libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureSigning.java delete mode 100644 libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureVerifying.java create mode 100644 libraries-security/src/test/java/com/baeldung/digitalsignature/DigitalSignatureUnitTest.java create mode 100644 libraries-security/src/test/resources/digitalsignature/receiver_keystore.jks create mode 100644 libraries-security/src/test/resources/digitalsignature/sender_certificate.cer create mode 100644 libraries-security/src/test/resources/digitalsignature/sender_keystore.jks diff --git a/libraries-security/src/main/java/com/baeldung/digitalsignature/DigitalSignatureUtils.java b/libraries-security/src/main/java/com/baeldung/digitalsignature/DigitalSignatureUtils.java new file mode 100644 index 0000000000..cc0da187b9 --- /dev/null +++ b/libraries-security/src/main/java/com/baeldung/digitalsignature/DigitalSignatureUtils.java @@ -0,0 +1,86 @@ +package com.baeldung.digitalsignature; + +import org.bouncycastle.asn1.x509.AlgorithmIdentifier; +import org.bouncycastle.asn1.x509.DigestInfo; +import org.bouncycastle.operator.DefaultDigestAlgorithmIdentifierFinder; +import org.bouncycastle.operator.DigestAlgorithmIdentifierFinder; + +import javax.crypto.Cipher; +import java.io.FileInputStream; +import java.io.IOException; +import java.security.*; +import java.security.cert.Certificate; +import java.util.Arrays; + +public class DigitalSignatureUtils { + + public static PrivateKey getPrivateKey(String file, char[] password, String storeType, String alias) throws Exception { + KeyStore keyStore = KeyStore.getInstance(storeType); + keyStore.load(new FileInputStream(file), password); + return (PrivateKey) keyStore.getKey(alias, password); + } + + public static PublicKey getPublicKey(String file, char[] password, String storeType, String alias) throws Exception { + KeyStore keyStore = KeyStore.getInstance(storeType); + keyStore.load(new FileInputStream(file), password); + Certificate certificate = keyStore.getCertificate(alias); + return certificate.getPublicKey(); + } + + public static byte[] sign(byte[] message, String signingAlgorithm, PrivateKey signingKey) throws SecurityException { + try { + Signature signature = Signature.getInstance(signingAlgorithm); + signature.initSign(signingKey); + signature.update(message); + return signature.sign(); + } catch (GeneralSecurityException exp) { + throw new SecurityException("Error during signature generation", exp); + } + } + + public static boolean verify(byte[] messageBytes, String signingAlgorithm, PublicKey publicKey, byte[] signedData) { + try { + Signature signature = Signature.getInstance(signingAlgorithm); + signature.initVerify(publicKey); + signature.update(messageBytes); + return signature.verify(signedData); + } catch (GeneralSecurityException exp) { + throw new SecurityException("Error during verifying", exp); + } + } + + public static byte[] signWithMessageDigestAndCipher(byte[] messageBytes, String hashingAlgorithm, PrivateKey privateKey) { + try { + MessageDigest md = MessageDigest.getInstance(hashingAlgorithm); + byte[] messageHash = md.digest(messageBytes); + DigestAlgorithmIdentifierFinder hashAlgorithmFinder = new DefaultDigestAlgorithmIdentifierFinder(); + AlgorithmIdentifier hashingAlgorithmIdentifier = hashAlgorithmFinder.find(hashingAlgorithm); + DigestInfo digestInfo = new DigestInfo(hashingAlgorithmIdentifier, messageHash); + byte[] hashToEncrypt = digestInfo.getEncoded(); + + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.ENCRYPT_MODE, privateKey); + return cipher.doFinal(hashToEncrypt); + } catch (GeneralSecurityException | IOException exp) { + throw new SecurityException("Error during signature generation", exp); + } + } + + public static boolean verifyWithMessageDigestAndCipher(byte[] messageBytes, String hashingAlgorithm, PublicKey publicKey, byte[] encryptedMessageHash) { + try { + MessageDigest md = MessageDigest.getInstance(hashingAlgorithm); + byte[] newMessageHash = md.digest(messageBytes); + DigestAlgorithmIdentifierFinder hashAlgorithmFinder = new DefaultDigestAlgorithmIdentifierFinder(); + AlgorithmIdentifier hashingAlgorithmIdentifier = hashAlgorithmFinder.find(hashingAlgorithm); + DigestInfo digestInfo = new DigestInfo(hashingAlgorithmIdentifier, newMessageHash); + byte[] hashToEncrypt = digestInfo.getEncoded(); + + Cipher cipher = Cipher.getInstance("RSA"); + cipher.init(Cipher.DECRYPT_MODE, publicKey); + byte[] decryptedMessageHash = cipher.doFinal(encryptedMessageHash); + return Arrays.equals(decryptedMessageHash, hashToEncrypt); + } catch (GeneralSecurityException | IOException exp) { + throw new SecurityException("Error during verifying", exp); + } + } +} diff --git a/libraries-security/src/main/java/com/baeldung/digitalsignature/Utils.java b/libraries-security/src/main/java/com/baeldung/digitalsignature/Utils.java deleted file mode 100644 index 9f1e5808c3..0000000000 --- a/libraries-security/src/main/java/com/baeldung/digitalsignature/Utils.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.digitalsignature; - -import java.io.FileInputStream; -import java.security.KeyStore; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.cert.Certificate; - -public class Utils { - - private static final String STORE_TYPE = "PKCS12"; - private static final char[] PASSWORD = "changeit".toCharArray(); - private static final String SENDER_KEYSTORE = "sender_keystore.p12"; - private static final String SENDER_ALIAS = "senderKeyPair"; - - public static final String SIGNING_ALGORITHM = "SHA256withRSA"; - - private static final String RECEIVER_KEYSTORE = "receiver_keystore.p12"; - private static final String RECEIVER_ALIAS = "receiverKeyPair"; - - public static PrivateKey getPrivateKey() throws Exception { - KeyStore keyStore = KeyStore.getInstance(STORE_TYPE); - keyStore.load(new FileInputStream(SENDER_KEYSTORE), PASSWORD); - return (PrivateKey) keyStore.getKey(SENDER_ALIAS, PASSWORD); - } - - public static PublicKey getPublicKey() throws Exception { - KeyStore keyStore = KeyStore.getInstance(STORE_TYPE); - keyStore.load(new FileInputStream(RECEIVER_KEYSTORE), PASSWORD); - Certificate certificate = keyStore.getCertificate(RECEIVER_ALIAS); - return certificate.getPublicKey(); - } -} diff --git a/libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherSigning.java b/libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherSigning.java deleted file mode 100644 index 78d40dd365..0000000000 --- a/libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherSigning.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.digitalsignature.level1; - -import com.baeldung.digitalsignature.Utils; - -import javax.crypto.Cipher; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.MessageDigest; -import java.security.PrivateKey; - -public class DigitalSignatureWithMessageDigestAndCipherSigning { - - public static void main(String[] args) throws Exception { - - PrivateKey privateKey = Utils.getPrivateKey(); - - byte[] messageBytes = Files.readAllBytes(Paths.get("src/test/resources/digitalsignature/message.txt")); - - MessageDigest md = MessageDigest.getInstance("SHA-256"); - byte[] messageHash = md.digest(messageBytes); - - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.ENCRYPT_MODE, privateKey); - byte[] digitalSignature = cipher.doFinal(messageHash); - - Files.write(Paths.get("target/digital_signature_1"), digitalSignature); - } -} diff --git a/libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherVerifying.java b/libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherVerifying.java deleted file mode 100644 index 0b242a44fb..0000000000 --- a/libraries-security/src/main/java/com/baeldung/digitalsignature/level1/DigitalSignatureWithMessageDigestAndCipherVerifying.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.baeldung.digitalsignature.level1; - -import com.baeldung.digitalsignature.Utils; - -import javax.crypto.Cipher; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.MessageDigest; -import java.security.PublicKey; -import java.util.Arrays; - -public class DigitalSignatureWithMessageDigestAndCipherVerifying { - - public static void main(String[] args) throws Exception { - - PublicKey publicKey = Utils.getPublicKey(); - - byte[] messageBytes = Files.readAllBytes(Paths.get("src/test/resources/digitalsignature/message.txt")); - - MessageDigest md = MessageDigest.getInstance("SHA-256"); - byte[] newMessageHash = md.digest(messageBytes); - - byte[] encryptedMessageHash = Files.readAllBytes(Paths.get("target/digital_signature_1")); - - Cipher cipher = Cipher.getInstance("RSA"); - cipher.init(Cipher.DECRYPT_MODE, publicKey); - byte[] decryptedMessageHash = cipher.doFinal(encryptedMessageHash); - - boolean isCorrect = Arrays.equals(decryptedMessageHash, newMessageHash); - System.out.println("Signature " + (isCorrect ? "correct" : "incorrect")); - } - -} diff --git a/libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureSigning.java b/libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureSigning.java deleted file mode 100644 index afc8fd1045..0000000000 --- a/libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureSigning.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.digitalsignature.level2; - -import com.baeldung.digitalsignature.Utils; - -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.PrivateKey; -import java.security.Signature; - -public class DigitalSignatureWithSignatureSigning { - - public static void main(String[] args) throws Exception { - - PrivateKey privateKey = Utils.getPrivateKey(); - - Signature signature = Signature.getInstance(Utils.SIGNING_ALGORITHM); - signature.initSign(privateKey); - - byte[] messageBytes = Files.readAllBytes(Paths.get("src/test/resources/digitalsignature/message.txt")); - - signature.update(messageBytes); - byte[] digitalSignature = signature.sign(); - - Files.write(Paths.get("target/digital_signature_2"), digitalSignature); - } - -} diff --git a/libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureVerifying.java b/libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureVerifying.java deleted file mode 100644 index ee34be989c..0000000000 --- a/libraries-security/src/main/java/com/baeldung/digitalsignature/level2/DigitalSignatureWithSignatureVerifying.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.baeldung.digitalsignature.level2; - -import com.baeldung.digitalsignature.Utils; - -import java.nio.file.Files; -import java.nio.file.Paths; -import java.security.PublicKey; -import java.security.Signature; - -public class DigitalSignatureWithSignatureVerifying { - - public static void main(String[] args) throws Exception { - - PublicKey publicKey = Utils.getPublicKey(); - - byte[] sig = Files.readAllBytes(Paths.get("target/digital_signature_2")); - - Signature signature = Signature.getInstance(Utils.SIGNING_ALGORITHM); - signature.initVerify(publicKey); - - byte[] messageBytes = Files.readAllBytes(Paths.get("src/test/resources/digitalsignature/message.txt")); - - signature.update(messageBytes); - - boolean isCorrect = signature.verify(sig); - System.out.println("Signature " + (isCorrect ? "correct" : "incorrect")); - } -} diff --git a/libraries-security/src/test/java/com/baeldung/digitalsignature/DigitalSignatureUnitTest.java b/libraries-security/src/test/java/com/baeldung/digitalsignature/DigitalSignatureUnitTest.java new file mode 100644 index 0000000000..65058dca52 --- /dev/null +++ b/libraries-security/src/test/java/com/baeldung/digitalsignature/DigitalSignatureUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.digitalsignature; + +import org.junit.Test; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.PrivateKey; +import java.security.PublicKey; + +import static org.junit.Assert.assertTrue; + +public class DigitalSignatureUnitTest { + + String messagePath = "src/test/resources/digitalsignature/message.txt"; + String senderKeyStore = "src/test/resources/digitalsignature/sender_keystore.jks"; + String receiverKeyStore = "src/test/resources/digitalsignature/receiver_keystore.jks"; + String storeType = "JKS"; + String senderAlias = "senderKeyPair"; + String receiverAlias = "receiverKeyPair"; + char[] password = "changeit".toCharArray(); + String signingAlgorithm = "SHA256withRSA"; + String hashingAlgorithm = "SHA-256"; + + @Test + public void givenMessageData_whenSignWithSignatureSigning_thenVerify() throws Exception { + PrivateKey privateKey = DigitalSignatureUtils.getPrivateKey(senderKeyStore, password, storeType, senderAlias); + byte[] messageBytes = Files.readAllBytes(Paths.get(messagePath)); + + byte[] digitalSignature = DigitalSignatureUtils.sign(messageBytes, signingAlgorithm, privateKey); + + PublicKey publicKey = DigitalSignatureUtils.getPublicKey(receiverKeyStore, password, storeType, receiverAlias); + boolean isCorrect = DigitalSignatureUtils.verify(messageBytes, signingAlgorithm, publicKey, digitalSignature); + + assertTrue(isCorrect); + } + + @Test + public void givenMessageData_whenSignWithMessageDigestAndCipher_thenVerify() throws Exception { + PrivateKey privateKey = DigitalSignatureUtils.getPrivateKey(senderKeyStore, password, storeType, senderAlias); + byte[] messageBytes = Files.readAllBytes(Paths.get(messagePath)); + + byte[] encryptedMessageHash = DigitalSignatureUtils.signWithMessageDigestAndCipher(messageBytes, hashingAlgorithm, privateKey); + + PublicKey publicKey = DigitalSignatureUtils.getPublicKey(receiverKeyStore, password, storeType, receiverAlias); + boolean isCorrect = DigitalSignatureUtils.verifyWithMessageDigestAndCipher(messageBytes, hashingAlgorithm, publicKey, encryptedMessageHash); + + assertTrue(isCorrect); + } + + @Test + public void givenMessageData_whenSignWithSignatureSigning_thenVerifyWithMessageDigestAndCipher() throws Exception { + PrivateKey privateKey = DigitalSignatureUtils.getPrivateKey(senderKeyStore, password, storeType, senderAlias); + byte[] messageBytes = Files.readAllBytes(Paths.get(messagePath)); + + byte[] digitalSignature = DigitalSignatureUtils.sign(messageBytes, signingAlgorithm, privateKey); + + PublicKey publicKey = DigitalSignatureUtils.getPublicKey(receiverKeyStore, password, storeType, receiverAlias); + boolean isCorrect = DigitalSignatureUtils.verifyWithMessageDigestAndCipher(messageBytes, hashingAlgorithm, publicKey, digitalSignature); + + assertTrue(isCorrect); + } + + @Test + public void givenMessageData_whenSignWithMessageDigestAndCipher_thenVerifyWithSignature() throws Exception { + PrivateKey privateKey = DigitalSignatureUtils.getPrivateKey(senderKeyStore, password, storeType, senderAlias); + byte[] messageBytes = Files.readAllBytes(Paths.get(messagePath)); + + byte[] encryptedMessageHash = DigitalSignatureUtils.signWithMessageDigestAndCipher(messageBytes, hashingAlgorithm, privateKey); + + PublicKey publicKey = DigitalSignatureUtils.getPublicKey(receiverKeyStore, password, storeType, receiverAlias); + boolean isCorrect = DigitalSignatureUtils.verify(messageBytes, signingAlgorithm, publicKey, encryptedMessageHash); + + assertTrue(isCorrect); + } + +} diff --git a/libraries-security/src/test/resources/digitalsignature/receiver_keystore.jks b/libraries-security/src/test/resources/digitalsignature/receiver_keystore.jks new file mode 100644 index 0000000000000000000000000000000000000000..184b5b8600adc83b8e40ccd9f91ba17045004a9b GIT binary patch literal 785 zcmezO_TO6u1_mY|W(3pxMXAZDnPsU(*{PKUiJ3(}@wN;f#ySSp2t88+OQ6z|22D&y z4VoC&E?{P2WMX2;3ftCXz{|#|)#lOmotKf3o0Y*p*ig`bpN%<`g;|)xDKRxCr8FLhAedPAsq7C0_d7+T*5}p^f>wqx1e}7~baHz@YW>|L>kD zbInrlHW4XSpI&&l6Zw+imPuO4SC#9F9zK+{?Fn;SXRdP0%C5>&`Fdr<>QB|laR;l#zCC zu54#wW@KPotY{!_APWp{Sw0pq77@p&4e1M1&4TY$IxjnX-eLE-<(F?D2O=VfiIljs!1(Pjg(an_ZuG_h*drj+Ae&J|2FTWM39vZtI)guF`nSx-7y_?_P$8 z_mc`IzlGbA40L9%pIx~=hV}csbjIxhoF%)r@8Rg1*uB>3$qS3k?$*g=o(l7nUY?5% zTYPW%;l+0vLjrgV&%duMPP+c}_~~|;;~(x$Jez%N!G!FY$#IU}U17nDA)>$Lf0T(z znDjS{&z)E8!2JBOtGn0fuNxQ11W$1pzRE z1pP1$1_~<%0R#am0uccL1pows1nH#M%}(`SxrW@K;Iqy^j*%zT*uBod0)-sit*PE# z{c3x!vMP18A?!HPeoD~c6&pfBp?jTnIMf1wP*qa#3%qJW8zNY5sw6Z$s^PwS^^^$Bui1y)!SMtGrQ=*u z1R^)5VPi>Gh30`MHVj%i4~d6EZARIgGITFF_b@v4tCfF(xIiQP50TnQxYL=0rVxjZ znJi!ht=&e;SG6@Q!+;0KcB`FXWy4Xc$Vii>Xye%>Kx(41D!XYQpq)Ab`Bg8F z)Y)wL=6m;ZNL)c3L&WL0J`~3g8_=!4NjA%(eR)iHp#GeD{=>E_C`uT}tb;0k&r|tW z@ZBL`LYG`ntkG~ShR(=`IC2)L8RsBte zlx$rdI~`f@E!;`^n@06nqf@JzpRB%KE^y$W?Ib~<1|?zoGk?G;i>nzMcF{T?@zz#m z$F!hO_dW-em9nN^+BAoitdSn-Q%C>Oud|UOya#E_#X6^Q=X@cp1hHR!F7J2Yai*m% zw>nNW(;?jSlRu1LnTz9#tGX?B|Hta+_Ws#1kI-jgPFyastr!XbeKe?WF`ZLHPVh|S zlIl_#mcBKku$is}nd&?D!6RqG55dm~Tw+LizO!0kob#yIxr3K(I<) z`C7KZKC0ilO%jGwG`S7xL)rdI&ijYfUz!V}@$%Kq`=#?&5fbsX)^QJ_Z{KZnu-))w zFk)v&LNQUHXL zinl@8Hnf`s*J+uC!rJg=^t`2aW_kfsGIjy?WJ&kP_=$+(y>TVO2*n}J7)7q(LMJLQ z_O%~yRJ1$@rm0smSjbAgQ(yrtbAZ%*j0Ws1T}Q!#9mpt>}25+}b- z$ftR_7j^eLNZA%KJU8yep8seu+YPV)D*6BWjFg?ukMGQPn@2^|#2r{as}orf`kqs8 z+8?x$Gauh@q+cM$)s1Sf6iPCKqHA3ni)}&ehklfrG-h=5B-f(h;T=7URza>eB*r>E zdPyVKd04CRdt+X~d(Nb`sqtiYb_M#Mrqs6r0|5X5qaiRKFdYU1RUHll76cSQTCiuJ zB{oyuc|)ed&p^A*r_hZ(wVn23YcRfvKha`ckZYM^UO`KWR#O2~75bm?99m$K{Z!Z+2th8BO6D2nI_^z*cl6 zA=~p>#*LO!R)3)ruCd&BC*>-`u6o;JI5t!QsG0Sl9ra@a7;^1r4|vSuSRf^!+Ktl3 z-^JUk2X-;%`V2wYo;eQpbgUCD2zsz2Lh;J_A9GPOm_iK;!OR@NDoZSZt9V-idlWB6 C3dLFg literal 0 HcmV?d00001