diff --git a/akka-http/pom.xml b/akka-http/pom.xml index c0b460dd8e..c146e58b60 100644 --- a/akka-http/pom.xml +++ b/akka-http/pom.xml @@ -38,8 +38,6 @@ - UTF-8 - UTF-8 10.0.11 2.5.11 diff --git a/algorithms-miscellaneous-3/pom.xml b/algorithms-miscellaneous-3/pom.xml index 877e8bfefa..4b67a30abb 100644 --- a/algorithms-miscellaneous-3/pom.xml +++ b/algorithms-miscellaneous-3/pom.xml @@ -91,8 +91,6 @@ 4.3 28.0-jre 2.6.0 - 1.19 - 1.19 3.8.1 1.1.0 diff --git a/apache-libraries/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java b/apache-libraries/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerIntegrationTest.java similarity index 97% rename from apache-libraries/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java rename to apache-libraries/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerIntegrationTest.java index 992ea806c3..3d413e1939 100644 --- a/apache-libraries/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java +++ b/apache-libraries/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerIntegrationTest.java @@ -13,7 +13,7 @@ import java.util.Objects; import static org.junit.Assert.*; -public class AvroSerealizerDeSerealizerUnitTest { +public class AvroSerealizerDeSerealizerIntegrationTest { AvroSerealizer serealizer; AvroDeSerealizer deSerealizer; diff --git a/apache-libraries/src/test/java/com/baeldung/meecrowave/ArticleEndpointsUnitTest.java b/apache-libraries/src/test/java/com/baeldung/meecrowave/ArticleEndpointsIntegrationTest.java similarity index 95% rename from apache-libraries/src/test/java/com/baeldung/meecrowave/ArticleEndpointsUnitTest.java rename to apache-libraries/src/test/java/com/baeldung/meecrowave/ArticleEndpointsIntegrationTest.java index f9a06fd7b9..dbd777231c 100644 --- a/apache-libraries/src/test/java/com/baeldung/meecrowave/ArticleEndpointsUnitTest.java +++ b/apache-libraries/src/test/java/com/baeldung/meecrowave/ArticleEndpointsIntegrationTest.java @@ -17,7 +17,7 @@ import okhttp3.Request; import okhttp3.Response; @RunWith(MonoMeecrowave.Runner.class) -public class ArticleEndpointsUnitTest { +public class ArticleEndpointsIntegrationTest { @ConfigurationInject private Meecrowave.Builder config; diff --git a/aws-reactive/pom.xml b/aws-reactive/pom.xml index d4f0e5e231..6224ccbb99 100644 --- a/aws-reactive/pom.xml +++ b/aws-reactive/pom.xml @@ -100,7 +100,6 @@ - 1.8 2.2.1.RELEASE 2.10.27 diff --git a/core-groovy-2/pom.xml b/core-groovy-2/pom.xml index b1bfa19771..207c090615 100644 --- a/core-groovy-2/pom.xml +++ b/core-groovy-2/pom.xml @@ -115,7 +115,6 @@ maven-surefire-plugin - ${surefire.plugin.version} false @@ -186,7 +185,6 @@ 1.2.3 2.5.7 3.1.0 - 2.20.1 3.8.0 3.3.0-01 diff --git a/core-groovy-collections/pom.xml b/core-groovy-collections/pom.xml index 125dfca4c1..770bcc57d6 100644 --- a/core-groovy-collections/pom.xml +++ b/core-groovy-collections/pom.xml @@ -101,7 +101,6 @@ maven-surefire-plugin - ${surefire.plugin.version} false @@ -128,7 +127,6 @@ 2.4.0 1.1-groovy-2.4 1.6 - 2.20.1 diff --git a/core-java-modules/core-java-11/pom.xml b/core-java-modules/core-java-11/pom.xml index 2f7f5a6bcf..cdb3aab2c7 100644 --- a/core-java-modules/core-java-11/pom.xml +++ b/core-java-modules/core-java-11/pom.xml @@ -32,12 +32,12 @@ org.openjdk.jmh jmh-core - ${jmh.version} + ${jmh-core.version} org.openjdk.jmh jmh-generator-annprocess - ${jmh.version} + ${jmh-generator.version} provided @@ -105,7 +105,6 @@ 27.1-jre 3.11.1 benchmarks - 1.22 10.0.0 3.2.4 diff --git a/core-java-modules/core-java-arrays-guides/pom.xml b/core-java-modules/core-java-arrays-guides/pom.xml index df8639820d..a7c996cf7e 100644 --- a/core-java-modules/core-java-arrays-guides/pom.xml +++ b/core-java-modules/core-java-arrays-guides/pom.xml @@ -17,16 +17,18 @@ org.openjdk.jmh jmh-core - ${jmh.version} + ${jmh-core.version} org.openjdk.jmh jmh-generator-annprocess - ${jmh.version} + ${jmh-generator.version} + + + org.assertj + assertj-core + 3.19.0 + test - - - 1.19 - \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-guides/src/test/java/com/baeldung/genericarrays/ListToArrayUnitTest.java b/core-java-modules/core-java-arrays-guides/src/test/java/com/baeldung/genericarrays/ListToArrayUnitTest.java index 5fd0385181..df7e0566ed 100644 --- a/core-java-modules/core-java-arrays-guides/src/test/java/com/baeldung/genericarrays/ListToArrayUnitTest.java +++ b/core-java-modules/core-java-arrays-guides/src/test/java/com/baeldung/genericarrays/ListToArrayUnitTest.java @@ -2,7 +2,6 @@ package com.baeldung.genericarrays; import org.junit.Test; -import java.util.ArrayList; import java.util.LinkedList; import java.util.List; diff --git a/core-java-modules/core-java-arrays-guides/src/test/java/com/baeldung/genericarrays/StreamToArrayUnitTest.java b/core-java-modules/core-java-arrays-guides/src/test/java/com/baeldung/genericarrays/StreamToArrayUnitTest.java new file mode 100644 index 0000000000..5dea901b25 --- /dev/null +++ b/core-java-modules/core-java-arrays-guides/src/test/java/com/baeldung/genericarrays/StreamToArrayUnitTest.java @@ -0,0 +1,77 @@ +package com.baeldung.genericarrays; + +import org.junit.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.IntFunction; +import java.util.stream.Stream; + +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class StreamToArrayUnitTest { + + @Test + public void givenAStream_thenCanGetArrayOfObject() { + Object[] strings = Stream.of("A", "AAA", "B", "AAB", "C") + .filter(string -> string.startsWith("A")) + .toArray(); + + assertThat(strings).containsExactly("A", "AAA", "AAB"); + assertThat(strings).isNotInstanceOf(String[].class); + } + + @Test + public void givenAStream_thenCanGetArrayOfString() { + String[] strings = Stream.of("A", "AAA", "B", "AAB", "C") + .filter(string -> string.startsWith("A")) + .toArray(String[]::new); + + assertThat(strings).containsExactly("A", "AAA", "AAB"); + assertThat(strings).isInstanceOf(String[].class); + } + + @SuppressWarnings("unchecked") + @Test + public void givenAStream_whenConvertToOptional_thenCanGetArrayOfOptional() { + Stream> stream = Stream.of("A", "AAA", "B", "AAB", "C") + .filter(string -> string.startsWith("A")) + .map(Optional::of); + Optional[] strings = stream + .toArray(Optional[]::new); + + assertThat(strings).containsExactly(Optional.of("A"), + Optional.of("AAA"), + Optional.of("AAB")); + assertThat(strings).isInstanceOf(Optional[].class); + } + + @Test + public void givenAStream_whenConvertToOptional_thenCanGetArrayOfOptionalWithHelper() { + Optional[] strings = Stream.of("A", "AAA", "B", "AAB", "C") + .filter(string -> string.startsWith("A")) + .map(Optional::of) + .toArray(genericArray(Optional[]::new)); + + assertThat(strings).containsExactly(Optional.of("A"), + Optional.of("AAA"), + Optional.of("AAB")); + assertThat(strings).isInstanceOf(Optional[].class); + } + + @Test + public void whenInvalidUseOfGenericArray_thenIllegalCast() { + assertThatThrownBy(() -> { + ArrayList[] lists = Stream.of(singletonList("A")) + .toArray(genericArray(List[]::new)); + }).isInstanceOf(ClassCastException.class); + } + + @SuppressWarnings("unchecked") + private static IntFunction genericArray(IntFunction arrayCreator) { + return size -> (R[])arrayCreator.apply(size); + } +} diff --git a/core-java-modules/core-java-arrays-operations-basic/pom.xml b/core-java-modules/core-java-arrays-operations-basic/pom.xml index dcee6547a0..9157d9deb9 100644 --- a/core-java-modules/core-java-arrays-operations-basic/pom.xml +++ b/core-java-modules/core-java-arrays-operations-basic/pom.xml @@ -24,12 +24,12 @@ org.openjdk.jmh jmh-core - ${jmh.version} + ${jmh-core.version} org.openjdk.jmh jmh-generator-annprocess - ${jmh.version} + ${jmh-generator.version} @@ -68,7 +68,6 @@ 3.2.0 - 1.19 3.10.0 \ No newline at end of file diff --git a/core-java-modules/core-java-arrays-sorting/pom.xml b/core-java-modules/core-java-arrays-sorting/pom.xml index 9b900c3de6..610582260b 100644 --- a/core-java-modules/core-java-arrays-sorting/pom.xml +++ b/core-java-modules/core-java-arrays-sorting/pom.xml @@ -31,12 +31,12 @@ org.openjdk.jmh jmh-core - ${jmh.version} + ${jmh-core.version} org.openjdk.jmh jmh-generator-annprocess - ${jmh.version} + ${jmh-generator.version} @@ -77,7 +77,6 @@ 3.2.0 28.2-jre - 1.19 3.10.0 \ No newline at end of file diff --git a/core-java-modules/core-java-char/pom.xml b/core-java-modules/core-java-char/pom.xml index 3691079482..078a829e00 100644 --- a/core-java-modules/core-java-char/pom.xml +++ b/core-java-modules/core-java-char/pom.xml @@ -25,17 +25,16 @@ org.openjdk.jmh jmh-core - ${openjdk.jmh.version} + ${jmh-core.version} org.openjdk.jmh jmh-generator-annprocess - ${openjdk.jmh.version} + ${jmh-generator.version} - 1.19 3.11.1 diff --git a/core-java-modules/core-java-collections-3/pom.xml b/core-java-modules/core-java-collections-3/pom.xml index 602fcf60f4..aa04d1cb24 100644 --- a/core-java-modules/core-java-collections-3/pom.xml +++ b/core-java-modules/core-java-collections-3/pom.xml @@ -24,7 +24,7 @@ org.openjdk.jmh jmh-core - ${openjdk.jmh.version} + ${jmh-core.version} org.assertj @@ -40,7 +40,6 @@ - 1.19 3.11.1 0.10 diff --git a/core-java-modules/core-java-collections-list-3/pom.xml b/core-java-modules/core-java-collections-list-3/pom.xml index e1cf645c8a..d1d199ec3f 100644 --- a/core-java-modules/core-java-collections-list-3/pom.xml +++ b/core-java-modules/core-java-collections-list-3/pom.xml @@ -58,7 +58,7 @@ org.openjdk.jmh jmh-generator-annprocess - ${jmh-core.version} + ${jmh-generator.version} diff --git a/core-java-modules/core-java-collections/pom.xml b/core-java-modules/core-java-collections/pom.xml index e1219c4713..fe9cf57bfb 100644 --- a/core-java-modules/core-java-collections/pom.xml +++ b/core-java-modules/core-java-collections/pom.xml @@ -25,17 +25,16 @@ org.openjdk.jmh jmh-core - ${openjdk.jmh.version} + ${jmh-core.version} org.openjdk.jmh jmh-generator-annprocess - ${openjdk.jmh.version} + ${jmh-generator.version} - 1.19 3.11.1 diff --git a/core-java-modules/core-java-concurrency-advanced-2/pom.xml b/core-java-modules/core-java-concurrency-advanced-2/pom.xml index 2f374bffac..98f159a85f 100644 --- a/core-java-modules/core-java-concurrency-advanced-2/pom.xml +++ b/core-java-modules/core-java-concurrency-advanced-2/pom.xml @@ -29,7 +29,7 @@ org.openjdk.jmh jmh-generator-annprocess - ${jmh-generator-annprocess.version} + ${jmh-generator.version} @@ -51,8 +51,6 @@ - 1.19 - 1.19 3.6.1 diff --git a/core-java-modules/core-java-concurrency-collections-2/pom.xml b/core-java-modules/core-java-concurrency-collections-2/pom.xml index f9ee41f6d5..19d43aa7dd 100644 --- a/core-java-modules/core-java-concurrency-collections-2/pom.xml +++ b/core-java-modules/core-java-concurrency-collections-2/pom.xml @@ -23,12 +23,12 @@ org.openjdk.jmh jmh-core - ${jmh.version} + ${jmh-core.version} org.openjdk.jmh jmh-generator-annprocess - ${jmh.version} + ${jmh-generator.version} org.assertj @@ -39,7 +39,6 @@ - 1.21 28.2-jre 3.6.1 diff --git a/core-java-modules/core-java-lang-2/pom.xml b/core-java-modules/core-java-lang-2/pom.xml index d395e8efb1..9da76fa168 100644 --- a/core-java-modules/core-java-lang-2/pom.xml +++ b/core-java-modules/core-java-lang-2/pom.xml @@ -65,8 +65,6 @@ - 1.19 - 1.19 3.12.2 1.9.4 29.0-jre diff --git a/core-java-modules/core-java-lang-4/pom.xml b/core-java-modules/core-java-lang-4/pom.xml index 3e92e9f9c7..f00a9318f7 100644 --- a/core-java-modules/core-java-lang-4/pom.xml +++ b/core-java-modules/core-java-lang-4/pom.xml @@ -20,12 +20,12 @@ org.openjdk.jmh jmh-core - ${jmh.version} + ${jmh-core.version} org.openjdk.jmh jmh-generator-annprocess - ${jmh.version} + ${jmh-generator.version} test @@ -39,9 +39,5 @@ - - - 1.28 - \ No newline at end of file diff --git a/core-java-modules/core-java-lang-math-2/pom.xml b/core-java-modules/core-java-lang-math-2/pom.xml index e2cced4fbf..42704c784a 100644 --- a/core-java-modules/core-java-lang-math-2/pom.xml +++ b/core-java-modules/core-java-lang-math-2/pom.xml @@ -58,7 +58,7 @@ org.openjdk.jmh jmh-generator-annprocess - ${jmh.version} + ${jmh-generator.version} @@ -83,7 +83,6 @@ 1.0.0-beta4 1.2.0 0.6.0 - 1.19 \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-types/README.md b/core-java-modules/core-java-lang-oop-types/README.md index 6c649877b3..1ac5a5c804 100644 --- a/core-java-modules/core-java-lang-oop-types/README.md +++ b/core-java-modules/core-java-lang-oop-types/README.md @@ -13,3 +13,4 @@ This module contains articles about types in Java - [A Guide to Java Enums](https://www.baeldung.com/a-guide-to-java-enums) - [Determine if an Object is of Primitive Type](https://www.baeldung.com/java-object-primitive-type) - [Extending Enums in Java](https://www.baeldung.com/java-extending-enums) +- [Java Class File Naming Conventions](https://www.baeldung.com/java-class-file-naming) diff --git a/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/classfile/Outer.java b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/classfile/Outer.java index b140f7085b..489b85d12d 100644 --- a/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/classfile/Outer.java +++ b/core-java-modules/core-java-lang-oop-types/src/main/java/com/baeldung/classfile/Outer.java @@ -47,6 +47,7 @@ public class Outer { // Anonymous Inner class extending a class public String greet() { Outer anonymous = new Outer() { + @Override public String greet() { return "Running Anonymous Class..."; } @@ -58,6 +59,7 @@ public class Outer { public String greet(String name) { HelloWorld helloWorld = new HelloWorld() { + @Override public String greet(String name) { return "Welcome to " + name; } @@ -68,8 +70,9 @@ public class Outer { // Anonymous inner class implementing nested interface public String greetSomeone(String name) { - + HelloSomeone helloSomeOne = new HelloSomeone() { + @Override public String greet(String name) { return "Hello " + name; } @@ -94,7 +97,8 @@ interface HelloWorld { public String greet(String name); // Nested class within an interface - class InnerClass { + class InnerClass implements HelloWorld { + @Override public String greet(String name) { return "Inner class within an interface"; } diff --git a/core-java-modules/core-java-networking-2/README.md b/core-java-modules/core-java-networking-2/README.md index 9def4c8eb6..fa49c35bf8 100644 --- a/core-java-modules/core-java-networking-2/README.md +++ b/core-java-modules/core-java-networking-2/README.md @@ -14,5 +14,4 @@ This module contains articles about networking in Java - [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception) - [Getting MAC addresses in Java](https://www.baeldung.com/java-mac-address) - [Sending Emails with Attachments in Java](https://www.baeldung.com/java-send-emails-attachments) -- [Finding a Free Port in Java](https://www.baeldung.com/java-free-port) - [[<-- Prev]](/core-java-modules/core-java-networking) diff --git a/core-java-modules/core-java-networking-3/README.md b/core-java-modules/core-java-networking-3/README.md index a81e85751d..09470fe88c 100644 --- a/core-java-modules/core-java-networking-3/README.md +++ b/core-java-modules/core-java-networking-3/README.md @@ -4,5 +4,5 @@ This module contains articles about networking in Java ### Relevant Articles -- TODO: add link once live +- [Finding a Free Port in Java](https://www.baeldung.com/java-free-port) - [[<-- Prev]](/core-java-modules/core-java-networking-2) diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml index 575ccb0759..a6127f5fdd 100644 --- a/core-java-modules/core-java-optional/pom.xml +++ b/core-java-modules/core-java-optional/pom.xml @@ -67,8 +67,6 @@ 5.4.0.Final - 1.19 - 1.19 27.1-jre 3.10.0 3.1.1 diff --git a/core-java-modules/core-java-security-2/src/test/java/com/baeldung/rsa/RsaUnitTest.java b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/rsa/RsaUnitTest.java new file mode 100644 index 0000000000..ac93f71125 --- /dev/null +++ b/core-java-modules/core-java-security-2/src/test/java/com/baeldung/rsa/RsaUnitTest.java @@ -0,0 +1,92 @@ +package com.baeldung.cipher; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import javax.crypto.Cipher; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.PublicKey; + +public class RsaUnitTest { + + @Test + public void givenRsaKeyPair_whenEncryptAndDecryptString_thenCompareResults() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair pair = generator.generateKeyPair(); + PrivateKey privateKey = pair.getPrivate(); + PublicKey publicKey = pair.getPublic(); + + String secretMessage = "Baeldung secret message"; + Cipher encryptCipher = Cipher.getInstance("RSA"); + encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey); + byte[] secretMessageBytes = secretMessage.getBytes(StandardCharsets.UTF_8); + byte[] encryptedMessageBytes = encryptCipher.doFinal(secretMessageBytes); + + Cipher decryptCipher = Cipher.getInstance("RSA"); + decryptCipher.init(Cipher.DECRYPT_MODE, privateKey); + byte[] decryptedMessageBytes = decryptCipher.doFinal(encryptedMessageBytes); + String decryptedMessage = new String(decryptedMessageBytes, StandardCharsets.UTF_8); + + Assertions.assertEquals(secretMessage, decryptedMessage); + } + + @Test + public void givenRsaKeyPair_whenEncryptAndDecryptFile_thenCompareResults() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair pair = generator.generateKeyPair(); + PrivateKey privateKey = pair.getPrivate(); + PublicKey publicKey = pair.getPublic(); + + String originalContent = "some secret message"; + Path tempFile = Files.createTempFile("temp", "txt"); + writeString(tempFile, originalContent); + + byte[] fileBytes = Files.readAllBytes(tempFile); + Cipher encryptCipher = Cipher.getInstance("RSA"); + encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey); + byte[] encryptedFileBytes = encryptCipher.doFinal(fileBytes); + try (FileOutputStream stream = new FileOutputStream(tempFile.toFile())) { + stream.write(encryptedFileBytes); + } + + encryptedFileBytes = Files.readAllBytes(tempFile); + Cipher decryptCipher = Cipher.getInstance("RSA"); + decryptCipher.init(Cipher.DECRYPT_MODE, privateKey); + byte[] decryptedFileBytes = decryptCipher.doFinal(encryptedFileBytes); + try (FileOutputStream stream = new FileOutputStream(tempFile.toFile())) { + stream.write(decryptedFileBytes); + } + + String fileContent = readString(tempFile); + + Assertions.assertEquals(originalContent, fileContent); + } + + private void writeString(Path path, String content) throws Exception { + try (BufferedWriter writer = Files.newBufferedWriter(path)) { + writer.write(content); + } + } + + private String readString(Path path) throws Exception { + StringBuilder resultStringBuilder = new StringBuilder(); + try (BufferedReader br = new BufferedReader(new FileReader(path.toFile()))) { + String line; + while ((line = br.readLine()) != null) { + resultStringBuilder.append(line); + } + } + return resultStringBuilder.toString(); + } +} diff --git a/core-java-modules/core-java-streams-2/pom.xml b/core-java-modules/core-java-streams-2/pom.xml index 2a0a4348b0..323e01261f 100644 --- a/core-java-modules/core-java-streams-2/pom.xml +++ b/core-java-modules/core-java-streams-2/pom.xml @@ -47,7 +47,6 @@ - UTF-8 1.9 1.9 3.11.1 diff --git a/core-java-modules/core-java-streams-3/README.md b/core-java-modules/core-java-streams-3/README.md index 9adde005e6..f81dca485b 100644 --- a/core-java-modules/core-java-streams-3/README.md +++ b/core-java-modules/core-java-streams-3/README.md @@ -10,4 +10,5 @@ This module contains articles about the Stream API in Java. - [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams) - [Add BigDecimals using the Stream API](https://www.baeldung.com/java-stream-add-bigdecimals) - [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close) +- [Returning Stream vs. Collection](https://www.baeldung.com/java-return-stream-collection) - More articles: [[<-- prev>]](/../core-java-streams-2) diff --git a/core-java-modules/core-java-streams-3/pom.xml b/core-java-modules/core-java-streams-3/pom.xml index cbb7366a7d..6597c999d8 100644 --- a/core-java-modules/core-java-streams-3/pom.xml +++ b/core-java-modules/core-java-streams-3/pom.xml @@ -49,8 +49,6 @@ 3.6.1 - - 2.22.1 diff --git a/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/streamvscollection/StreamVsCollectionExample.java b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/streamvscollection/StreamVsCollectionExample.java new file mode 100644 index 0000000000..379d231bed --- /dev/null +++ b/core-java-modules/core-java-streams-3/src/main/java/com/baeldung/streams/streamvscollection/StreamVsCollectionExample.java @@ -0,0 +1,95 @@ +package com.baeldung.streams.streamvscollection; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class StreamVsCollectionExample { + + static ArrayList userNameSource = new ArrayList<>(); + + static { + userNameSource.add("john"); + userNameSource.add("smith"); + userNameSource.add("tom"); + userNameSource.add("rob"); + userNameSource.add("charlie"); + userNameSource.add("alfred"); + } + + public static Stream userNames() { + return userNameSource.stream(); + } + + public static List userNameList() { + return userNames().collect(Collectors.toList()); + } + + public static Set userNameSet() { + return userNames().collect(Collectors.toSet()); + } + + public static Map userNameMap() { + return userNames().collect(Collectors.toMap(u1 -> u1.toString(), u1 -> u1.toString())); + } + + public static Stream filterUserNames() { + return userNames().filter(i -> i.length() >= 4); + } + + public static Stream sortUserNames() { + return userNames().sorted(); + } + + public static Stream limitUserNames() { + return userNames().limit(3); + } + + public static Stream sortFilterLimitUserNames() { + return filterUserNames().sorted().limit(3); + } + + public static void printStream(Stream stream) { + stream.forEach(System.out::println); + } + + public static void modifyList() { + userNameSource.remove(2); + } + + public static Map modifyMap() { + Map userNameMap = userNameMap(); + userNameMap.put("bob", "bob"); + userNameMap.remove("alfred"); + + return userNameMap; + } + + public static void tryStreamTraversal() { + Stream userNameStream = userNames(); + userNameStream.forEach(System.out::println); + + try { + userNameStream.forEach(System.out::println); + } catch(IllegalStateException e) { + System.out.println("stream has already been operated upon or closed"); + } + } + + public static void main(String[] args) { + System.out.println(userNameMap()); + System.out.println(modifyMap()); + tryStreamTraversal(); + + Set set = userNames().collect(Collectors.toCollection(TreeSet::new)); + set.forEach(val -> System.out.println(val)); + + } + + +} diff --git a/core-java-modules/core-java-string-algorithms-2/pom.xml b/core-java-modules/core-java-string-algorithms-2/pom.xml index 2a84cebb4c..ae2685e742 100644 --- a/core-java-modules/core-java-string-algorithms-2/pom.xml +++ b/core-java-modules/core-java-string-algorithms-2/pom.xml @@ -34,7 +34,7 @@ org.openjdk.jmh jmh-generator-annprocess - ${jmh-core.version} + ${jmh-generator.version} org.assertj diff --git a/core-java-modules/core-java-string-algorithms/pom.xml b/core-java-modules/core-java-string-algorithms/pom.xml index 6ba9ae7bb3..abafd10f2b 100644 --- a/core-java-modules/core-java-string-algorithms/pom.xml +++ b/core-java-modules/core-java-string-algorithms/pom.xml @@ -39,7 +39,7 @@ org.openjdk.jmh jmh-generator-annprocess - ${jmh-core.version} + ${jmh-generator.version} com.vdurmont diff --git a/core-java-modules/multimodulemavenproject/pom.xml b/core-java-modules/multimodulemavenproject/pom.xml index dcf9f7311e..25f268f8b3 100644 --- a/core-java-modules/multimodulemavenproject/pom.xml +++ b/core-java-modules/multimodulemavenproject/pom.xml @@ -59,7 +59,6 @@ 3.8.0 1.9 1.9 - UTF-8 3.12.2 diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml index 7dc54bd907..d44ce97f14 100644 --- a/core-java-modules/pom.xml +++ b/core-java-modules/pom.xml @@ -100,6 +100,7 @@ core-java-networking core-java-networking-2 + core-java-networking-3 core-java-nio core-java-nio-2 @@ -148,18 +149,6 @@ - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - - 2.22.2 5.6.2 diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml index e0f38199ec..50bd16e2d5 100644 --- a/custom-pmd/pom.xml +++ b/custom-pmd/pom.xml @@ -45,7 +45,6 @@ - UTF-8 3.7.0 6.0.1 1.8 diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java index 7469e8ba64..42cacbd3ea 100644 --- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java +++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java @@ -148,48 +148,46 @@ public class BinaryTree { } } - public void traverseInOrderWithoutRecursion() { - Stack stack = new Stack(); + Stack stack = new Stack<>(); + Node current = root; + + while (current != null || !stack.isEmpty()) { + while (current != null) { + stack.push(current); + current = current.left; + } + + Node top = stack.pop(); + visit(top.value); + current = top.right; + } + } + + public void traversePreOrderWithoutRecursion() { + Stack stack = new Stack<>(); Node current = root; stack.push(root); - while(! stack.isEmpty()) { - while(current.left != null) { - current = current.left; - stack.push(current); - } + + while (current != null && !stack.isEmpty()) { current = stack.pop(); visit(current.value); - if(current.right != null) { - current = current.right; - stack.push(current); - } + + if (current.right != null) + stack.push(current.right); + + if (current.left != null) + stack.push(current.left); } } - public void traversePreOrderWithoutRecursion() { - Stack stack = new Stack(); - Node current = root; - stack.push(root); - while(! stack.isEmpty()) { - current = stack.pop(); - visit(current.value); - - if(current.right != null) - stack.push(current.right); - - if(current.left != null) - stack.push(current.left); - } - } - public void traversePostOrderWithoutRecursion() { - Stack stack = new Stack(); + Stack stack = new Stack<>(); Node prev = root; Node current = root; stack.push(root); - while (!stack.isEmpty()) { + while (current != null && !stack.isEmpty()) { current = stack.peek(); boolean hasChild = (current.left != null || current.right != null); boolean isPrevLastChild = (prev == current.right || (prev == current.left && current.right == null)); diff --git a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java index f99cb52ed7..e89557f21b 100644 --- a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java +++ b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java @@ -13,7 +13,7 @@ public class BinaryTreeUnitTest { BinaryTree bt = createBinaryTree(); - assertTrue(!bt.isEmpty()); + assertFalse(bt.isEmpty()); } @Test @@ -72,6 +72,7 @@ public class BinaryTreeUnitTest { @Test public void it_deletes_the_root() { + int value = 12; BinaryTree bt = new BinaryTree(); bt.add(value); @@ -91,6 +92,14 @@ public class BinaryTreeUnitTest { bt.traverseInOrderWithoutRecursion(); } + @Test + public void givenAnEmptyBinaryTree_WhenTraversingInOrderWithoutRecursion_ThenNoException() { + + BinaryTree empty = new BinaryTree(); + + empty.traverseInOrderWithoutRecursion(); + } + @Test public void givenABinaryTree_WhenTraversingPreOrder_ThenPrintValues() { @@ -101,6 +110,14 @@ public class BinaryTreeUnitTest { bt.traversePreOrderWithoutRecursion(); } + @Test + public void givenAnEmptyBinaryTree_WhenTraversingPreOrderWithoutRecursion_ThenNoException() { + + BinaryTree empty = new BinaryTree(); + + empty.traversePreOrderWithoutRecursion(); + } + @Test public void givenABinaryTree_WhenTraversingPostOrder_ThenPrintValues() { @@ -111,6 +128,14 @@ public class BinaryTreeUnitTest { bt.traversePostOrderWithoutRecursion(); } + @Test + public void givenAnEmptyBinaryTree_WhenTraversingPostOrderWithoutRecursion_ThenNoException() { + + BinaryTree empty = new BinaryTree(); + + empty.traversePostOrderWithoutRecursion(); + } + @Test public void givenABinaryTree_WhenTraversingLevelOrder_ThenPrintValues() { diff --git a/ddd-modules/mainapp/pom.xml b/ddd-modules/mainapp/pom.xml index 59d2ad7d3a..6b913df979 100644 --- a/ddd-modules/mainapp/pom.xml +++ b/ddd-modules/mainapp/pom.xml @@ -29,7 +29,6 @@ org.apache.maven.plugins maven-surefire-plugin - 2.16 true diff --git a/ddd-modules/pom.xml b/ddd-modules/pom.xml index 6ab1829198..376dad89e5 100644 --- a/ddd-modules/pom.xml +++ b/ddd-modules/pom.xml @@ -66,7 +66,6 @@ org.apache.maven.plugins maven-surefire-plugin - ${maven-surefire-plugin.version} 0 @@ -75,13 +74,10 @@ - UTF-8 - 9 9 3.8.1 - 2.22.2 1.0 diff --git a/ddd/pom.xml b/ddd/pom.xml index 7d03208802..41fccc7d5f 100644 --- a/ddd/pom.xml +++ b/ddd/pom.xml @@ -99,15 +99,6 @@ - - - - org.apache.maven.plugins - maven-surefire-plugin - - - - 1.0.1 diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml index 6fdcae4f75..1ff5081343 100644 --- a/google-web-toolkit/pom.xml +++ b/google-web-toolkit/pom.xml @@ -97,7 +97,6 @@ maven-surefire-plugin - ${surefire.plugin.version} true @@ -113,12 +112,8 @@ 1.8 1.8 - - UTF-8 - UTF-8 2.8.2 1.0-rc-8 - 2.17 diff --git a/guava-modules/guava-collections-list/pom.xml b/guava-modules/guava-collections-list/pom.xml index cc52a5d48b..78a4aeb8ea 100644 --- a/guava-modules/guava-collections-list/pom.xml +++ b/guava-modules/guava-collections-list/pom.xml @@ -66,14 +66,6 @@ true - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - diff --git a/guava-modules/guava-collections-map/pom.xml b/guava-modules/guava-collections-map/pom.xml index 82d634265b..f3f829f25f 100644 --- a/guava-modules/guava-collections-map/pom.xml +++ b/guava-modules/guava-collections-map/pom.xml @@ -38,14 +38,6 @@ true - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - diff --git a/guava-modules/guava-collections-set/pom.xml b/guava-modules/guava-collections-set/pom.xml index 8f58148e41..0e53527aef 100644 --- a/guava-modules/guava-collections-set/pom.xml +++ b/guava-modules/guava-collections-set/pom.xml @@ -37,14 +37,6 @@ guava-collections-set - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - diff --git a/guava-modules/guava-collections/pom.xml b/guava-modules/guava-collections/pom.xml index 53c55dc655..90ed99bab7 100644 --- a/guava-modules/guava-collections/pom.xml +++ b/guava-modules/guava-collections/pom.xml @@ -71,14 +71,6 @@ true - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - diff --git a/guava-modules/guava-io/pom.xml b/guava-modules/guava-io/pom.xml index 6b3280755c..b77bad575d 100644 --- a/guava-modules/guava-io/pom.xml +++ b/guava-modules/guava-io/pom.xml @@ -40,14 +40,6 @@ true - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - \ No newline at end of file diff --git a/guava-modules/guava-utilities/pom.xml b/guava-modules/guava-utilities/pom.xml index 0496f5b2e8..fd9523c224 100644 --- a/guava-modules/guava-utilities/pom.xml +++ b/guava-modules/guava-utilities/pom.xml @@ -52,14 +52,6 @@ true - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - diff --git a/guava-modules/pom.xml b/guava-modules/pom.xml index b625f9fd0f..4b84f616f3 100644 --- a/guava-modules/pom.xml +++ b/guava-modules/pom.xml @@ -46,17 +46,8 @@ - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - - - + 2.22.2 5.6.2 29.0-jre diff --git a/jackson-modules/pom.xml b/jackson-modules/pom.xml index 70b10e9554..819f11c110 100644 --- a/jackson-modules/pom.xml +++ b/jackson-modules/pom.xml @@ -50,16 +50,6 @@ - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - - - 5.6.2 diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml index 761dca6afa..8dfd949166 100644 --- a/jackson-simple/pom.xml +++ b/jackson-simple/pom.xml @@ -51,14 +51,6 @@ true - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - diff --git a/java-rmi/src/test/java/com/baeldung/rmi/JavaRMIIntegrationTest.java b/java-rmi/src/test/java/com/baeldung/rmi/JavaRMIIntegrationTest.java index 5e4ecb3e76..604899de03 100644 --- a/java-rmi/src/test/java/com/baeldung/rmi/JavaRMIIntegrationTest.java +++ b/java-rmi/src/test/java/com/baeldung/rmi/JavaRMIIntegrationTest.java @@ -1,42 +1,42 @@ package com.baeldung.rmi; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import org.junit.Before; +import org.junit.Test; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; -import org.junit.BeforeClass; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; public class JavaRMIIntegrationTest { - - @BeforeClass - public static void whenRunServer_thenServerStarts() { - - try { - MessengerServiceImpl server = new MessengerServiceImpl(); - server.createStubAndBind(); - } catch (RemoteException e) { - fail("Exception Occurred: " + e); - } - } - - @Test - public void whenClientSendsMessageToServer_thenServerSendsResponseMessage() { - - try { - Registry registry = LocateRegistry.getRegistry(); - MessengerService server = (MessengerService) registry.lookup("MessengerService"); - String responseMessage = server.sendMessage("Client Message"); - - String expectedMessage = "Server Message"; - assertEquals(responseMessage, expectedMessage); - } catch (RemoteException | NotBoundException e) { - fail("Exception Occurred: " + e); - }; - } - + + private MessengerServiceImpl messengerService; + + @Before + public void init() { + try { + messengerService = new MessengerServiceImpl(); + messengerService.createStubAndBind(); + } catch (RemoteException e) { + fail("Exception Occurred: " + e); + } + } + + @Test + public void whenClientSendsMessageToServer_thenServerSendsResponseMessage() { + try { + Registry registry = LocateRegistry.getRegistry(); + MessengerService server = (MessengerService) registry.lookup("MessengerService"); + String responseMessage = server.sendMessage("Client Message"); + + String expectedMessage = "Server Message"; + assertEquals(responseMessage, expectedMessage); + } catch (RemoteException | NotBoundException e) { + fail("Exception Occurred: " + e); + } + } + } \ No newline at end of file diff --git a/jee-7/pom.xml b/jee-7/pom.xml index b0e10c1580..48814e6d2f 100644 --- a/jee-7/pom.xml +++ b/jee-7/pom.xml @@ -523,7 +523,6 @@ 2.25 1.0.0.Final 4.2.3.RELEASE - 2.21.0 1.1.2 2.2.14 4.5 diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointIntegrationTest.java similarity index 96% rename from jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java rename to jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointIntegrationTest.java index c607efeb24..8190ae5afb 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointIntegrationTest.java @@ -12,7 +12,7 @@ import javax.batch.runtime.StepExecution; import org.junit.jupiter.api.Test; -class CustomCheckPointUnitTest { +class CustomCheckPointIntegrationTest { @Test public void givenChunk_whenCustomCheckPoint_thenCommitCountIsThree() throws Exception { JobOperator jobOperator = BatchRuntime.getJobOperator(); diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceIntegrationTest.java similarity index 99% rename from jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java rename to jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceIntegrationTest.java index 4b27e5f5ec..7dda13a752 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceIntegrationTest.java @@ -16,7 +16,7 @@ import javax.batch.runtime.StepExecution; import org.junit.jupiter.api.Test; -class JobSequenceUnitTest { +class JobSequenceIntegrationTest { @Test public void givenTwoSteps_thenBatch_CompleteWithSuccess() throws Exception { JobOperator jobOperator = BatchRuntime.getJobOperator(); diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetIntegrationTest.java similarity index 98% rename from jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java rename to jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetIntegrationTest.java index 788b75eb3e..dc91f747d3 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetIntegrationTest.java @@ -11,7 +11,7 @@ import javax.batch.runtime.JobExecution; import org.junit.jupiter.api.Test; -class SimpleBatchLetUnitTest { +class SimpleBatchLetIntegrationTest { @Test public void givenBatchLet_thenBatch_CompleteWithSuccess() throws Exception { JobOperator jobOperator = BatchRuntime.getJobOperator(); diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkIntegrationTest.java similarity index 99% rename from jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java rename to jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkIntegrationTest.java index 9010c365a2..a7884dbb32 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkIntegrationTest.java @@ -16,7 +16,7 @@ import javax.batch.runtime.StepExecution; import org.junit.jupiter.api.Test; -class SimpleChunkUnitTest { +class SimpleChunkIntegrationTest { @Test public void givenChunk_thenBatch_CompletesWithSucess() throws Exception { JobOperator jobOperator = BatchRuntime.getJobOperator(); diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkIntegrationTest.java similarity index 97% rename from jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java rename to jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkIntegrationTest.java index bc410aec8d..8c3beeb2f3 100644 --- a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java +++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkIntegrationTest.java @@ -13,7 +13,7 @@ import javax.batch.runtime.StepExecution; import org.junit.jupiter.api.Test; -class SimpleErrorChunkUnitTest { +class SimpleErrorChunkIntegrationTest { @Test public void givenChunkError_thenBatch_CompletesWithFailed() throws Exception { diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-5/bookstore-monolith/pom.xml index dbc46bbb97..5da3bde449 100644 --- a/jhipster-5/bookstore-monolith/pom.xml +++ b/jhipster-5/bookstore-monolith/pom.xml @@ -1099,8 +1099,6 @@ 2.12.6 v10.15.0 6.4.1 - UTF-8 - UTF-8 ${project.build.directory}/test-results yyyyMMddHHmmss ${java.version} diff --git a/jhipster/jhipster-uaa/gateway/pom.xml b/jhipster/jhipster-uaa/gateway/pom.xml index b417bd7b57..21a04a9692 100644 --- a/jhipster/jhipster-uaa/gateway/pom.xml +++ b/jhipster/jhipster-uaa/gateway/pom.xml @@ -1020,8 +1020,6 @@ 2.12.6 v8.12.0 6.4.1 - UTF-8 - UTF-8 ${project.build.directory}/test-results yyyyMMddHHmmss ${java.version} diff --git a/jhipster/jhipster-uaa/quotes/pom.xml b/jhipster/jhipster-uaa/quotes/pom.xml index f088ad2fd1..12bbf66d37 100644 --- a/jhipster/jhipster-uaa/quotes/pom.xml +++ b/jhipster/jhipster-uaa/quotes/pom.xml @@ -840,8 +840,6 @@ 2.12.6 v8.12.0 6.4.1 - UTF-8 - UTF-8 ${project.build.directory}/test-results yyyyMMddHHmmss ${java.version} diff --git a/jhipster/jhipster-uaa/uaa/pom.xml b/jhipster/jhipster-uaa/uaa/pom.xml index f9c1f226bb..d0d81aa0b3 100644 --- a/jhipster/jhipster-uaa/uaa/pom.xml +++ b/jhipster/jhipster-uaa/uaa/pom.xml @@ -842,8 +842,6 @@ 2.12.6 v8.12.0 6.4.1 - UTF-8 - UTF-8 ${project.build.directory}/test-results yyyyMMddHHmmss ${java.version} diff --git a/jmh/pom.xml b/jmh/pom.xml index 16a5bc54a4..ecee66f410 100644 --- a/jmh/pom.xml +++ b/jmh/pom.xml @@ -19,12 +19,12 @@ org.openjdk.jmh jmh-core - ${openjdk.jmh.version} + ${jmh-core.version} org.openjdk.jmh jmh-generator-annprocess - ${openjdk.jmh.version} + ${jmh-generator.version} org.openjdk.jol @@ -76,7 +76,6 @@ - 1.19 3.0.2 0.10 3.2.0 diff --git a/kubernetes/k8s-intro/README.md b/kubernetes/k8s-intro/README.md index 37ca5f3686..0055e8a27c 100644 --- a/kubernetes/k8s-intro/README.md +++ b/kubernetes/k8s-intro/README.md @@ -10,4 +10,8 @@ An easy way to check that everything is working as expected is issuing any *kube ```shell $ kubectl get nodes ``` -If you get a valid response, then you're good to go. \ No newline at end of file +If you get a valid response, then you're good to go. + +### Relevant Articles: + +- [Paging and Async Calls with the Kubernetes API](https://www.baeldung.com/java-kubernetes-paging-async) diff --git a/libraries-5/pom.xml b/libraries-5/pom.xml index 63347dd60d..c0de1af822 100644 --- a/libraries-5/pom.xml +++ b/libraries-5/pom.xml @@ -55,12 +55,12 @@ net.bytebuddy byte-buddy - ${bytebuddy.version} + ${byte-buddy.version} net.bytebuddy byte-buddy-agent - ${bytebuddy.version} + ${byte-buddy.version} @@ -115,7 +115,7 @@ org.openjdk.jmh jmh-core - ${jmh.version} + ${jmh-core.version} @@ -127,14 +127,12 @@ 2.11 2.5.11 0.6.5 - 1.7.1 3.0.14 2.5.5 3.0.2 4.5.1 1.0 2.1.2 - 1.19 \ No newline at end of file diff --git a/libraries-primitive/pom.xml b/libraries-primitive/pom.xml index 1370468e76..a3bf5e0d9d 100644 --- a/libraries-primitive/pom.xml +++ b/libraries-primitive/pom.xml @@ -26,13 +26,13 @@ org.openjdk.jmh jmh-core - ${jmh.version} + ${jmh-core.version} test org.openjdk.jmh jmh-generator-annprocess - ${jmh.version} + ${jmh-generator.version} test @@ -46,10 +46,11 @@ 8.2.2 4.12 - 1.19 10.0.0 1.8 1.8 + 1.28 + 1.28 \ No newline at end of file diff --git a/libraries/pom.xml b/libraries/pom.xml index fee66f928d..5924ed009a 100644 --- a/libraries/pom.xml +++ b/libraries/pom.xml @@ -202,7 +202,7 @@ org.openjdk.jmh jmh-core - ${jmh.version} + ${jmh-core.version} junit @@ -395,7 +395,6 @@ 3.0.3 2.3.0 0.9.12 - 1.19 3.0.2 3.6 2.6 diff --git a/logging-modules/log-mdc/pom.xml b/logging-modules/log-mdc/pom.xml index 5e2155fde9..a7cfd3faa8 100644 --- a/logging-modules/log-mdc/pom.xml +++ b/logging-modules/log-mdc/pom.xml @@ -95,14 +95,6 @@ - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - diff --git a/logging-modules/pom.xml b/logging-modules/pom.xml index b5354c7c23..e396d477dc 100644 --- a/logging-modules/pom.xml +++ b/logging-modules/pom.xml @@ -14,23 +14,13 @@ + flogger log4j log4j2 logback log-mdc - flogger - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - - - 5.6.2 diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml index c9a2b67a6c..a476eacc64 100644 --- a/maven-modules/pom.xml +++ b/maven-modules/pom.xml @@ -20,14 +20,15 @@ maven-integration-test maven-multi-source maven-plugins - maven-unused-dependencies - maven-war-plugin maven-profiles maven-properties - versions-maven-plugin - version-collision + + maven-unused-dependencies + maven-war-plugin optional-dependencies + version-collision version-overriding-plugins + versions-maven-plugin diff --git a/parent-java/pom.xml b/parent-java/pom.xml index 9170f45bbe..ce79b34f57 100644 --- a/parent-java/pom.xml +++ b/parent-java/pom.xml @@ -32,18 +32,17 @@ org.openjdk.jmh jmh-core - ${jmh.version} + ${jmh-core.version} org.openjdk.jmh jmh-generator-annprocess - ${jmh.version} + ${jmh-generator.version} 29.0-jre - 1.19 2.3.7 2.2 diff --git a/patterns/clean-architecture/pom.xml b/patterns/clean-architecture/pom.xml index 6e7de78751..b9968095f8 100644 --- a/patterns/clean-architecture/pom.xml +++ b/patterns/clean-architecture/pom.xml @@ -15,10 +15,6 @@ ../../parent-boot-2 - - 1.8 - - com.h2database diff --git a/patterns/design-patterns-behavioral/src/main/java/com/baeldung/nulls/UsingOptional.java b/patterns/design-patterns-behavioral/src/main/java/com/baeldung/nulls/UsingOptional.java index 099864589c..03bed5fedf 100644 --- a/patterns/design-patterns-behavioral/src/main/java/com/baeldung/nulls/UsingOptional.java +++ b/patterns/design-patterns-behavioral/src/main/java/com/baeldung/nulls/UsingOptional.java @@ -38,8 +38,8 @@ public class UsingOptional { .flatMap(list -> list.stream().findFirst()); } - private Optional getOptionalList() { - return Optional.ofNullable(getList()); + private Optional> getOptionalList() { + return Optional.of(getList()); } private String doSomething(boolean processed) { diff --git a/patterns/design-patterns-behavioral/src/test/java/com/baeldung/nulls/UsingOptionalUnitTest.java b/patterns/design-patterns-behavioral/src/test/java/com/baeldung/nulls/UsingOptionalUnitTest.java index 73797d48c8..576d2bacf3 100644 --- a/patterns/design-patterns-behavioral/src/test/java/com/baeldung/nulls/UsingOptionalUnitTest.java +++ b/patterns/design-patterns-behavioral/src/test/java/com/baeldung/nulls/UsingOptionalUnitTest.java @@ -19,22 +19,22 @@ class UsingOptionalUnitTest { } @Test - public void whenArgIsFalse_thenReturnEmptyResponse() { + void whenArgIsFalse_thenReturnEmptyResponse() { Optional result = dataObject.process(false); assertFalse(result.isPresent()); } @Test - public void whenArgIsTrue_thenReturnValidResponse() { + void whenArgIsTrue_thenReturnValidResponse() { Optional result = dataObject.process(true); assertTrue(result.isPresent()); } @Test - public void whenArgIsFalse_thenChainResponseAndThrowException() { - assertThrows(Exception.class, () -> dataObject.process(false).orElseThrow(() -> new Exception())); + void whenArgIsFalse_thenChainResponseAndThrowException() { + assertThrows(Exception.class, () -> dataObject.process(false).orElseThrow(Exception::new)); } @Test() @@ -51,7 +51,4 @@ class UsingOptionalUnitTest { void whenOptionalListFirst_returnsEmptyOptional() { assertFalse(dataObject.optionalListFirst().isPresent()); } - - - } \ No newline at end of file diff --git a/patterns/hexagonal-architecture/pom.xml b/patterns/hexagonal-architecture/pom.xml index 62f55c2efa..db7ee69e2e 100644 --- a/patterns/hexagonal-architecture/pom.xml +++ b/patterns/hexagonal-architecture/pom.xml @@ -15,10 +15,6 @@ ../../parent-boot-2 - - 1.8 - - org.springframework.boot diff --git a/performance-tests/pom.xml b/performance-tests/pom.xml index fb3f82df38..c203f0a923 100644 --- a/performance-tests/pom.xml +++ b/performance-tests/pom.xml @@ -42,12 +42,12 @@ org.openjdk.jmh jmh-core - ${jmh.version} + ${jmh-core.version} org.openjdk.jmh jmh-generator-annprocess - ${jmh.version} + ${jmh-generator.version} provided @@ -67,7 +67,7 @@ org.openjdk.jmh jmh-generator-annprocess - ${jmh.version} + ${jmh-generator.version} org.mapstruct @@ -147,19 +147,11 @@ maven-source-plugin ${source.plugin.version} - - maven-surefire-plugin - ${surefire.plugin.version} - - - 1.23 1.5.4 6.5.0 1.3.1.Final @@ -185,7 +177,6 @@ 3.1.0 3.9.1 3.2.1 - 2.17 diff --git a/persistence-modules/apache-bookkeeper/pom.xml b/persistence-modules/apache-bookkeeper/pom.xml index 32467b9997..3ef1f50d63 100644 --- a/persistence-modules/apache-bookkeeper/pom.xml +++ b/persistence-modules/apache-bookkeeper/pom.xml @@ -31,7 +31,7 @@ org.testcontainers testcontainers - 1.14.3 + ${testcontainers.version} test @@ -39,6 +39,7 @@ 4.10.0 + 1.14.3 diff --git a/persistence-modules/core-java-persistence-2/README.md b/persistence-modules/core-java-persistence-2/README.md index 36c33cc6e1..cebd81388d 100644 --- a/persistence-modules/core-java-persistence-2/README.md +++ b/persistence-modules/core-java-persistence-2/README.md @@ -2,3 +2,4 @@ - [Getting Database URL From JDBC Connection Object](https://www.baeldung.com/jdbc-get-url-from-connection) - [JDBC URL Format For Different Databases](https://www.baeldung.com/java-jdbc-url-format) +- [How to Check if a Database Table Exists with JDBC](https://www.baeldung.com/jdbc-check-table-exists) diff --git a/persistence-modules/core-java-persistence-2/src/main/java/com/baeldung/tableexists/DatabaseConfig.java b/persistence-modules/core-java-persistence-2/src/main/java/com/baeldung/tableexists/DatabaseConfig.java new file mode 100644 index 0000000000..4ea8a5203e --- /dev/null +++ b/persistence-modules/core-java-persistence-2/src/main/java/com/baeldung/tableexists/DatabaseConfig.java @@ -0,0 +1,21 @@ +package com.baeldung.tableexists; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +class DatabaseConfig { + static Connection connect() throws ClassNotFoundException, SQLException { + Class.forName("org.h2.Driver"); + String url = "jdbc:h2:mem:testdb"; + return DriverManager.getConnection(url, "user", "password"); + } + + static void createTables(Connection connection) throws SQLException { + connection.createStatement().executeUpdate("create table EMPLOYEE (id int primary key auto_increment, name VARCHAR(255))"); + } + + static void dropTables(Connection connection) throws SQLException { + connection.createStatement().executeUpdate("drop table EMPLOYEE"); + } +} diff --git a/persistence-modules/core-java-persistence-2/src/main/java/com/baeldung/tableexists/TableChecker.java b/persistence-modules/core-java-persistence-2/src/main/java/com/baeldung/tableexists/TableChecker.java new file mode 100644 index 0000000000..e6b2ea2fcf --- /dev/null +++ b/persistence-modules/core-java-persistence-2/src/main/java/com/baeldung/tableexists/TableChecker.java @@ -0,0 +1,35 @@ +package com.baeldung.tableexists; + +import java.sql.*; + +class TableChecker { + static void printAllTables(Connection connection, String tableName) throws SQLException { + DatabaseMetaData databaseMetaData = connection.getMetaData(); + ResultSet resultSet = databaseMetaData.getTables(null, null, tableName, new String[] {"TABLE"}); + + while (resultSet.next()) { + String name = resultSet.getString("TABLE_NAME"); + String schema = resultSet.getString("TABLE_SCHEM"); + System.out.println(name + " on schema " + schema); + } + } + + static boolean tableExists(Connection connection, String tableName) throws SQLException { + DatabaseMetaData meta = connection.getMetaData(); + ResultSet resultSet = meta.getTables(null, null, tableName, new String[] {"TABLE"}); + + return resultSet.next(); + } + + static boolean tableExistsSQL(Connection connection, String tableName) throws SQLException { + PreparedStatement preparedStatement = connection.prepareStatement("SELECT count(*) " + + "FROM information_schema.tables " + + "WHERE table_name = ?" + + "LIMIT 1;"); + preparedStatement.setString(1, tableName); + + ResultSet resultSet = preparedStatement.executeQuery(); + resultSet.next(); + return resultSet.getInt(1) != 0; + } +} diff --git a/persistence-modules/core-java-persistence-2/src/test/java/com/baeldung/tableexists/TableCheckerTest.java b/persistence-modules/core-java-persistence-2/src/test/java/com/baeldung/tableexists/TableCheckerTest.java new file mode 100644 index 0000000000..d7322332a5 --- /dev/null +++ b/persistence-modules/core-java-persistence-2/src/test/java/com/baeldung/tableexists/TableCheckerTest.java @@ -0,0 +1,70 @@ +package com.baeldung.tableexists; + +import org.junit.jupiter.api.Test; + +import java.sql.Connection; +import java.sql.SQLException; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class TableCheckerUnitTest { + + @Test + void givenCreatedTable_shouldFindTable() throws SQLException, ClassNotFoundException { + // given + Connection connection = DatabaseConfig.connect(); + DatabaseConfig.createTables(connection); + + // when + boolean tableExists = TableChecker.tableExists(connection, "EMPLOYEE"); + + // then + TableChecker.printAllTables(connection, null); + assertTrue(tableExists); + + DatabaseConfig.dropTables(connection); + } + + @Test + void givenCreatedTable_shouldFindTableWithSQL() throws SQLException, ClassNotFoundException { + // given + Connection connection = DatabaseConfig.connect(); + DatabaseConfig.createTables(connection); + + // when + boolean tableExists = TableChecker.tableExistsSQL(connection, "EMPLOYEE"); + + // then + TableChecker.printAllTables(connection, null); + assertTrue(tableExists); + + DatabaseConfig.dropTables(connection); + } + + @Test + void givenNoTable_shouldNotFindTable() throws SQLException, ClassNotFoundException { + // given + Connection connection = DatabaseConfig.connect(); + + // when + boolean tableExists = TableChecker.tableExists(connection, "EMPLOYEE"); + + // then + TableChecker.printAllTables(connection, null); + assertFalse(tableExists); + } + + @Test + void givenNoTable_shouldNotFindTableWithSQL() throws SQLException, ClassNotFoundException { + // given + Connection connection = DatabaseConfig.connect(); + + // when + boolean tableExists = TableChecker.tableExistsSQL(connection, "EMPLOYEE"); + + // then + TableChecker.printAllTables(connection, null); + assertFalse(tableExists); + } +} \ No newline at end of file diff --git a/persistence-modules/hibernate-jpa/pom.xml b/persistence-modules/hibernate-jpa/pom.xml index 07b1ee1c51..e5056c413b 100644 --- a/persistence-modules/hibernate-jpa/pom.xml +++ b/persistence-modules/hibernate-jpa/pom.xml @@ -79,7 +79,7 @@ org.openjdk.jmh jmh-generator-annprocess - ${openjdk-jmh.version} + ${jmh-generator.version} org.postgresql @@ -94,7 +94,6 @@ 42.2.11 2.2.3 3.8.0 - 1.21 2.1.7.RELEASE diff --git a/persistence-modules/hibernate-libraries/pom.xml b/persistence-modules/hibernate-libraries/pom.xml index f67309cf43..053ad05167 100644 --- a/persistence-modules/hibernate-libraries/pom.xml +++ b/persistence-modules/hibernate-libraries/pom.xml @@ -175,7 +175,6 @@ 2.0.0 1.2.3 3.0.2 - 2.22.2 3.8.1 3.8.1 8.0.19 diff --git a/persistence-modules/hibernate-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml index 4374c833c2..d44bc0f8ae 100644 --- a/persistence-modules/hibernate-queries/pom.xml +++ b/persistence-modules/hibernate-queries/pom.xml @@ -53,7 +53,7 @@ org.openjdk.jmh jmh-generator-annprocess - ${openjdk-jmh.version} + ${jmh-generator.version} @@ -61,7 +61,6 @@ 6.0.6 2.2.3 3.8.0 - 1.21 diff --git a/persistence-modules/hibernate5/pom.xml b/persistence-modules/hibernate5/pom.xml index 3feffc98fd..fe0e7680ab 100644 --- a/persistence-modules/hibernate5/pom.xml +++ b/persistence-modules/hibernate5/pom.xml @@ -59,7 +59,7 @@ org.openjdk.jmh jmh-generator-annprocess - ${openjdk-jmh.version} + ${jmh-generator.version} @@ -68,7 +68,6 @@ 6.0.6 2.2.3 3.8.0 - 1.21 diff --git a/persistence-modules/java-jpa-3/pom.xml b/persistence-modules/java-jpa-3/pom.xml index 7c02cc6c8e..f931cd90b8 100644 --- a/persistence-modules/java-jpa-3/pom.xml +++ b/persistence-modules/java-jpa-3/pom.xml @@ -30,17 +30,17 @@ mysql mysql-connector-java - 8.0.21 + ${mysql.version} com.fasterxml.jackson.core jackson-databind - 2.11.3 + ${jackson.version} com.fasterxml.jackson.datatype jackson-datatype-hibernate5 - 2.9.8 + ${jackson.version} @@ -87,6 +87,7 @@ 5.4.14.Final 2.7.4 42.2.5 + 8.0.21 2.2 3.11.1 3.5.1 diff --git a/persistence-modules/java-jpa-3/src/main/java/com/baeldung/ignorable/fields/HibernateConfig.java b/persistence-modules/java-jpa-3/src/main/java/com/baeldung/ignorable/fields/HibernateConfig.java index 9285c23dfa..d121c81c6b 100644 --- a/persistence-modules/java-jpa-3/src/main/java/com/baeldung/ignorable/fields/HibernateConfig.java +++ b/persistence-modules/java-jpa-3/src/main/java/com/baeldung/ignorable/fields/HibernateConfig.java @@ -9,6 +9,7 @@ import org.hibernate.cfg.Environment; import org.hibernate.service.ServiceRegistry; public class HibernateConfig { + private static SessionFactory sessionFactory; public static SessionFactory getSessionFactory() { @@ -16,12 +17,12 @@ public class HibernateConfig { Configuration configuration = new Configuration(); Properties settings = new Properties(); - settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver"); - settings.put(Environment.URL, "jdbc:mysql://localhost:3306/app_db?useSSL=false"); - settings.put(Environment.USER, "root"); - settings.put(Environment.PASS, "password"); - settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect"); - settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); + settings.put(Environment.DRIVER, "org.h2.Driver"); + settings.put(Environment.URL, "jdbc:h2:mem:test"); + settings.put(Environment.USER, "sa"); + settings.put(Environment.PASS, ""); + settings.put(Environment.DIALECT, "org.hibernate.dialect.H2Dialect"); + settings.put(Environment.HBM2DDL_AUTO, "create-drop"); configuration.setProperties(settings); configuration.addAnnotatedClass(User.class); diff --git a/persistence-modules/java-jpa-3/src/test/java/com/baeldung/ignorable/fields/TransientFieldUnitTest.java b/persistence-modules/java-jpa-3/src/test/java/com/baeldung/ignorable/fields/TransientFieldUnitTest.java index 114a4cca4c..6d4eba2c29 100644 --- a/persistence-modules/java-jpa-3/src/test/java/com/baeldung/ignorable/fields/TransientFieldUnitTest.java +++ b/persistence-modules/java-jpa-3/src/test/java/com/baeldung/ignorable/fields/TransientFieldUnitTest.java @@ -1,18 +1,24 @@ package com.baeldung.ignorable.fields; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -import java.io.*; -import java.util.List; -import java.util.Random; - -import org.junit.Test; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module; +import org.junit.Test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; public class TransientFieldUnitTest { @@ -34,18 +40,20 @@ public class TransientFieldUnitTest { @Test public void givenFieldWithTransientAnnotation_whenSerializingObject_thenFieldSerialized() throws IOException, ClassNotFoundException { - FileOutputStream fout = new FileOutputStream("test.obj"); - ObjectOutputStream out = new ObjectOutputStream(fout); - out.writeObject(user); - out.flush(); - out.close(); + try (FileOutputStream fout = new FileOutputStream("test.obj")) { + ObjectOutputStream out = new ObjectOutputStream(fout); + out.writeObject(user); + out.flush(); + } - FileInputStream fin = new FileInputStream("test.obj"); - ObjectInputStream in = new ObjectInputStream(fin); - User savedUser = (User) in.readObject(); - in.close(); + try (FileInputStream fin = new FileInputStream("test.obj")) { + ObjectInputStream in = new ObjectInputStream(fin); + User savedUser = (User) in.readObject(); - assertEquals(user.getCurrentDevice(), savedUser.getCurrentDevice()); + assertEquals(user.getCurrentDevice(), savedUser.getCurrentDevice()); + } + + Files.deleteIfExists(Paths.get("test.obj")); } @Test diff --git a/persistence-modules/jooq/pom.xml b/persistence-modules/jooq/pom.xml index f0c5a27a96..cdda860040 100644 --- a/persistence-modules/jooq/pom.xml +++ b/persistence-modules/jooq/pom.xml @@ -19,28 +19,34 @@ org.jooq jooq - 3.13.4 + ${jooq.version} org.jooq jooq-meta - 3.13.4 + ${jooq.version} org.jooq jooq-codegen - 3.13.4 + ${jooq.version} org.postgresql postgresql - 42.2.16 + ${postgresql.version} com.h2database h2 - 1.4.200 + ${h2.version} + + 3.13.4 + 42.2.16 + 1.4.200 + + diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml index 8789a8473b..32423a42dd 100644 --- a/persistence-modules/pom.xml +++ b/persistence-modules/pom.xml @@ -38,6 +38,7 @@ java-jdbi java-jpa java-jpa-2 + java-jpa-3 java-mongodb jnosql jooq diff --git a/persistence-modules/sirix/pom.xml b/persistence-modules/sirix/pom.xml index 67de507cca..da9695081c 100644 --- a/persistence-modules/sirix/pom.xml +++ b/persistence-modules/sirix/pom.xml @@ -47,7 +47,6 @@ - UTF-8 11 0.9.3 3.8.0 diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java similarity index 98% rename from persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java rename to persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java index 93083f6c4c..ac5661afbc 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationUnitTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java @@ -24,7 +24,7 @@ import lombok.extern.slf4j.Slf4j; @RunWith(SpringRunner.class) @SpringBootTest(classes = {SpringBootJdbiApplication.class, JdbiConfiguration.class}) @Slf4j -public class SpringBootJdbiApplicationUnitTest { +public class SpringBootJdbiApplicationIntegrationTest { @Autowired diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java similarity index 97% rename from persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java rename to persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java index be16f8f563..6956df0b13 100644 --- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerUnitTest.java +++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java @@ -20,7 +20,7 @@ import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc -public class CustomerControllerUnitTest { +public class CustomerControllerIntegrationTest { private static MediaType MEDIA_TYPE_JSON; diff --git a/persistence-modules/spring-data-cosmosdb/pom.xml b/persistence-modules/spring-data-cosmosdb/pom.xml index 19a66648b2..f3c913195f 100644 --- a/persistence-modules/spring-data-cosmosdb/pom.xml +++ b/persistence-modules/spring-data-cosmosdb/pom.xml @@ -14,9 +14,7 @@ - 1.8 2.3.0 - diff --git a/persistence-modules/spring-data-geode/pom.xml b/persistence-modules/spring-data-geode/pom.xml index 07aa65463c..ebdb37299e 100644 --- a/persistence-modules/spring-data-geode/pom.xml +++ b/persistence-modules/spring-data-geode/pom.xml @@ -61,7 +61,7 @@ com.mysema.maven maven-apt-plugin - 1.0 + ${maven-apt-plugin.version} generate-sources @@ -88,6 +88,7 @@ com.baeldung.springdatageode.app.ClientCacheApp 1.1.1.RELEASE 2.1.9.RELEASE + 1.0 \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-enterprise/pom.xml b/persistence-modules/spring-data-jpa-enterprise/pom.xml index 7ff2f00fdf..12ffeee7f0 100644 --- a/persistence-modules/spring-data-jpa-enterprise/pom.xml +++ b/persistence-modules/spring-data-jpa-enterprise/pom.xml @@ -78,7 +78,7 @@ maven-compiler-plugin - 3.8.1 + ${maven-compiler-plugin.version} 1.8 1.8 @@ -86,7 +86,7 @@ org.mapstruct mapstruct-processor - 1.3.1.Final + ${mapstruct.version} @@ -98,7 +98,6 @@ 1.3.1.Final 21.0 1.12.2 - diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/resources/logback.xml b/persistence-modules/spring-data-jpa-filtering/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/persistence-modules/spring-data-jpa-filtering/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java index 96eaf4ed07..5fdcf6a787 100644 --- a/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java +++ b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/projection/JpaProjectionIntegrationTest.java @@ -6,18 +6,15 @@ import com.baeldung.projection.repository.PersonRepository; import com.baeldung.projection.view.AddressView; import com.baeldung.projection.view.PersonDto; import com.baeldung.projection.view.PersonView; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.AFTER_TEST_METHOD; @DataJpaTest -@RunWith(SpringRunner.class) @Sql(scripts = "/projection-insert-data.sql") @Sql(scripts = "/projection-clean-up-data.sql", executionPhase = AFTER_TEST_METHOD) public class JpaProjectionIntegrationTest { diff --git a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java index 72d4dea377..c7ca9f1ffd 100644 --- a/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java +++ b/persistence-modules/spring-hibernate-5/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java @@ -162,6 +162,25 @@ public class ApplicationView { return betweenItems; } + // To get records having itemName in 'Skate Board', 'Paint' and 'Glue' + public String[] inCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Item.class); + final Root root = cr.from(Item.class); + cr.select(root) + .where(root.get("itemName").in("Skate Board", "Paint", "Glue")); + Query query = session.createQuery(cr); + final List inItemsList = query.getResultList(); + final String inItems[] = new String[inItemsList.size()]; + for (int i = 0; i < inItemsList.size(); i++) { + inItems[i] = inItemsList.get(i) + .getItemName(); + } + session.close(); + return inItems; + } + // To check if the given property is null public String[] nullCriteria() { final Session session = HibernateUtil.getHibernateSession(); diff --git a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java index 7d95e0f342..a1f88f3387 100644 --- a/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java +++ b/persistence-modules/spring-hibernate-5/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java @@ -189,6 +189,18 @@ public class HibernateCriteriaIntegrationTest { assertArrayEquals(expectedPriceBetweenItems, av.betweenCriteria()); } + @Test + public void inCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedInList = session.createQuery("From Item where itemName in ('Skate Board', 'Paint', 'Glue')").list(); + final String expectedNameInItems[] = new String[expectedInList.size()]; + for (int i = 0; i < expectedInList.size(); i++) { + expectedNameInItems[i] = expectedInList.get(i).getItemName(); + } + session.close(); + assertArrayEquals(expectedNameInItems, av.inCriteria()); + } + @Test public void givenNewItemPrice_whenCriteriaUpdate_thenReturnAffectedResult() { diff --git a/persistence-modules/spring-jooq/README.md b/persistence-modules/spring-jooq/README.md index 515ab8be3c..d0cb946614 100644 --- a/persistence-modules/spring-jooq/README.md +++ b/persistence-modules/spring-jooq/README.md @@ -5,6 +5,7 @@ This module contains articles about Spring with jOOQ ### Relevant Articles: - [Spring Boot Support for jOOQ](https://www.baeldung.com/spring-boot-support-for-jooq) - [Introduction to jOOQ with Spring](https://www.baeldung.com/jooq-with-spring) +- [Count Query In jOOQ](https://www.baeldung.com/jooq-count-query) In order to fix the error "Plugin execution not covered by lifecycle configuration: org.jooq:jooq-codegen-maven:3.7.3:generate (execution: default, phase: generate-sources)", right-click on the error message and choose "Mark goal generated as ignore in pom.xml". Until version 1.4.x, the maven-plugin-plugin was covered by the default lifecycle mapping that ships with m2e. diff --git a/persistence-modules/spring-jooq/src/test/java/com/baeldung/jooq/introduction/CountQueryIntegrationTest.java b/persistence-modules/spring-jooq/src/test/java/com/baeldung/jooq/introduction/CountQueryIntegrationTest.java new file mode 100644 index 0000000000..7edcc2cd4b --- /dev/null +++ b/persistence-modules/spring-jooq/src/test/java/com/baeldung/jooq/introduction/CountQueryIntegrationTest.java @@ -0,0 +1,96 @@ +package com.baeldung.jooq.introduction; + +import static com.baeldung.jooq.introduction.db.public_.tables.Author.AUTHOR; + +import java.util.ArrayList; +import java.util.List; + +import org.jooq.Condition; +import org.jooq.DSLContext; +import org.jooq.Record2; +import org.jooq.Result; +import org.jooq.impl.DSL; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +@ContextConfiguration(classes = PersistenceContextIntegrationTest.class) +@Transactional(transactionManager = "transactionManager") +@RunWith(SpringJUnit4ClassRunner.class) +public class CountQueryIntegrationTest { + + @Autowired + private DSLContext dsl; + + @Test + public void givenValidData_whenSimpleSelect_thenSucceed() { + int count = dsl.select().from(AUTHOR).execute(); + Assert.assertEquals(3, count); + } + + @Test + public void givenValidData_whenSelectCount_thenSucceed() { + int count = dsl.selectCount().from(AUTHOR) + .where(AUTHOR.FIRST_NAME.equalIgnoreCase("Bryan")) + .fetchOne(0, int.class); + Assert.assertEquals(1, count); + } + + @Test + public void givenValidData_whenCount_thenSucceed() { + int count = dsl.select(DSL.count()) + .from(AUTHOR).fetchOne(0, int.class); + Assert.assertEquals(3, count); + } + + @Test + public void givenValidData_whenFetchCount_thenSucceed() { + int count = dsl.fetchCount(DSL.selectFrom(AUTHOR) + .where(AUTHOR.FIRST_NAME.equalIgnoreCase("Bryan"))); + Assert.assertEquals(1, count); + } + + @Test + public void givenValidData_whenFetchCountWithoutCondition_thenSucceed() { + int count = dsl.fetchCount(DSL.selectFrom(AUTHOR)); + Assert.assertEquals(3, count); + } + + @Test + public void givenValidData_whenFetchCountWithSingleCondition_thenSucceed() { + int count = dsl.fetchCount(AUTHOR, AUTHOR.FIRST_NAME.equalIgnoreCase("Bryan")); + Assert.assertEquals(1, count); + } + + @Test + public void givenValidData_whenFetchCountWithMultipleConditions_thenSucceed() { + Condition firstCond = AUTHOR.FIRST_NAME.equalIgnoreCase("Bryan"); + Condition secondCond = AUTHOR.ID.notEqual(1); + List conditions = new ArrayList<>(); + conditions.add(firstCond); + conditions.add(secondCond); + int count = dsl.fetchCount(AUTHOR, conditions); + Assert.assertEquals(1, count); + } + + @Test + public void givenValidData_whenFetchCountWithConditionsInVarargs_thenSucceed() { + Condition firstCond = AUTHOR.FIRST_NAME.equalIgnoreCase("Bryan"); + Condition secondCond = AUTHOR.ID.notEqual(1); + int count = dsl.fetchCount(AUTHOR, firstCond, secondCond); + Assert.assertEquals(1, count); + } + + @Test + public void givenValidData_whenCountwithGroupBy_thenSucceed() { + final Result> result = dsl.select(AUTHOR.FIRST_NAME, DSL.count()) + .from(AUTHOR).groupBy(AUTHOR.FIRST_NAME).fetch(); + Assert.assertEquals(3, result.size()); + Assert.assertEquals(result.get(0).get(0), "Bert"); + Assert.assertEquals(result.get(0).get(1), 1); + } +} \ No newline at end of file diff --git a/persistence-modules/spring-jpa-2/pom.xml b/persistence-modules/spring-jpa-2/pom.xml index 7770c0e045..52067f3e5e 100644 --- a/persistence-modules/spring-jpa-2/pom.xml +++ b/persistence-modules/spring-jpa-2/pom.xml @@ -66,11 +66,6 @@ guava ${guava.version} - - net.bytebuddy - byte-buddy - ${byte-buddy.version} - @@ -97,7 +92,6 @@ 21.0 - 1.10.16 \ No newline at end of file diff --git a/pom.xml b/pom.xml index f202430ccf..13f24d7aea 100644 --- a/pom.xml +++ b/pom.xml @@ -412,6 +412,7 @@ google-web-toolkit + graphql/graphql-java grpc @@ -531,7 +532,7 @@ protobuffer quarkus - + quarkus-extension rabbitmq @@ -614,11 +615,12 @@ spring-aop spring-apache-camel - spring-batch - spring-batch-2 + spring-batch + spring-batch-2 spring-bom spring-boot-modules spring-boot-rest + spring-boot-rest-2 spring-caching @@ -875,6 +877,7 @@ google-web-toolkit + graphql/graphql-java grpc @@ -930,6 +933,7 @@ jooby jsf json + json-2 json-path jsoup jta @@ -992,7 +996,7 @@ protobuffer quarkus - + quarkus-extension rabbitmq @@ -1068,9 +1072,11 @@ spring-apache-camel spring-batch + spring-batch-2 spring-bom spring-boot-modules spring-boot-rest + spring-boot-rest-2 spring-caching @@ -1089,6 +1095,7 @@ spring-data-rest spring-data-rest-querydsl spring-di + spring-di-2 spring-drools spring-ejb @@ -1273,7 +1280,7 @@ 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 @@ -1318,6 +1325,7 @@ 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 @@ -1351,13 +1359,13 @@ false false false - true + true 4.12 2.2 1.3 3.3.0 - 1.10.5 + 1.10.22 1.7.30 @@ -1371,8 +1379,8 @@ 1.8 1.2.17 2.2.2.0 - 1.19 - 1.19 + 1.28 + 1.28 1.6.0 2.21.0 2.8.0 diff --git a/quarkus-extension/quarkus-app/pom.xml b/quarkus-extension/quarkus-app/pom.xml index 6d3f4c7c28..4c9e9c3cc7 100644 --- a/quarkus-extension/quarkus-app/pom.xml +++ b/quarkus-extension/quarkus-app/pom.xml @@ -27,9 +27,10 @@ com.baeldung.quarkus.liquibase - quarkus-liquibase-runtime + runtime ${project.version} + io.quarkus quarkus-jdbc-h2 diff --git a/quarkus-extension/quarkus-liquibase/deployment/pom.xml b/quarkus-extension/quarkus-liquibase/deployment/pom.xml index d7f1f995ff..42d3ca2810 100644 --- a/quarkus-extension/quarkus-liquibase/deployment/pom.xml +++ b/quarkus-extension/quarkus-liquibase/deployment/pom.xml @@ -3,6 +3,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 + com.baeldung.quarkus.liquibase deployment deployment @@ -30,7 +31,7 @@ com.baeldung.quarkus.liquibase - quarkus-liquibase-runtime + runtime ${project.version} diff --git a/quarkus-extension/quarkus-liquibase/runtime/pom.xml b/quarkus-extension/quarkus-liquibase/runtime/pom.xml index 5d3b05ef92..0250d34711 100644 --- a/quarkus-extension/quarkus-liquibase/runtime/pom.xml +++ b/quarkus-extension/quarkus-liquibase/runtime/pom.xml @@ -2,6 +2,7 @@ 4.0.0 + com.baeldung.quarkus.liquibase runtime runtime @@ -41,7 +42,7 @@ extension-descriptor - ${project.groupId}:quarkus-liquibase-deployment:${project.version} + ${project.groupId}:deployment:${project.version} diff --git a/quarkus/pom.xml b/quarkus/pom.xml index 9c14afca3c..9826fd1034 100644 --- a/quarkus/pom.xml +++ b/quarkus/pom.xml @@ -97,7 +97,6 @@ maven-surefire-plugin - ${surefire-plugin.version} 1 true @@ -136,7 +135,6 @@ maven-failsafe-plugin - ${surefire-plugin.version} @@ -157,7 +155,6 @@ - 2.22.0 1.7.0.Final 5.6.0 diff --git a/reactive-systems/inventory-service/pom.xml b/reactive-systems/inventory-service/pom.xml index 4c04afb5cb..b5ec210636 100644 --- a/reactive-systems/inventory-service/pom.xml +++ b/reactive-systems/inventory-service/pom.xml @@ -15,10 +15,6 @@ ../../parent-boot-2 - - 1.8 - - org.springframework.boot diff --git a/reactive-systems/order-service/pom.xml b/reactive-systems/order-service/pom.xml index c793f448b5..603f0373ba 100644 --- a/reactive-systems/order-service/pom.xml +++ b/reactive-systems/order-service/pom.xml @@ -15,10 +15,6 @@ ../../parent-boot-2 - - 1.8 - - org.springframework.boot diff --git a/reactive-systems/shipping-service/pom.xml b/reactive-systems/shipping-service/pom.xml index 72487e691e..458b91b6ce 100644 --- a/reactive-systems/shipping-service/pom.xml +++ b/reactive-systems/shipping-service/pom.xml @@ -15,10 +15,6 @@ ../../parent-boot-2 - - 1.8 - - org.springframework.boot diff --git a/spring-5-reactive-client/pom.xml b/spring-5-reactive-client/pom.xml index 66861a3bb6..28f692a735 100644 --- a/spring-5-reactive-client/pom.xml +++ b/spring-5-reactive-client/pom.xml @@ -150,21 +150,6 @@ 1.8 - - maven-surefire-plugin - 2.22.0 - - - maven-surefire-plugin - 2.19.1 - - - org.junit.platform - junit-platform-surefire-provider - 1.0.1 - - - diff --git a/spring-5/pom.xml b/spring-5/pom.xml index e368bcacba..082b1f8a87 100644 --- a/spring-5/pom.xml +++ b/spring-5/pom.xml @@ -142,7 +142,6 @@ 1.5.6 4.1 ${project.build.directory}/generated-snippets - 2.21.0 diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 4902368d7e..0288b03928 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -106,17 +106,8 @@ - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.2 - - - - 5.6.2 + 2.22.2 diff --git a/spring-boot-modules/spring-boot-actuator/pom.xml b/spring-boot-modules/spring-boot-actuator/pom.xml index a808b8cb1b..3cb324a0b8 100644 --- a/spring-boot-modules/spring-boot-actuator/pom.xml +++ b/spring-boot-modules/spring-boot-actuator/pom.xml @@ -28,6 +28,10 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.springframework.boot + spring-boot-starter-security + com.h2database h2 @@ -44,6 +48,11 @@ + + org.springframework.security + spring-security-test + test + @@ -53,6 +62,7 @@ spring-boot-maven-plugin com.baeldung.probes.ProbesApplication + com.baeldung.endpoints.enabling.EndpointEnablingApplication diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/enabling/EndpointEnablingApplication.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/enabling/EndpointEnablingApplication.java new file mode 100644 index 0000000000..2e8024dcd5 --- /dev/null +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/enabling/EndpointEnablingApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.endpoints.enabling; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; + +@SpringBootApplication(exclude = { SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class }, scanBasePackages = "com.baeldung.endpoints.enabling") +public class EndpointEnablingApplication { + + public static void main(String[] args) { + SpringApplication.run(EndpointEnablingApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/enabling/SecurityConfiguration.java b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/enabling/SecurityConfiguration.java new file mode 100644 index 0000000000..894c24693e --- /dev/null +++ b/spring-boot-modules/spring-boot-actuator/src/main/java/com/baeldung/endpoints/enabling/SecurityConfiguration.java @@ -0,0 +1,36 @@ +package com.baeldung.endpoints.enabling; + +import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest; +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.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +@EnableWebSecurity +public class SecurityConfiguration extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); + auth.inMemoryAuthentication() + .withUser("user") + .password(encoder.encode("password")) + .roles("USER") + .and() + .withUser("admin") + .password(encoder.encode("admin")) + .roles("USER", "ADMIN"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.requestMatcher(EndpointRequest.toAnyEndpoint()) + .authorizeRequests((requests) -> requests.anyRequest() + .hasRole("ADMIN")); + http.httpBasic(); + } +} diff --git a/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties b/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties index de7be417a8..e69c763eeb 100644 --- a/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-actuator/src/main/resources/application.properties @@ -11,3 +11,6 @@ info.app.name=Spring Sample Application info.app.description=This is my first spring boot application G1 info.app.version=1.0.0 info.java-vendor = ${java.specification.vendor} + +management.endpoints.web.exposure.include=* +management.endpoint.shutdown.enabled=true diff --git a/spring-boot-modules/spring-boot-actuator/src/test/java/com/baeldung/endpoints/enabling/EndpointEnablingIntegrationTest.java b/spring-boot-modules/spring-boot-actuator/src/test/java/com/baeldung/endpoints/enabling/EndpointEnablingIntegrationTest.java new file mode 100644 index 0000000000..8274619517 --- /dev/null +++ b/spring-boot-modules/spring-boot-actuator/src/test/java/com/baeldung/endpoints/enabling/EndpointEnablingIntegrationTest.java @@ -0,0 +1,36 @@ +package com.baeldung.endpoints.enabling; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +public class EndpointEnablingIntegrationTest { + @Autowired + private MockMvc mockMvc; + + @Test + @WithMockUser(username = "user", password = "password", roles = "USER") + public void givenWrongAuthentication_whenCallingActuator_thenReturns401() throws Exception { + mockMvc.perform(get("/actuator")) + .andExpect(status().isForbidden()); + } + + @Test + @WithMockUser(username = "admin", password = "admin", roles = "ADMIN") + public void givenProperAuthentication_whenCallingActuator_thenReturnsExpectedEndpoints() throws Exception { + mockMvc.perform(get("/actuator")) + .andExpect(jsonPath("$._links").exists()) + .andExpect(jsonPath("$._links.beans").exists()) + .andExpect(jsonPath("$._links.env").exists()) + .andExpect(jsonPath("$._links.shutdown").exists()); + } +} diff --git a/spring-boot-modules/spring-boot-autoconfiguration/pom.xml b/spring-boot-modules/spring-boot-autoconfiguration/pom.xml index 269d87bbb9..4990e6884c 100644 --- a/spring-boot-modules/spring-boot-autoconfiguration/pom.xml +++ b/spring-boot-modules/spring-boot-autoconfiguration/pom.xml @@ -48,7 +48,6 @@ org.springframework.boot spring-boot-configuration-processor - 2.1.6.RELEASE true diff --git a/spring-boot-modules/spring-boot-bootstrap/pom.xml b/spring-boot-modules/spring-boot-bootstrap/pom.xml index 6a1be7a2c8..5f1cd8fb65 100644 --- a/spring-boot-modules/spring-boot-bootstrap/pom.xml +++ b/spring-boot-modules/spring-boot-bootstrap/pom.xml @@ -167,7 +167,7 @@ org.springframework.cloud spring-cloud-dependencies - Greenwich.RELEASE + ${spring-cloud.version} pom import @@ -177,12 +177,12 @@ org.springframework.cloud spring-cloud-gcp-starter - 1.0.0.RELEASE + ${spring-cloud-gcp.version} org.springframework.cloud spring-cloud-gcp-starter-sql-mysql - 1.0.0.RELEASE + ${spring-cloud-gcp.version} @@ -215,7 +215,7 @@ org.springframework.cloud spring-cloud-dependencies - Greenwich.RELEASE + ${spring-cloud.version} pom import @@ -332,6 +332,8 @@ 4.0.0 + Greenwich.RELEASE + 1.0.0.RELEASE diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml index 532f45cf3e..4903f21c77 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-autoconfigure/pom.xml @@ -62,7 +62,6 @@ - UTF-8 2.2.6.RELEASE 0.0.1-SNAPSHOT diff --git a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml index 0e8fb4cbc9..85a6721492 100644 --- a/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml +++ b/spring-boot-modules/spring-boot-custom-starter/greeter-spring-boot-starter/pom.xml @@ -49,7 +49,6 @@ - UTF-8 0.0.1-SNAPSHOT 2.2.6.RELEASE diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md index 29d9dafe66..875ee502b4 100644 --- a/spring-boot-modules/spring-boot-data-2/README.md +++ b/spring-boot-modules/spring-boot-data-2/README.md @@ -2,3 +2,4 @@ - [Spring Boot: Customize the Jackson ObjectMapper](https://www.baeldung.com/spring-boot-customize-jackson-objectmapper) - [“HttpMessageNotWritableException: No converter found for return value of type”](https://www.baeldung.com/spring-no-converter-found) +- [Creating a Read-Only Repository with Spring Data](https://www.baeldung.com/spring-data-read-only-repository) diff --git a/spring-boot-modules/spring-boot-libraries-2/README.md b/spring-boot-modules/spring-boot-libraries-2/README.md index 4218dfc1be..7bf51b5424 100644 --- a/spring-boot-modules/spring-boot-libraries-2/README.md +++ b/spring-boot-modules/spring-boot-libraries-2/README.md @@ -5,3 +5,4 @@ This module contains articles about various Spring Boot libraries ### Relevant Articles: - [Background Jobs in Spring with JobRunr](https://www.baeldung.com/java-jobrunr-spring) +- [Open API Server Implementation Using OpenAPI Generator](https://www.baeldung.com/java-openapi-generator-server) diff --git a/spring-boot-modules/spring-boot-libraries-2/pom.xml b/spring-boot-modules/spring-boot-libraries-2/pom.xml index 35dec54450..629b713cb5 100644 --- a/spring-boot-modules/spring-boot-libraries-2/pom.xml +++ b/spring-boot-modules/spring-boot-libraries-2/pom.xml @@ -16,6 +16,14 @@ org.springframework.boot spring-boot-starter-web + + ch.qos.logback + logback-classic + + + org.springframework.data + spring-data-jpa + @@ -23,6 +31,23 @@ jobrunr-spring-boot-starter ${jobrunr.version} + + + + org.openapitools + openapi-generator + ${openapi-generator.version} + + + org.openapitools + jackson-databind-nullable + ${jackson-databind.version} + + + io.springfox + springfox-swagger2 + ${springfox.version} + org.springframework.boot @@ -37,10 +62,45 @@ test + + + + + org.openapitools + openapi-generator-maven-plugin + ${openapi-generator.version} + + + + generate + + + + ${project.basedir}/src/main/resources/petstore.yml + + spring + com.baeldung.openapi.api + com.baeldung.openapi.model + + ApiUtil.java + + + true + + + + + + + 1.1.0 4.0.3 + 5.1.0 + 2.4.5 + 0.2.1 + 2.9.2 diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/jobrunr/JobRunrSpringBootApp.java b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/JobRunrSpringBootApp.java similarity index 97% rename from spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/jobrunr/JobRunrSpringBootApp.java rename to spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/JobRunrSpringBootApp.java index d72e9464d9..77297feb92 100644 --- a/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/jobrunr/JobRunrSpringBootApp.java +++ b/spring-boot-modules/spring-boot-libraries-2/src/main/java/com/baeldung/JobRunrSpringBootApp.java @@ -1,4 +1,4 @@ -package com.baeldung.jobrunr; +package com.baeldung; import com.baeldung.jobrunr.service.SampleJobService; import org.jobrunr.jobs.mappers.JobMapper; diff --git a/spring-boot-modules/spring-boot-libraries-2/src/main/resources/petstore.yml b/spring-boot-modules/spring-boot-libraries-2/src/main/resources/petstore.yml new file mode 100644 index 0000000000..3265a18c3e --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-2/src/main/resources/petstore.yml @@ -0,0 +1,111 @@ +openapi: "3.0.0" +info: + version: 1.0.0 + title: Swagger Petstore + license: + name: MIT +servers: + - url: http://localhost:8080/ +paths: + /pets: + get: + summary: List all pets + operationId: listPets + tags: + - pets + parameters: + - name: limit + in: query + description: How many items to return at one time (max 100) + required: false + schema: + type: integer + format: int32 + responses: + '200': + description: A paged array of pets + headers: + x-next: + description: A link to the next page of responses + schema: + type: string + content: + application/json: + schema: + $ref: "#/components/schemas/Pets" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + post: + summary: Create a pet + operationId: createPets + tags: + - pets + responses: + '201': + description: Null response + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" + /pets/{petId}: + get: + summary: Info for a specific pet + operationId: showPetById + tags: + - pets + parameters: + - name: petId + in: path + required: true + description: The id of the pet to retrieve + schema: + type: string + responses: + '200': + description: Expected response to a valid request + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + default: + description: unexpected error + content: + application/json: + schema: + $ref: "#/components/schemas/Error" +components: + schemas: + Pet: + type: object + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string + Pets: + type: array + items: + $ref: "#/components/schemas/Pet" + Error: + type: object + required: + - code + - message + properties: + code: + type: integer + format: int32 + message: + type: string \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-libraries-2/src/test/java/com/baeldung/jobrunr/JobRunrLiveTest.java b/spring-boot-modules/spring-boot-libraries-2/src/test/java/com/baeldung/jobrunr/JobRunrLiveTest.java index 83222e7726..2c259b6879 100644 --- a/spring-boot-modules/spring-boot-libraries-2/src/test/java/com/baeldung/jobrunr/JobRunrLiveTest.java +++ b/spring-boot-modules/spring-boot-libraries-2/src/test/java/com/baeldung/jobrunr/JobRunrLiveTest.java @@ -10,6 +10,8 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.test.context.junit4.SpringRunner; +import com.baeldung.JobRunrSpringBootApp; + import java.net.URI; import java.util.concurrent.TimeUnit; diff --git a/spring-boot-modules/spring-boot-libraries-2/src/test/java/com/baeldung/openapi/OpenApiPetsIntegrationTest.java b/spring-boot-modules/spring-boot-libraries-2/src/test/java/com/baeldung/openapi/OpenApiPetsIntegrationTest.java new file mode 100644 index 0000000000..b56c19d94c --- /dev/null +++ b/spring-boot-modules/spring-boot-libraries-2/src/test/java/com/baeldung/openapi/OpenApiPetsIntegrationTest.java @@ -0,0 +1,35 @@ +package com.baeldung.openapi; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +@RunWith(SpringRunner.class) +@SpringBootTest +@AutoConfigureMockMvc +public class OpenApiPetsIntegrationTest { + + private static final String PETS_PATH = "/pets/"; + + @Autowired + private MockMvc mockMvc; + + @Test + public void whenReadAll_thenStatusIsNotImplemented() throws Exception { + this.mockMvc.perform(get(PETS_PATH)) + .andExpect(status().isNotImplemented()); + } + + @Test + public void whenReadOne_thenStatusIsNotImplemented() throws Exception { + this.mockMvc.perform(get(PETS_PATH + 1)) + .andExpect(status().isNotImplemented()); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-parent/spring-boot-with-custom-parent/pom.xml b/spring-boot-modules/spring-boot-parent/spring-boot-with-custom-parent/pom.xml index 5f5d3a9f6a..63d6078eca 100644 --- a/spring-boot-modules/spring-boot-parent/spring-boot-with-custom-parent/pom.xml +++ b/spring-boot-modules/spring-boot-parent/spring-boot-with-custom-parent/pom.xml @@ -23,8 +23,4 @@ - - 1.8 - - diff --git a/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml b/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml index 108e66b68e..4274f63aa3 100644 --- a/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml +++ b/spring-boot-modules/spring-boot-parent/spring-boot-with-starter-parent/pom.xml @@ -39,7 +39,6 @@ - 1.8 2.2.5.RELEASE diff --git a/spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java b/spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java index 195b260399..72c55e2de5 100644 --- a/spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java +++ b/spring-boot-modules/spring-boot-performance/src/main/java/com/baeldung/lazyinitialization/Application.java @@ -3,6 +3,7 @@ package com.baeldung.lazyinitialization; import com.baeldung.lazyinitialization.services.Writer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; @@ -20,7 +21,9 @@ public class Application { } public static void main(String[] args) { + ApplicationContext ctx = SpringApplication.run(Application.class, args); + System.out.println("Application context initialized!!!"); Writer writer1 = ctx.getBean("writer1", Writer.class); @@ -29,4 +32,23 @@ public class Application { Writer writer2 = ctx.getBean("writer2", Writer.class); writer2.write("Second message"); } + + /* + This method shows how to set lazy initialization and start the application using SpringApplicationBuilder + */ + private static ApplicationContext runUsingSpringApplicationBuilder(String[] args){ + return new SpringApplicationBuilder(Application.class) + .lazyInitialization(true) + .build(args) + .run(); + } + + /* + This method shows how to set lazy initialization and start the application using SpringApplication + */ + private static ApplicationContext runUsingSpringApplication(String[] args){ + SpringApplication app = new SpringApplication(Application.class); + app.setLazyInitialization(true); + return app.run(args); + } } diff --git a/spring-boot-modules/spring-boot-properties-3/pom.xml b/spring-boot-modules/spring-boot-properties-3/pom.xml index 809fd6e2d4..33799b557d 100644 --- a/spring-boot-modules/spring-boot-properties-3/pom.xml +++ b/spring-boot-modules/spring-boot-properties-3/pom.xml @@ -14,9 +14,6 @@ spring-boot-properties-3 Spring Boot Properties Module - - 1.8 - org.springframework.boot diff --git a/spring-boot-modules/spring-boot-properties/pom.xml b/spring-boot-modules/spring-boot-properties/pom.xml index 40668f47fd..0a7d8a8cbf 100644 --- a/spring-boot-modules/spring-boot-properties/pom.xml +++ b/spring-boot-modules/spring-boot-properties/pom.xml @@ -134,7 +134,6 @@ - 1.8 2020.0.0-M5 1.10 20.0 diff --git a/spring-boot-modules/spring-boot-security/pom.xml b/spring-boot-modules/spring-boot-security/pom.xml index 33b7cbfd74..3f8d2ff73f 100644 --- a/spring-boot-modules/spring-boot-security/pom.xml +++ b/spring-boot-modules/spring-boot-security/pom.xml @@ -71,7 +71,6 @@ org.springframework.boot spring-boot-autoconfigure - diff --git a/spring-boot-modules/spring-boot-springdoc/pom.xml b/spring-boot-modules/spring-boot-springdoc/pom.xml index 259383a1d2..8442504fed 100644 --- a/spring-boot-modules/spring-boot-springdoc/pom.xml +++ b/spring-boot-modules/spring-boot-springdoc/pom.xml @@ -169,7 +169,6 @@ - 1.8 5.2.10.Final 1.5.2 1.5.6 diff --git a/spring-boot-modules/spring-boot-swagger-jwt/pom.xml b/spring-boot-modules/spring-boot-swagger-jwt/pom.xml index d71d7342ce..6ee7db2ac9 100644 --- a/spring-boot-modules/spring-boot-swagger-jwt/pom.xml +++ b/spring-boot-modules/spring-boot-swagger-jwt/pom.xml @@ -25,7 +25,7 @@ io.springfox springfox-boot-starter - 3.0.0 + ${springfox.version} @@ -38,4 +38,8 @@ + + 3.0.0 + + diff --git a/spring-boot-modules/spring-boot-swagger/pom.xml b/spring-boot-modules/spring-boot-swagger/pom.xml index 4e0180460d..2d80cae4d5 100644 --- a/spring-boot-modules/spring-boot-swagger/pom.xml +++ b/spring-boot-modules/spring-boot-swagger/pom.xml @@ -25,7 +25,7 @@ io.springfox springfox-boot-starter - 3.0.0 + ${springfox.version} @@ -38,4 +38,8 @@ + + 3.0.0 + + diff --git a/spring-caching/pom.xml b/spring-caching/pom.xml index 9fa9ba0333..c620072604 100644 --- a/spring-caching/pom.xml +++ b/spring-caching/pom.xml @@ -71,11 +71,6 @@ org.springframework.boot spring-boot-starter-data-jpa - - net.bytebuddy - byte-buddy - 1.10.11 - org.springframework.data spring-data-commons diff --git a/spring-cloud/spring-cloud-bootstrap/order-service/pom.xml b/spring-cloud/spring-cloud-bootstrap/order-service/pom.xml index a32bd5a2d3..2ebc673ef4 100644 --- a/spring-cloud/spring-cloud-bootstrap/order-service/pom.xml +++ b/spring-cloud/spring-cloud-bootstrap/order-service/pom.xml @@ -112,7 +112,6 @@ - 1.8 2.6 0.0.2 1.8 diff --git a/spring-cloud/spring-cloud-connectors-heroku/pom.xml b/spring-cloud/spring-cloud-connectors-heroku/pom.xml index e71e1350a2..d318aa3c64 100644 --- a/spring-cloud/spring-cloud-connectors-heroku/pom.xml +++ b/spring-cloud/spring-cloud-connectors-heroku/pom.xml @@ -35,11 +35,6 @@ org.postgresql postgresql - - net.bytebuddy - byte-buddy-dep - ${bytebuddy.version} - com.h2database h2 @@ -63,8 +58,6 @@ 2.2.6.RELEASE Hoxton.SR4 42.2.10 - 1.10.10 - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/kubernetes-selfhealing/liveness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/kubernetes-selfhealing/liveness-example/pom.xml index f0d34d2231..16e718a3be 100644 --- a/spring-cloud/spring-cloud-kubernetes/kubernetes-selfhealing/liveness-example/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/kubernetes-selfhealing/liveness-example/pom.xml @@ -41,9 +41,4 @@ - - UTF-8 - UTF-8 - - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-kubernetes/kubernetes-selfhealing/readiness-example/pom.xml b/spring-cloud/spring-cloud-kubernetes/kubernetes-selfhealing/readiness-example/pom.xml index 8bfd4d305d..0ee40b6504 100644 --- a/spring-cloud/spring-cloud-kubernetes/kubernetes-selfhealing/readiness-example/pom.xml +++ b/spring-cloud/spring-cloud-kubernetes/kubernetes-selfhealing/readiness-example/pom.xml @@ -41,9 +41,4 @@ - - UTF-8 - UTF-8 - - \ No newline at end of file diff --git a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml index 52230dd1c1..32a31c3042 100644 --- a/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml +++ b/spring-cloud/spring-cloud-stream/spring-cloud-stream-kafka/pom.xml @@ -101,7 +101,6 @@ - 1.8 Greenwich.SR1 4.0.0 1.8.2 diff --git a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml index 4e6b8b8b6c..fd10322efb 100644 --- a/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml +++ b/spring-cloud/spring-cloud-task/springcloudtaskbatch/pom.xml @@ -45,13 +45,6 @@ org.springframework.cloud spring-cloud-task-batch - - - net.bytebuddy - byte-buddy-dep - ${bytebuddy.version} - - com.h2database h2 @@ -70,7 +63,6 @@ com.baeldung.TaskDemo - 1.10.10 diff --git a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml index c7b35ef934..c6658d70a2 100644 --- a/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml +++ b/spring-cloud/spring-cloud-zuul-eureka-integration/bin/pom.xml @@ -22,7 +22,6 @@ - UTF-8 3.7.0 1.4.2.RELEASE 1.10 diff --git a/spring-cloud/spring-cloud-zuul-fallback/pom.xml b/spring-cloud/spring-cloud-zuul-fallback/pom.xml index cb762eb099..42925a6ab9 100644 --- a/spring-cloud/spring-cloud-zuul-fallback/pom.xml +++ b/spring-cloud/spring-cloud-zuul-fallback/pom.xml @@ -21,7 +21,6 @@ - 1.8 Finchley.SR2 3.1.1 diff --git a/spring-core-3/pom.xml b/spring-core-3/pom.xml index 205259e8e4..618800529c 100644 --- a/spring-core-3/pom.xml +++ b/spring-core-3/pom.xml @@ -69,18 +69,7 @@ - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven.surefire.version} - - - - - 2.22.1 1.3.2 2.2.2.RELEASE diff --git a/spring-core-4/pom.xml b/spring-core-4/pom.xml index df0b90fef2..d2e948c475 100644 --- a/spring-core-4/pom.xml +++ b/spring-core-4/pom.xml @@ -87,18 +87,7 @@ - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven.surefire.version} - - - - - 2.22.1 1.3.2 2.2.2.RELEASE 28.2-jre diff --git a/spring-core-5/README.md b/spring-core-5/README.md index 4109faca67..6befae7372 100644 --- a/spring-core-5/README.md +++ b/spring-core-5/README.md @@ -5,4 +5,5 @@ This module contains articles about core Spring functionality ## Relevant Articles: - [Spring @Component Annotation](https://www.baeldung.com/spring-component-annotation) +- [Solving Spring’s “not eligible for auto-proxying” Warning](https://www.baeldung.com/spring-not-eligible-for-auto-proxying) - More articles: [[<-- prev]](/spring-core-4) diff --git a/spring-core-5/pom.xml b/spring-core-5/pom.xml index 743002c137..05ee1c5f5d 100644 --- a/spring-core-5/pom.xml +++ b/spring-core-5/pom.xml @@ -25,22 +25,16 @@ ${spring-boot-starter.version} test + + org.projectlombok + lombok + ${lombok.version} + - - - - org.apache.maven.plugins - maven-surefire-plugin - ${maven.surefire.version} - - - - 5.3.3 2.4.2 - 2.22.1 diff --git a/spring-core-5/src/main/java/com/baeldung/component/autoproxying/DataCache.java b/spring-core-5/src/main/java/com/baeldung/component/autoproxying/DataCache.java new file mode 100644 index 0000000000..bc92d0a1d9 --- /dev/null +++ b/spring-core-5/src/main/java/com/baeldung/component/autoproxying/DataCache.java @@ -0,0 +1,12 @@ +package com.baeldung.component.autoproxying; + +import lombok.Getter; +import org.springframework.stereotype.Component; + +@Getter +@Component +public class DataCache { + @RandomInt(min = 2, max = 10) + private int group; + private String name; +} diff --git a/spring-core-5/src/main/java/com/baeldung/component/autoproxying/EligibleForAutoProxyRandomIntProcessor.java b/spring-core-5/src/main/java/com/baeldung/component/autoproxying/EligibleForAutoProxyRandomIntProcessor.java new file mode 100644 index 0000000000..1fa9aa376f --- /dev/null +++ b/spring-core-5/src/main/java/com/baeldung/component/autoproxying/EligibleForAutoProxyRandomIntProcessor.java @@ -0,0 +1,33 @@ +package com.baeldung.component.autoproxying; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.annotation.Lazy; +import org.springframework.util.ReflectionUtils; + +import java.lang.reflect.Field; + +public class EligibleForAutoProxyRandomIntProcessor implements BeanPostProcessor { + private final RandomIntGenerator randomIntGenerator; + + @Lazy + public EligibleForAutoProxyRandomIntProcessor(RandomIntGenerator randomIntGenerator) { + this.randomIntGenerator = randomIntGenerator; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + Field[] fields = bean.getClass().getDeclaredFields(); + for (Field field : fields) { + RandomInt injectRandomInt = field.getAnnotation(RandomInt.class); + if (injectRandomInt != null) { + int min = injectRandomInt.min(); + int max = injectRandomInt.max(); + int randomValue = randomIntGenerator.generate(min, max); + field.setAccessible(true); + ReflectionUtils.setField(field, bean, randomValue); + } + } + return bean; + } +} diff --git a/spring-core-5/src/main/java/com/baeldung/component/autoproxying/NotEligibleForAutoProxyRandomIntProcessor.java b/spring-core-5/src/main/java/com/baeldung/component/autoproxying/NotEligibleForAutoProxyRandomIntProcessor.java new file mode 100644 index 0000000000..d02780011c --- /dev/null +++ b/spring-core-5/src/main/java/com/baeldung/component/autoproxying/NotEligibleForAutoProxyRandomIntProcessor.java @@ -0,0 +1,31 @@ +package com.baeldung.component.autoproxying; + +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.util.ReflectionUtils; + +import java.lang.reflect.Field; + +public class NotEligibleForAutoProxyRandomIntProcessor implements BeanPostProcessor { + private final RandomIntGenerator randomIntGenerator; + + public NotEligibleForAutoProxyRandomIntProcessor(RandomIntGenerator randomIntGenerator) { + this.randomIntGenerator = randomIntGenerator; + } + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { + Field[] fields = bean.getClass().getDeclaredFields(); + for (Field field : fields) { + RandomInt injectRandomInt = field.getAnnotation(RandomInt.class); + if (injectRandomInt != null) { + int min = injectRandomInt.min(); + int max = injectRandomInt.max(); + int randomValue = randomIntGenerator.generate(min, max); + field.setAccessible(true); + ReflectionUtils.setField(field, bean, randomValue); + } + } + return bean; + } +} diff --git a/spring-core-5/src/main/java/com/baeldung/component/autoproxying/RandomInt.java b/spring-core-5/src/main/java/com/baeldung/component/autoproxying/RandomInt.java new file mode 100644 index 0000000000..c7881af4af --- /dev/null +++ b/spring-core-5/src/main/java/com/baeldung/component/autoproxying/RandomInt.java @@ -0,0 +1,11 @@ +package com.baeldung.component.autoproxying; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +public @interface RandomInt { + int min(); + + int max(); +} diff --git a/spring-core-5/src/main/java/com/baeldung/component/autoproxying/RandomIntGenerator.java b/spring-core-5/src/main/java/com/baeldung/component/autoproxying/RandomIntGenerator.java new file mode 100644 index 0000000000..d0d44c3333 --- /dev/null +++ b/spring-core-5/src/main/java/com/baeldung/component/autoproxying/RandomIntGenerator.java @@ -0,0 +1,21 @@ +package com.baeldung.component.autoproxying; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +import java.util.Random; + +@Slf4j +@Component +public class RandomIntGenerator { + private final Random random = new Random(); + private final DataCache dataCache; + + public RandomIntGenerator(DataCache dataCache) { + this.dataCache = dataCache; + } + + public int generate(int min, int max) { + return random.nextInt(max - min) + min; + } +} diff --git a/spring-core-5/src/test/java/com/baeldung/component/autoproxying/EligibleForAutoProxyingIntegrationTest.java b/spring-core-5/src/test/java/com/baeldung/component/autoproxying/EligibleForAutoProxyingIntegrationTest.java new file mode 100644 index 0000000000..4af700813a --- /dev/null +++ b/spring-core-5/src/test/java/com/baeldung/component/autoproxying/EligibleForAutoProxyingIntegrationTest.java @@ -0,0 +1,49 @@ +package com.baeldung.component.autoproxying; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.ILoggingEvent; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {EligibleForAutoProxyRandomIntProcessor.class, DataCache.class, RandomIntGenerator.class}) +public class EligibleForAutoProxyingIntegrationTest { + private static MemoryLogAppender memoryAppender; + + private EligibleForAutoProxyRandomIntProcessor randomIntProcessor; + + @Autowired + private DataCache dataCache; + + @BeforeClass + public static void setup() { + memoryAppender = new MemoryLogAppender(); + memoryAppender.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); + + Logger logger = (Logger) LoggerFactory.getLogger("org.springframework.context"); + logger.setLevel(Level.INFO); + logger.addAppender(memoryAppender); + memoryAppender.start(); + } + + @Test + public void givenAutowireInBeanPostProcessor_whenSpringContextInitialize_thenNotEligibleLogShouldShowAndGroupFieldPopulated() { + List notEligibleEvents = memoryAppender.search("Bean 'randomIntGenerator' of type [com.baeldung.autoproxying.RandomIntGenerator] " + + "is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)"); + + assertEquals(0, notEligibleEvents.size()); + assertNotEquals(0, dataCache.getGroup()); + } +} diff --git a/spring-core-5/src/test/java/com/baeldung/component/autoproxying/MemoryLogAppender.java b/spring-core-5/src/test/java/com/baeldung/component/autoproxying/MemoryLogAppender.java new file mode 100644 index 0000000000..fad35a7c2b --- /dev/null +++ b/spring-core-5/src/test/java/com/baeldung/component/autoproxying/MemoryLogAppender.java @@ -0,0 +1,48 @@ +package com.baeldung.component.autoproxying; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; + +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +public class MemoryLogAppender extends ListAppender { + public void reset() { + this.list.clear(); + } + + public boolean contains(String string, Level level) { + return this.list.stream() + .anyMatch(event -> event.getMessage().toString().contains(string) + && event.getLevel().equals(level)); + } + + public int countEventsForLogger(String loggerName) { + return (int) this.list.stream() + .filter(event -> event.getLoggerName().contains(loggerName)) + .count(); + } + + public List search(String string) { + return this.list.stream() + .filter(event -> event.getMessage().toString().contains(string)) + .collect(Collectors.toList()); + } + + public List search(String string, Level level) { + return this.list.stream() + .filter(event -> event.getMessage().toString().contains(string) + && event.getLevel().equals(level)) + .collect(Collectors.toList()); + } + + public int getSize() { + return this.list.size(); + } + + public List getLoggedEvents() { + return Collections.unmodifiableList(this.list); + } +} diff --git a/spring-core-5/src/test/java/com/baeldung/component/autoproxying/NotEligibleForAutoProxyingIntegrationTest.java b/spring-core-5/src/test/java/com/baeldung/component/autoproxying/NotEligibleForAutoProxyingIntegrationTest.java new file mode 100644 index 0000000000..9434f77a30 --- /dev/null +++ b/spring-core-5/src/test/java/com/baeldung/component/autoproxying/NotEligibleForAutoProxyingIntegrationTest.java @@ -0,0 +1,48 @@ +package com.baeldung.component.autoproxying; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.ILoggingEvent; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.List; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {NotEligibleForAutoProxyRandomIntProcessor.class, DataCache.class, RandomIntGenerator.class}) +public class NotEligibleForAutoProxyingIntegrationTest { + private static MemoryLogAppender memoryAppender; + + private NotEligibleForAutoProxyRandomIntProcessor proxyRandomIntProcessor; + + @Autowired + private DataCache dataCache; + + @BeforeClass + public static void setup() { + memoryAppender = new MemoryLogAppender(); + memoryAppender.setContext((LoggerContext) LoggerFactory.getILoggerFactory()); + + Logger logger = (Logger) LoggerFactory.getLogger("org.springframework.context"); + logger.setLevel(Level.INFO); + logger.addAppender(memoryAppender); + memoryAppender.start(); + } + + @Test + public void givenAutowireInBeanPostProcessor_whenSpringContextInitialize_thenNotEligibleLogShouldShowAndGroupFieldNotPopulated() { + List notEligibleEvents = memoryAppender.search("Bean 'randomIntGenerator' of type [com.baeldung.autoproxying.RandomIntGenerator] " + + "is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)"); + + assertEquals(1, notEligibleEvents.size()); + assertEquals(0, dataCache.getGroup()); + } +} diff --git a/spring-ejb/ejb-beans/pom.xml b/spring-ejb/ejb-beans/pom.xml index d7f875acd0..8f2bf31ee4 100644 --- a/spring-ejb/ejb-beans/pom.xml +++ b/spring-ejb/ejb-beans/pom.xml @@ -184,7 +184,6 @@ 5.10.2 5.13.1 2.21.0 - 1.8.5 2.8 8.2.1.Final diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index 096ffb9c3f..bb2702fc9d 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -14,33 +14,34 @@ - spring-ldap spring-5-security spring-5-security-cognito spring-5-security-oauth + spring-ldap spring-security-acl spring-security-auth0 - spring-security-web-angular/server spring-security-config spring-security-core - spring-security-web-mvc - spring-security-web-boot-1 - spring-security-web-boot-2 - spring-security-web-mvc-custom - spring-security-web-digest-auth spring-security-ldap - spring-security-web-login - spring-security-web-persisted-remember-me - spring-security-web-sockets spring-security-legacy-oidc + spring-security-oauth2-sso spring-security-oidc spring-security-okta spring-security-saml + spring-security-web-angular/server + spring-security-web-boot-1 + spring-security-web-boot-2 + spring-security-web-boot-3 + spring-security-web-digest-auth + spring-security-web-login + spring-security-web-mvc-custom + spring-security-web-mvc + spring-security-web-persisted-remember-me spring-security-web-react - spring-security-web-rest spring-security-web-rest-basic-auth spring-security-web-rest-custom - spring-security-oauth2-sso + spring-security-web-rest + spring-security-web-sockets spring-security-web-thymeleaf spring-security-web-x509 spring-session diff --git a/spring-security-modules/spring-5-security/src/test/java/com/baeldung/xss/PersonControllerUnitTest.java b/spring-security-modules/spring-5-security/src/test/java/com/baeldung/xss/PersonControllerIntegrationTest.java similarity index 98% rename from spring-security-modules/spring-5-security/src/test/java/com/baeldung/xss/PersonControllerUnitTest.java rename to spring-security-modules/spring-5-security/src/test/java/com/baeldung/xss/PersonControllerIntegrationTest.java index 4e278ebf16..5afa3bc1dd 100644 --- a/spring-security-modules/spring-5-security/src/test/java/com/baeldung/xss/PersonControllerUnitTest.java +++ b/spring-security-modules/spring-5-security/src/test/java/com/baeldung/xss/PersonControllerIntegrationTest.java @@ -14,7 +14,7 @@ import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -class PersonControllerUnitTest { +class PersonControllerIntegrationTest { @LocalServerPort int randomServerPort; diff --git a/spring-security-modules/spring-security-web-angular/server/pom.xml b/spring-security-modules/spring-security-web-angular/server/pom.xml index 19d980062c..07d5d44e8d 100644 --- a/spring-security-modules/spring-security-web-angular/server/pom.xml +++ b/spring-security-modules/spring-security-web-angular/server/pom.xml @@ -62,9 +62,4 @@ - - UTF-8 - UTF-8 - - diff --git a/spring-security-modules/spring-security-web-boot-3/README.md b/spring-security-modules/spring-security-web-boot-3/README.md new file mode 100644 index 0000000000..0e962273c5 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/README.md @@ -0,0 +1,11 @@ +## Spring Boot Security MVC + +This module contains articles about Spring Security with Spring MVC in Boot applications + +### The Course +The "REST With Spring" Classes: http://github.learnspringsecurity.com + +### Relevant Articles: + +- [TLS Setup in Spring](https://www.baeldung.com/) +- More articles: [[<-- prev]](/spring-security-modules/spring-security-web-boot-2) diff --git a/spring-security-modules/spring-security-web-boot-3/pom.xml b/spring-security-modules/spring-security-web-boot-3/pom.xml new file mode 100644 index 0000000000..a6e2b48d75 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + spring-security-web-boot-3 + 0.0.1-SNAPSHOT + spring-security-web-boot-3 + jar + Spring Security MVC Boot - 3 + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + + diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/tls/HomeController.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/tls/HomeController.java new file mode 100644 index 0000000000..c72821cc9b --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/tls/HomeController.java @@ -0,0 +1,16 @@ +package com.baeldung.tls; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class HomeController { + + @GetMapping("/baeldung") + public ResponseEntity welcome() { + return new ResponseEntity<>("tls/baeldung", HttpStatus.OK); + } + +} diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/tls/SecurityConfig.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/tls/SecurityConfig.java new file mode 100644 index 0000000000..63b59b8cc8 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/tls/SecurityConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.tls; + +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; + +@EnableWebSecurity +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/**") + .permitAll(); + } +} diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/tls/TLSEnabledApplication.java b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/tls/TLSEnabledApplication.java new file mode 100644 index 0000000000..62ba77d769 --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/src/main/java/com/baeldung/tls/TLSEnabledApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.tls; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.PropertySource; + +@SpringBootApplication +public class TLSEnabledApplication { + + public static void main(String... args) { + SpringApplication application = new SpringApplication(TLSEnabledApplication.class); + application.setAdditionalProfiles("tls"); + application.run(args); + } +} diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/resources/application-tls.properties b/spring-security-modules/spring-security-web-boot-3/src/main/resources/application-tls.properties new file mode 100644 index 0000000000..002d702eab --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/src/main/resources/application-tls.properties @@ -0,0 +1,23 @@ + +server.port=8443 + +# enable/disable https +server.ssl.enabled=true +# keystore format +server.ssl.key-store-type=PKCS12 +# keystore location +server.ssl.key-store=classpath:keystore/keystore.p12 +# keystore password +server.ssl.key-store-password=changeit +server.ssl.key-alias=baeldung +# SSL protocol to use +server.ssl.protocol=TLS +# Enabled SSL protocols +server.ssl.enabled-protocols=TLSv1.2 + +#server.ssl.client-auth=need + +#trust store location +#server.ssl.trust-store=classpath:keystore/truststore.p12 +#trust store password +#server.ssl.trust-store-password=changeit \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/resources/keystore/baeldung.cer b/spring-security-modules/spring-security-web-boot-3/src/main/resources/keystore/baeldung.cer new file mode 100644 index 0000000000..1a6bb4d49b --- /dev/null +++ b/spring-security-modules/spring-security-web-boot-3/src/main/resources/keystore/baeldung.cer @@ -0,0 +1,28 @@ +-----BEGIN CERTIFICATE----- +MIIExzCCAq+gAwIBAgIEbh/WszANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDEwls +b2NhbGhvc3QwHhcNMjEwMzIxMDgzMzU3WhcNMzEwMzE5MDgzMzU3WjAUMRIwEAYD +VQQDEwlsb2NhbGhvc3QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCD +QWvAEewDE+vFFqYPgXFJ94bMgPZT6qdb17DkWWbL2jV5QENbSYTLAPNQ1TGUgKhj +t1LCHpooLwWIo6xvhK/qZYjh3YonSIe8Eo0fBCDoZpLO+Vp0us22NBgLOYH8hvAm +zEvPXdSZo5Qkeaqjwd6kB/z083y8OL+Civ0ARXoLsn7CFslKfZp2o/aebH6i/T+3 +hWVqasIIMtfNUrxE/pnOnV8aSAt24jcm/VxbtheqIzmcOPlCXSP1RAmFez6tJsNu +2dbUhaeOf95RCaM6a43soEvLvooGa/uqBPsRojg5WEFGf7Tc7pzB+BtALwRmHAqr +hiYjVv329QGZ+g8dADBvvqvGpGysy+X0LxixvIP14KdCqG8uMYmw5cBTJHc23AHV +iP+JsfDtdu+bzZeOZmhSsv4M3DZ1QPHEX+zCnotE+SeycqEr+3SaJELyjCB1twFT +pCRCQGWFKYCRwhjQ1vGY7qhD6ZDn30a96xAlPS+T35pA01rNgORJi8j9sf3oiwEe +oPQOecgFHdua5drHJ78j7MUz/Gvj02GnwKnBKbMYDGeBKJWm0ir4MxoU7HPaDwLj +jofXgIz+CMXkp+9arVu5IsZwL2MKNZ4fiM+VWZg9R73CAVpKvs6dTlQXe++DCaOr +XGiQeCPPpIC74vqWhAHuzPncGJndHlmXYGLhi0sk0wIDAQABoyEwHzAdBgNVHQ4E +FgQUhW4a3uWREJoTxodyD5u7i7mCaacwDQYJKoZIhvcNAQELBQADggIBAD/Qfkot +qklQr4r7eoHtyFCGozfZvsPwEediZORkycU/fCZozdVh95ebt2/N/jw7RlNhv+t+ +HahMoiXbLX2RUrqM/2X5U7BbxIpy3XjhcEYTJudqFfCxDQfxD1bFrWHygQzAanOb +sPHkcEt3tu2suV2YsJpHry/1BMo83WAoTgw/3dFtJ7oEoi/LaI03v9Qlp0+hLfA5 +zwyuuRqFn24FRvdWHX5GqAweF+WUdmmlkiJiKu2RtQsPoN7ITvZQs9t4l0zZ8w2v +QV0YdhWYLkS3g53oyOP8T5YlCFGuUOyo433hRyrzaxj3aFDkMbNrX9REB9v8Iz7X +aFsmLDJsfT5Spovz68HCIMDW1Sl1WqVkNN2V3Rwt72bn7DEbKZzGW9RC5eXEW1Zw +46XeYOVdEjzl/l623moWC5ZTlwPF1qRDaoZXT/1d1eAJE8ZBHm1YjwgDD5aFvylG +0OT1qWD5gx3nOmAbBk1e3r8ESMo9k29/4hycUUUgtFuWtBwBaY/O/4YoLx59wbpL +rFR/zjKIdYFj0AM2ABTgrG7v5pEhjLTnzjc+mZV7hJCBvB+bbC5vvfDg0K7lQUpJ +ruIPvqKfJyuTwkKmoTF5jmG04jwUDtA5iGUB3U3QiQ8zcbTiVRptXLEQDYw/bzDk +0fd4xTbok1ygI7wJ/KRyMvFXdbTKSvVu/tnM +-----END CERTIFICATE----- diff --git a/spring-security-modules/spring-security-web-boot-3/src/main/resources/keystore/keystore.p12 b/spring-security-modules/spring-security-web-boot-3/src/main/resources/keystore/keystore.p12 new file mode 100644 index 0000000000..6f0d9c508c Binary files /dev/null and b/spring-security-modules/spring-security-web-boot-3/src/main/resources/keystore/keystore.p12 differ diff --git a/spring-web-modules/pom.xml b/spring-web-modules/pom.xml index 37ee84da25..ca96dcff35 100644 --- a/spring-web-modules/pom.xml +++ b/spring-web-modules/pom.xml @@ -41,6 +41,7 @@ spring-thymeleaf spring-thymeleaf-2 spring-thymeleaf-3 + spring-boot-jsp diff --git a/spring-web-modules/spring-boot-jsp/pom.xml b/spring-web-modules/spring-boot-jsp/pom.xml new file mode 100644 index 0000000000..d646b6058a --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/pom.xml @@ -0,0 +1,91 @@ + + + 4.0.0 + spring-boot-jsp + 0.0.1-SNAPSHOT + spring-boot-jsp + war + + + com.baeldung + spring-web-modules + 0.0.1-SNAPSHOT + + + + + + org.springframework.boot + spring-boot-dependencies + ${spring-boot.version} + pom + import + + + + + + + javax.servlet + jstl + ${jstl.version} + + + org.apache.tomcat.embed + tomcat-embed-jasper + + + + + org.projectlombok + lombok + ${lombok.version} + provided + + + org.springframework.boot + spring-boot-starter-web + + + + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + spring-boot-jsp + + + org.springframework.boot + spring-boot-maven-plugin + ${spring-boot.version} + + com.baeldung.boot.jsp.SpringBootJspApplication + + + + + repackage + + + + + + + + + 1.2 + 5.7.1 + 2.4.4 + + + \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/SpringBootJspApplication.java b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/SpringBootJspApplication.java new file mode 100644 index 0000000000..c77554f9f6 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/SpringBootJspApplication.java @@ -0,0 +1,19 @@ +package com.baeldung.boot.jsp; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +@SpringBootApplication(scanBasePackages = "com.baeldung.boot.jsp") +public class SpringBootJspApplication extends SpringBootServletInitializer { + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return builder.sources(SpringBootJspApplication.class); + } + + public static void main(String[] args) { + SpringApplication.run(SpringBootJspApplication.class); + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/SpringBootJspConfiguration.java b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/SpringBootJspConfiguration.java new file mode 100644 index 0000000000..7fdae2c2a6 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/SpringBootJspConfiguration.java @@ -0,0 +1,29 @@ +package com.baeldung.boot.jsp; + +import java.util.HashMap; +import java.util.Map; + +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.baeldung.boot.jsp.repository.BookRepository; +import com.baeldung.boot.jsp.repository.impl.InMemoryBookRepository; +import com.baeldung.boot.jsp.repository.model.BookData; + +@Configuration +public class SpringBootJspConfiguration { + + @Bean + public BookRepository provideBookRepository() { + return new InMemoryBookRepository(initialBookData()); + } + + private static Map initialBookData() { + Map initData = new HashMap<>(); + initData.put("ISBN-1", new BookData("ISBN-1", "Book 1", "Book 1 Author")); + initData.put("ISBN-2", new BookData("ISBN-2", "Book 2", "Book 2 Author")); + initData.put("ISBN-3", new BookData("ISBN-3", "Book 3", "Book 3 Author")); + return initData; + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/controller/BookController.java b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/controller/BookController.java new file mode 100644 index 0000000000..c104a9cad3 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/controller/BookController.java @@ -0,0 +1,45 @@ +package com.baeldung.boot.jsp.controller; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.ModelAttribute; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.mvc.support.RedirectAttributes; +import org.springframework.web.servlet.view.RedirectView; + +import com.baeldung.boot.jsp.dto.Book; +import com.baeldung.boot.jsp.service.BookService; + +@Controller +@RequestMapping("/book") +public class BookController { + + private final BookService bookService; + + public BookController(BookService bookService) { + this.bookService = bookService; + } + + @GetMapping("/viewBooks") + public String viewBooks(Model model) { + model.addAttribute("books", bookService.getBooks()); + return "view-books"; + } + + @GetMapping("/addBook") + public String addBookView(Model model) { + model.addAttribute("book", new Book()); + return "add-book"; + } + + @PostMapping("/addBook") + public RedirectView addBook(@ModelAttribute("book") Book book, RedirectAttributes redirectAttributes) { + final RedirectView redirectView = new RedirectView("/book/addBook", true); + Book savedBook = bookService.addBook(book); + redirectAttributes.addFlashAttribute("savedBook", savedBook); + redirectAttributes.addFlashAttribute("addBookSuccess", true); + return redirectView; + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/dto/Book.java b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/dto/Book.java new file mode 100644 index 0000000000..f4cd6b0b3b --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/dto/Book.java @@ -0,0 +1,14 @@ +package com.baeldung.boot.jsp.dto; + +import lombok.*; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@ToString +public class Book { + private String isbn; + private String name; + private String author; +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/exception/DuplicateBookException.java b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/exception/DuplicateBookException.java new file mode 100644 index 0000000000..bd52a591e3 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/exception/DuplicateBookException.java @@ -0,0 +1,13 @@ +package com.baeldung.boot.jsp.exception; + +import com.baeldung.boot.jsp.dto.Book; +import lombok.Getter; + +@Getter +public class DuplicateBookException extends RuntimeException { + private final Book book; + + public DuplicateBookException(Book book) { + this.book = book; + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/exception/LibraryControllerAdvice.java b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/exception/LibraryControllerAdvice.java new file mode 100644 index 0000000000..8217fea2e3 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/exception/LibraryControllerAdvice.java @@ -0,0 +1,19 @@ +package com.baeldung.boot.jsp.exception; + +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.servlet.ModelAndView; + +@ControllerAdvice +public class LibraryControllerAdvice { + + @ExceptionHandler(value = DuplicateBookException.class) + public ModelAndView duplicateBookException(DuplicateBookException e) { + final ModelAndView modelAndView = new ModelAndView(); + modelAndView.addObject("ref", e.getBook().getIsbn()); + modelAndView.addObject("object", e.getBook()); + modelAndView.addObject("message", "Cannot add an already existing book"); + modelAndView.setViewName("error-book"); + return modelAndView; + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/repository/BookRepository.java b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/repository/BookRepository.java new file mode 100644 index 0000000000..f10cecfa81 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/repository/BookRepository.java @@ -0,0 +1,14 @@ +package com.baeldung.boot.jsp.repository; + +import java.util.Collection; +import java.util.Optional; + +import com.baeldung.boot.jsp.repository.model.BookData; + +public interface BookRepository { + Collection findAll(); + + Optional findById(String isbn); + + BookData add(BookData book); +} diff --git a/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/repository/impl/InMemoryBookRepository.java b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/repository/impl/InMemoryBookRepository.java new file mode 100644 index 0000000000..8fae303158 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/repository/impl/InMemoryBookRepository.java @@ -0,0 +1,36 @@ +package com.baeldung.boot.jsp.repository.impl; + +import java.util.*; + +import com.baeldung.boot.jsp.repository.BookRepository; +import com.baeldung.boot.jsp.repository.model.BookData; + +public class InMemoryBookRepository implements BookRepository { + + private final Map storedBooks; + + public InMemoryBookRepository(Map storedBooks) { + this.storedBooks = new HashMap<>(); + this.storedBooks.putAll(storedBooks); + } + + @Override + public Collection findAll() { + if (storedBooks.isEmpty()) { + return Collections.emptyList(); + } + + return storedBooks.values(); + } + + @Override + public Optional findById(String isbn) { + return Optional.ofNullable(storedBooks.get(isbn)); + } + + @Override + public BookData add(BookData book) { + storedBooks.put(book.getIsbn(), book); + return book; + } +} diff --git a/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/repository/model/BookData.java b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/repository/model/BookData.java new file mode 100644 index 0000000000..7c722a92e5 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/repository/model/BookData.java @@ -0,0 +1,16 @@ +package com.baeldung.boot.jsp.repository.model; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +public class BookData { + private String isbn; + private String name; + private String author; +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/service/BookService.java b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/service/BookService.java new file mode 100644 index 0000000000..7c2c401ef2 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/service/BookService.java @@ -0,0 +1,11 @@ +package com.baeldung.boot.jsp.service; + +import java.util.Collection; + +import com.baeldung.boot.jsp.dto.Book; + +public interface BookService { + Collection getBooks(); + + Book addBook(Book book); +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/service/impl/BookServiceImpl.java b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/service/impl/BookServiceImpl.java new file mode 100644 index 0000000000..519ee19205 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/java/com/baeldung/boot/jsp/service/impl/BookServiceImpl.java @@ -0,0 +1,50 @@ +package com.baeldung.boot.jsp.service.impl; + +import java.util.Collection; +import java.util.Optional; +import java.util.stream.Collectors; + +import com.baeldung.boot.jsp.exception.DuplicateBookException; +import org.springframework.stereotype.Service; + +import com.baeldung.boot.jsp.dto.Book; +import com.baeldung.boot.jsp.repository.BookRepository; +import com.baeldung.boot.jsp.repository.model.BookData; +import com.baeldung.boot.jsp.service.BookService; + +@Service +public class BookServiceImpl implements BookService { + + private final BookRepository bookRepository; + + public BookServiceImpl(BookRepository bookRepository) { + this.bookRepository = bookRepository; + } + + @Override + public Collection getBooks() { + return bookRepository.findAll() + .stream() + .map(BookServiceImpl::convertBookData) + .collect(Collectors.toList()); + } + + @Override + public Book addBook(Book book) { + final Optional existingBook = bookRepository.findById(book.getIsbn()); + if (existingBook.isPresent()) { + throw new DuplicateBookException(book); + } + + final BookData savedBook = bookRepository.add(convertBook(book)); + return convertBookData(savedBook); + } + + private static Book convertBookData(BookData bookData) { + return new Book(bookData.getIsbn(), bookData.getName(), bookData.getAuthor()); + } + + private static BookData convertBook(Book book) { + return new BookData(book.getIsbn(), book.getName(), book.getAuthor()); + } +} diff --git a/spring-web-modules/spring-boot-jsp/src/main/resources/application.properties b/spring-web-modules/spring-boot-jsp/src/main/resources/application.properties new file mode 100644 index 0000000000..56638f8c1a --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/resources/application.properties @@ -0,0 +1,4 @@ +server.servlet.context-path=/spring-boot-jsp + +spring.mvc.view.prefix: /WEB-INF/jsp/ +spring.mvc.view.suffix: .jsp \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/resources/static/css/common.css b/spring-web-modules/spring-boot-jsp/src/main/resources/static/css/common.css new file mode 100644 index 0000000000..a32d81c6a2 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/resources/static/css/common.css @@ -0,0 +1,10 @@ +table { + font-family: arial, sans-serif; + border-collapse: collapse; +} + +td, th { + border: 1px solid #dddddd; + text-align: left; + padding: 8px; +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/resources/static/error/4xx.html b/spring-web-modules/spring-boot-jsp/src/main/resources/static/error/4xx.html new file mode 100644 index 0000000000..c27bd8bb7a --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/resources/static/error/4xx.html @@ -0,0 +1,10 @@ + + + + + Error + + +Opps! 4xx Error Occurred. + + \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/webapp/WEB-INF/jsp/add-book.jsp b/spring-web-modules/spring-boot-jsp/src/main/webapp/WEB-INF/jsp/add-book.jsp new file mode 100644 index 0000000000..8195743da8 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/webapp/WEB-INF/jsp/add-book.jsp @@ -0,0 +1,21 @@ +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> +<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Add Book + + + +
Successfully added Book with ISBN: ${savedBook.isbn}
+
+ + + + ISBN: + Book Name: + Author Name: + + + + \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/main/webapp/WEB-INF/jsp/error-book.jsp b/spring-web-modules/spring-boot-jsp/src/main/webapp/WEB-INF/jsp/error-book.jsp new file mode 100644 index 0000000000..6db90ca5c7 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/webapp/WEB-INF/jsp/error-book.jsp @@ -0,0 +1,18 @@ +<%-- + Created by IntelliJ IDEA. + User: jason + Date: 3/13/21 + Time: 10:39 PM + To change this template use File | Settings | File Templates. +--%> +<%@ page contentType="text/html;charset=UTF-8" language="java" %> + + + Error + + +

Reference: ${ref}

+

Error Message: ${message}

+

Object: ${object}

+ + diff --git a/spring-web-modules/spring-boot-jsp/src/main/webapp/WEB-INF/jsp/view-books.jsp b/spring-web-modules/spring-boot-jsp/src/main/webapp/WEB-INF/jsp/view-books.jsp new file mode 100644 index 0000000000..4a8e00a69b --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/main/webapp/WEB-INF/jsp/view-books.jsp @@ -0,0 +1,28 @@ +<%@ page contentType="text/html;charset=UTF-8" language="java" %> +<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> + + + View Books + " rel="stylesheet" type="text/css"> + + + + + + + + + + + + + + + + + + + +
ISBNNameAuthor
${book.isbn}${book.name}${book.author}
+ + \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/controller/BookControllerIntegrationTest.java b/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/controller/BookControllerIntegrationTest.java new file mode 100644 index 0000000000..1847cbf545 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/controller/BookControllerIntegrationTest.java @@ -0,0 +1,93 @@ +package com.baeldung.boot.jsp.controller; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.hasProperty; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; + +import java.util.Collections; +import java.util.Optional; + +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.MediaType; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import com.baeldung.boot.jsp.repository.BookRepository; +import com.baeldung.boot.jsp.repository.impl.InMemoryBookRepository; +import com.baeldung.boot.jsp.repository.model.BookData; + +@ExtendWith(SpringExtension.class) +@WebAppConfiguration +@ContextConfiguration +@AutoConfigureMockMvc +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class BookControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @Autowired + private BookRepository bookRepository; + + @Test + @Order(1) + public void whenAddBook_thenBookSaved() throws Exception { + MockHttpServletRequestBuilder addBookRequest = MockMvcRequestBuilders.post("/book/addBook") + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .param("isbn", "isbn1") + .param("name", "name1") + .param("author", "author1"); + mockMvc.perform(addBookRequest) + .andReturn(); + + Optional storedBookOpt = bookRepository.findById("isbn1"); + assertTrue(storedBookOpt.isPresent()); + assertEquals("name1", storedBookOpt.get() + .getName()); + assertEquals("author1", storedBookOpt.get() + .getAuthor()); + } + + @Test + @Order(2) + public void givenAlreadyExistingBook_whenAddBook_thenShowErrorPage() throws Exception { + MockHttpServletRequestBuilder addBookRequest = MockMvcRequestBuilders.post("/book/addBook") + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .param("isbn", "isbn1") + .param("name", "name1") + .param("author", "author1"); + ResultActions addBookResult = mockMvc.perform(addBookRequest); + + addBookResult.andExpect(view().name("error-book")) + .andExpect(model().attribute("ref", "isbn1")) + .andExpect(model().attribute("object", hasProperty("isbn", equalTo("isbn1")))) + .andExpect(model().attribute("message", "Cannot add an already existing book")); + } + + @Configuration + @ComponentScan("com.baeldung.boot.jsp") + static class ContextConfiguration { + + @Bean + public BookRepository provideBookRepository() { + return new InMemoryBookRepository(Collections.emptyMap()); + } + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/controller/BookControllerUnitTest.java b/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/controller/BookControllerUnitTest.java new file mode 100644 index 0000000000..af1d3d4956 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/controller/BookControllerUnitTest.java @@ -0,0 +1,76 @@ +package com.baeldung.boot.jsp.controller; + +import static org.hamcrest.Matchers.*; +import static org.mockito.ArgumentMatchers.any; +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.*; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.mockito.AdditionalAnswers; +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.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import com.baeldung.boot.jsp.dto.Book; +import com.baeldung.boot.jsp.service.BookService; + +@WebMvcTest(BookController.class) +class BookControllerUnitTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private BookService bookService; + + @Test + public void whenViewBooks_thenReturnBooksView() throws Exception { + when(bookService.getBooks()).thenReturn(existingBooks()); + ResultActions viewBooksResult = mockMvc.perform(get("/book/viewBooks")); + + viewBooksResult.andExpect(view().name("view-books")) + .andExpect(model().attribute("books", hasSize(3))); + } + + @Test + public void whenAddBookView_thenReturnAddBooksView() throws Exception { + ResultActions addBookViewResult = mockMvc.perform(get("/book/addBook")); + + addBookViewResult.andExpect(view().name("add-book")) + .andExpect(model().attribute("book", isA(Book.class))); + } + + @Test + public void whenAddBookPost_thenRedirectToAddBookView() throws Exception { + when(bookService.addBook(any(Book.class))).thenAnswer(AdditionalAnswers.returnsFirstArg()); + MockHttpServletRequestBuilder addBookRequest = MockMvcRequestBuilders.post("/book/addBook") + .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) + .param("isbn", "isbn1") + .param("name", "name1") + .param("author", "author1"); + ResultActions addBookResult = mockMvc.perform(addBookRequest); + + addBookResult.andExpect(status().is3xxRedirection()) + .andExpect(redirectedUrl("/book/addBook")) + .andExpect(flash().attribute("savedBook", hasProperty("isbn", equalTo("isbn1")))) + .andExpect(flash().attribute("addBookSuccess", true)); + } + + private static Collection existingBooks() { + List books = new ArrayList<>(); + books.add(new Book("isbn1", "name1", "author1")); + books.add(new Book("isbn2", "name2", "author2")); + books.add(new Book("isbn3", "name3", "author3")); + return books; + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/repository/impl/InMemoryBookRepositoryUnitTest.java b/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/repository/impl/InMemoryBookRepositoryUnitTest.java new file mode 100644 index 0000000000..83f0c19e26 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/repository/impl/InMemoryBookRepositoryUnitTest.java @@ -0,0 +1,62 @@ +package com.baeldung.boot.jsp.repository.impl; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.*; + +import org.junit.jupiter.api.Test; + +import com.baeldung.boot.jsp.repository.BookRepository; +import com.baeldung.boot.jsp.repository.model.BookData; + +public class InMemoryBookRepositoryUnitTest { + + @Test + public void givenEmtpyData_whenFindAll_thenReturnEmptyCollection() { + BookRepository bookRepository = new InMemoryBookRepository(Collections.emptyMap()); + Collection storedBooks = bookRepository.findAll(); + + assertEquals(0, storedBooks.size()); + } + + @Test + public void givenInitialData_whenFindAll_thenReturnInitialData() { + BookRepository bookRepository = new InMemoryBookRepository(initialBookData()); + Collection storedBooks = bookRepository.findAll(); + + assertEquals(3, storedBooks.size()); + } + + @Test + public void givenInitialData_whenFindUnavailableIsbn_thenReturnEmpty() { + BookRepository bookRepository = new InMemoryBookRepository(initialBookData()); + Optional storedBookOpt = bookRepository.findById("isbn4"); + + assertFalse(storedBookOpt.isPresent()); + } + + @Test + public void givenInitialData_whenFindAvailableIsbn_thenReturnItem() { + BookRepository bookRepository = new InMemoryBookRepository(initialBookData()); + Optional storedBookOpt = bookRepository.findById("isbn1"); + + assertTrue(storedBookOpt.isPresent()); + } + + @Test + public void givenAddedIsbn_whenFindAvailableIsbn_thenReturnItem() { + BookRepository bookRepository = new InMemoryBookRepository(Collections.emptyMap()); + bookRepository.add(new BookData("isbn4", "name4", "author4")); + Optional storedBookOpt = bookRepository.findById("isbn4"); + + assertTrue(storedBookOpt.isPresent()); + } + + private static Map initialBookData() { + Map initData = new HashMap<>(); + initData.put("isbn1", new BookData("isbn1", "name1", "author1")); + initData.put("isbn2", new BookData("isbn2", "name2", "author2")); + initData.put("isbn3", new BookData("isbn3", "name3", "author3")); + return initData; + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/service/BookServiceIntegrationTest.java b/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/service/BookServiceIntegrationTest.java new file mode 100644 index 0000000000..4223f3f970 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/service/BookServiceIntegrationTest.java @@ -0,0 +1,84 @@ +package com.baeldung.boot.jsp.service; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.boot.jsp.dto.Book; +import com.baeldung.boot.jsp.exception.DuplicateBookException; +import com.baeldung.boot.jsp.repository.BookRepository; +import com.baeldung.boot.jsp.repository.impl.InMemoryBookRepository; +import com.baeldung.boot.jsp.repository.model.BookData; + +@ExtendWith(SpringExtension.class) +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@ContextConfiguration(loader = AnnotationConfigContextLoader.class) +public class BookServiceIntegrationTest { + + @Autowired + private BookService bookService; + + @Test + @Order(1) + public void givenNoAddedBooks_whenGetAllBooks_thenReturnInitialBooks() { + Collection storedBooks = bookService.getBooks(); + + assertEquals(3, storedBooks.size()); + assertThat(storedBooks, hasItem(hasProperty("isbn", equalTo("ISBN-TEST-1")))); + assertThat(storedBooks, hasItem(hasProperty("isbn", equalTo("ISBN-TEST-2")))); + assertThat(storedBooks, hasItem(hasProperty("isbn", equalTo("ISBN-TEST-3")))); + } + + @Test + @Order(2) + public void givenBookNotAlreadyExists_whenAddBook_thenReturnSuccessfully() { + Book bookToBeAdded = new Book("ISBN-ADD-TEST-4", "Added Book 4", "Added Book 4 Author"); + Book storedBook = bookService.addBook(bookToBeAdded); + + assertEquals(bookToBeAdded.getIsbn(), storedBook.getIsbn()); + } + + @Test + @Order(3) + public void givenBookAlreadyExists_whenAddBook_thenDuplicateBookException() { + Book bookToBeAdded = new Book("ISBN-ADD-TEST-4", "Updated Book 4", "Updated Book 4 Author"); + + assertThrows(DuplicateBookException.class, () -> bookService.addBook(bookToBeAdded)); + } + + @Configuration + @ComponentScan("com.baeldung.boot.jsp") + static class ContextConfiguration { + + @Bean + public BookRepository provideBookRepository() { + return new InMemoryBookRepository(initialBookData()); + } + + private static Map initialBookData() { + Map initData = new HashMap<>(); + initData.put("ISBN-TEST-1", new BookData("ISBN-TEST-1", "Book 1", "Book 1 Author")); + initData.put("ISBN-TEST-2", new BookData("ISBN-TEST-2", "Book 2", "Book 2 Author")); + initData.put("ISBN-TEST-3", new BookData("ISBN-TEST-3", "Book 3", "Book 3 Author")); + return initData; + } + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/service/impl/BookServiceImplUnitTest.java b/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/service/impl/BookServiceImplUnitTest.java new file mode 100644 index 0000000000..defbf71fd9 --- /dev/null +++ b/spring-web-modules/spring-boot-jsp/src/test/java/com/baeldung/boot/jsp/service/impl/BookServiceImplUnitTest.java @@ -0,0 +1,75 @@ +package com.baeldung.boot.jsp.service.impl; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.AdditionalAnswers; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import com.baeldung.boot.jsp.dto.Book; +import com.baeldung.boot.jsp.exception.DuplicateBookException; +import com.baeldung.boot.jsp.repository.BookRepository; +import com.baeldung.boot.jsp.repository.model.BookData; +import com.baeldung.boot.jsp.service.BookService; + +@ExtendWith(MockitoExtension.class) +public class BookServiceImplUnitTest { + + @Mock + private BookRepository bookRepository; + + @Test + public void whenGetBooks_thenAllBooksReturned() { + when(bookRepository.findAll()).thenReturn(existingBooks()); + BookService bookService = new BookServiceImpl(bookRepository); + + Collection storedBooks = bookService.getBooks(); + assertEquals(3, storedBooks.size()); + assertThat(storedBooks, hasItem(hasProperty("isbn", equalTo("isbn1")))); + assertThat(storedBooks, hasItem(hasProperty("isbn", equalTo("isbn2")))); + assertThat(storedBooks, hasItem(hasProperty("isbn", equalTo("isbn3")))); + } + + @Test + public void whenAddBook_thenAddSuccessful() { + when(bookRepository.findById(anyString())).thenReturn(Optional.empty()); + when(bookRepository.add(any(BookData.class))).thenAnswer(AdditionalAnswers.returnsFirstArg()); + BookService bookService = new BookServiceImpl(bookRepository); + Book book = bookService.addBook(new Book("isbn1", "name1", "author1")); + + assertEquals("isbn1", book.getIsbn()); + assertEquals("name1", book.getName()); + assertEquals("author1", book.getAuthor()); + } + + @Test + public void givenBookAlreadyExist_whenAddBook_thenDuplicateBookException() { + BookData existingBook = new BookData("isbn1", "name1", "author1"); + when(bookRepository.findById("isbn1")).thenReturn(Optional.of(existingBook)); + BookService bookService = new BookServiceImpl(bookRepository); + Book bookToBeAdded = new Book("isbn1", "name1", "author1"); + + assertThrows(DuplicateBookException.class, () -> bookService.addBook(bookToBeAdded)); + } + + private static Collection existingBooks() { + List books = new ArrayList<>(); + books.add(new BookData("isbn1", "name1", "author1")); + books.add(new BookData("isbn2", "name2", "author2")); + books.add(new BookData("isbn3", "name3", "author3")); + return books; + } +} \ No newline at end of file diff --git a/spring-web-modules/spring-mvc-basics-2/pom.xml b/spring-web-modules/spring-mvc-basics-2/pom.xml index 0b4515994b..adc42d8db8 100644 --- a/spring-web-modules/spring-mvc-basics-2/pom.xml +++ b/spring-web-modules/spring-mvc-basics-2/pom.xml @@ -131,14 +131,6 @@ json ${json.version} - - org.apache.maven.surefire - surefire-logger-api - ${maven-surefire-plugin.version} - - test - true - @@ -163,7 +155,6 @@ 1.8 1.8 - 2.21.0 2.3.2-b02 4.0.0 6.0.10.Final diff --git a/spring-web-modules/spring-mvc-basics/src/main/resources/application.properties b/spring-web-modules/spring-mvc-basics/src/main/resources/application.properties index cf26fbfb60..b8a9be0b40 100644 --- a/spring-web-modules/spring-mvc-basics/src/main/resources/application.properties +++ b/spring-web-modules/spring-mvc-basics/src/main/resources/application.properties @@ -5,6 +5,3 @@ spring.mvc.pathmatch.use-suffix-pattern=true #spring.mvc.contentnegotiation.favor-path-extension=true #spring.mvc.contentnegotiation.favor-parameter=true #spring.mvc.contentnegotiation.parameter-name=mediaType - -# https://github.com/spring-projects/spring-boot/issues/24207 -spring.main.allow-bean-definition-overriding=true diff --git a/spring-web-modules/spring-mvc-views/pom.xml b/spring-web-modules/spring-mvc-views/pom.xml index 2e80a60966..649814263c 100644 --- a/spring-web-modules/spring-mvc-views/pom.xml +++ b/spring-web-modules/spring-mvc-views/pom.xml @@ -111,7 +111,6 @@ - 1.8 2.3.3 4.0.1 5.2.1.RELEASE diff --git a/spring-web-modules/spring-rest-http-2/pom.xml b/spring-web-modules/spring-rest-http-2/pom.xml index 0ea3fd6840..a349ac1116 100644 --- a/spring-web-modules/spring-rest-http-2/pom.xml +++ b/spring-web-modules/spring-rest-http-2/pom.xml @@ -44,12 +44,13 @@ io.github.resilience4j resilience4j-timelimiter - 1.6.1 + ${resilience4j.version} 2.9.2 + 1.6.1 diff --git a/testing-modules/junit-5-advanced/pom.xml b/testing-modules/junit-5-advanced/pom.xml index 4756223c3d..f53af9347f 100644 --- a/testing-modules/junit-5-advanced/pom.xml +++ b/testing-modules/junit-5-advanced/pom.xml @@ -35,18 +35,8 @@ - - - - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - - 5.4.2 - 2.21.0 5.4.2 diff --git a/testing-modules/junit-5-basics/pom.xml b/testing-modules/junit-5-basics/pom.xml index b9c9635dc4..cdb0c367ce 100644 --- a/testing-modules/junit-5-basics/pom.xml +++ b/testing-modules/junit-5-basics/pom.xml @@ -152,7 +152,6 @@ 1.2.0 5.4.2 5.0.6.RELEASE - 2.21.0 diff --git a/testing-modules/junit-5/pom.xml b/testing-modules/junit-5/pom.xml index 831fa97e12..ded3e9e26d 100644 --- a/testing-modules/junit-5/pom.xml +++ b/testing-modules/junit-5/pom.xml @@ -105,10 +105,6 @@ - - maven-surefire-plugin - ${maven-surefire-plugin.version} - org.codehaus.mojo exec-maven-plugin diff --git a/testing-modules/junit5-migration/pom.xml b/testing-modules/junit5-migration/pom.xml index 3b2663d81d..e3ef21f506 100644 --- a/testing-modules/junit5-migration/pom.xml +++ b/testing-modules/junit5-migration/pom.xml @@ -18,12 +18,12 @@ org.junit.platform junit-platform-engine - ${junit.platform.version} + ${junit-platform.version} org.junit.platform junit-platform-runner - ${junit.platform.version} + ${junit-platform.version} test @@ -48,17 +48,6 @@ - - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - org.junit.platform - junit-platform-surefire-provider - ${junit.platform.version} - - - org.codehaus.mojo exec-maven-plugin @@ -79,7 +68,7 @@ 5.2.0 - 1.2.0 + 1.2.0 5.2.0 2.21.0 1.6.0 diff --git a/testing-modules/mockito-3/.gitignore b/testing-modules/mockito-3/.gitignore new file mode 100644 index 0000000000..38fe5148c1 --- /dev/null +++ b/testing-modules/mockito-3/.gitignore @@ -0,0 +1,4 @@ +/target/ +/.settings/ +/.classpath +/.project \ No newline at end of file diff --git a/testing-modules/mockito-3/README.md b/testing-modules/mockito-3/README.md new file mode 100644 index 0000000000..c9766031a3 --- /dev/null +++ b/testing-modules/mockito-3/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Mocking Static Methods With Mockito](https://www.baeldung.com/mockito-mock-static-methods) diff --git a/testing-modules/mockito-3/pom.xml b/testing-modules/mockito-3/pom.xml new file mode 100644 index 0000000000..8d506561ed --- /dev/null +++ b/testing-modules/mockito-3/pom.xml @@ -0,0 +1,38 @@ + + + 4.0.0 + mockito-3 + 0.0.1-SNAPSHOT + mockito-3 + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + ../../ + + + + + org.mockito + mockito-inline + ${mockito.version} + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + 3.8.0 + 3.8.0 + + + diff --git a/testing-modules/mockito-3/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java b/testing-modules/mockito-3/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java new file mode 100644 index 0000000000..2e2f5ead33 --- /dev/null +++ b/testing-modules/mockito-3/src/main/java/com/baeldung/mockito/mockedstatic/StaticUtils.java @@ -0,0 +1,22 @@ +package com.baeldung.mockito.mockedstatic; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class StaticUtils { + + private StaticUtils() { + } + + public static List range(int start, int end) { + return IntStream.range(start, end) + .boxed() + .collect(Collectors.toList()); + } + + public static String name() { + return "Baeldung"; + } + +} diff --git a/testing-modules/mockito-3/src/main/resources/logback.xml b/testing-modules/mockito-3/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/testing-modules/mockito-3/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/testing-modules/mockito-3/src/test/java/com/baeldung/mockito/mockedstatic/MockedStaticUnitTest.java b/testing-modules/mockito-3/src/test/java/com/baeldung/mockito/mockedstatic/MockedStaticUnitTest.java new file mode 100644 index 0000000000..a212e6e3eb --- /dev/null +++ b/testing-modules/mockito-3/src/test/java/com/baeldung/mockito/mockedstatic/MockedStaticUnitTest.java @@ -0,0 +1,39 @@ +package com.baeldung.mockito.mockedstatic; + +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import static org.assertj.core.api.Assertions.*; + +import java.util.Arrays; + +class MockedStaticUnitTest { + + @Test + void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() { + assertThat(StaticUtils.name()).isEqualTo("Baeldung"); + + try (MockedStatic utilities = Mockito.mockStatic(StaticUtils.class)) { + utilities.when(StaticUtils::name).thenReturn("Eugen"); + assertThat(StaticUtils.name()).isEqualTo("Eugen"); + } + + assertThat(StaticUtils.name()).isEqualTo("Baeldung"); + } + + @Test + void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() { + assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); + + try (MockedStatic utilities = Mockito.mockStatic(StaticUtils.class)) { + utilities.when(() -> StaticUtils.range(2, 6)) + .thenReturn(Arrays.asList(10, 11, 12)); + + assertThat(StaticUtils.range(2, 6)).containsExactly(10, 11, 12); + } + + assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5); + } + +} diff --git a/testing-modules/parallel-tests-junit/math-test-functions/pom.xml b/testing-modules/parallel-tests-junit/math-test-functions/pom.xml index fb12803333..fdd45e19d6 100644 --- a/testing-modules/parallel-tests-junit/math-test-functions/pom.xml +++ b/testing-modules/parallel-tests-junit/math-test-functions/pom.xml @@ -27,7 +27,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.0 + ${maven-surefire-plugin.version} all 10 @@ -45,4 +45,8 @@ + + 2.22.0 + + diff --git a/testing-modules/parallel-tests-junit/string-test-functions/pom.xml b/testing-modules/parallel-tests-junit/string-test-functions/pom.xml index 313d82c23f..727a1f814a 100644 --- a/testing-modules/parallel-tests-junit/string-test-functions/pom.xml +++ b/testing-modules/parallel-tests-junit/string-test-functions/pom.xml @@ -27,7 +27,7 @@ org.apache.maven.plugins maven-surefire-plugin - 2.22.0 + ${maven-surefire-plugin.version} all true @@ -37,4 +37,8 @@ + + 2.22.0 + + diff --git a/testing-modules/pom.xml b/testing-modules/pom.xml index fd4a13d026..228e47838c 100644 --- a/testing-modules/pom.xml +++ b/testing-modules/pom.xml @@ -16,34 +16,35 @@ assertion-libraries easy-random + easymock gatling groovy-spock + hamcrest + junit-4 + junit-5-advanced + junit-5-basics junit-5 junit5-annotations junit5-migration load-testing-comparison - mockito mockito-2 - hamcrest + mockito-3 + mockito mocks mockserver parallel-tests-junit + powermock rest-assured rest-testing selenium-junit-testng - spring-testing spring-testing-2 + spring-testing test-containers testing-assertions - testng - junit-5-basics - easymock - junit-5-advanced - xmlunit-2 - junit-4 - testing-libraries testing-libraries-2 - powermock + testing-libraries + testng + xmlunit-2 zerocode diff --git a/testing-modules/spring-testing-2/pom.xml b/testing-modules/spring-testing-2/pom.xml index 4686a20202..40b556732a 100644 --- a/testing-modules/spring-testing-2/pom.xml +++ b/testing-modules/spring-testing-2/pom.xml @@ -73,6 +73,5 @@ 1.12.2 - 2.21.0 \ No newline at end of file diff --git a/testing-modules/test-containers/pom.xml b/testing-modules/test-containers/pom.xml index e83d3aff32..1946b7306f 100644 --- a/testing-modules/test-containers/pom.xml +++ b/testing-modules/test-containers/pom.xml @@ -80,17 +80,6 @@ - - maven-surefire-plugin - ${maven-surefire-plugin.version} - - - org.junit.platform - junit-platform-surefire-provider - ${junit-platform-surefire-provider.version} - - - org.codehaus.mojo exec-maven-plugin @@ -117,7 +106,7 @@ 42.2.6 3.141.59 2.22.2 - 1.3.2 + 1.3.2
diff --git a/testing-modules/testing-assertions/pom.xml b/testing-modules/testing-assertions/pom.xml index fa0f666c7f..8b8536462d 100644 --- a/testing-modules/testing-assertions/pom.xml +++ b/testing-modules/testing-assertions/pom.xml @@ -16,47 +16,43 @@ ch.qos.logback logback-classic - 1.2.3 + ${logback.version} org.junit.jupiter junit-jupiter-engine - 5.6.2 + ${junit-jupiter.version} test org.junit.jupiter junit-jupiter-api - 5.6.2 + ${junit-jupiter.version} test org.assertj assertj-core - 3.16.1 + ${assertj-core.version} test org.hamcrest hamcrest-all - 1.3 + ${hamcrest-all.version} test org.apache.commons commons-collections4 - 4.4 + ${commons-collections4.version} test - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.22.1 - - - + + 3.16.1 + 4.4 + 5.6.2 + diff --git a/testing-modules/testing-libraries-2/pom.xml b/testing-modules/testing-libraries-2/pom.xml index 42c84d0da9..7f96280cac 100644 --- a/testing-modules/testing-libraries-2/pom.xml +++ b/testing-modules/testing-libraries-2/pom.xml @@ -16,7 +16,7 @@ org.assertj assertj-core - 3.16.1 + ${assertj-core.version} test @@ -86,5 +86,6 @@ 1.0.0 1.1.0 5.6.2 + 3.16.1 diff --git a/testing-modules/testing-libraries/pom.xml b/testing-modules/testing-libraries/pom.xml index aa22a5253e..4edd13fa30 100644 --- a/testing-modules/testing-libraries/pom.xml +++ b/testing-modules/testing-libraries/pom.xml @@ -36,11 +36,10 @@ ${cucumber.version} test - org.springframework.boot spring-boot-starter-web - 2.2.0.RELEASE + ${spring-boot.version} com.github.stefanbirkner @@ -103,6 +102,7 @@ 3.0.0 1.19.0 1.0.0 + 2.4.3 diff --git a/testing-modules/zerocode/pom.xml b/testing-modules/zerocode/pom.xml index 9d765e6cb4..63f0dc9cbb 100644 --- a/testing-modules/zerocode/pom.xml +++ b/testing-modules/zerocode/pom.xml @@ -28,7 +28,7 @@ org.jsmart zerocode-tdd - 1.3.27 + ${zerocode-tdd.version} test @@ -68,7 +68,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.0.0-M5 + ${maven-failsafe-plugin.version} ${skip.it} @@ -76,7 +76,7 @@ org.apache.maven.surefire surefire-junit47 - 3.0.0-M5 + ${surefire-junit47.version} @@ -92,11 +92,13 @@ - UTF-8 + 3.0.0-M5 + 3.0.0-M5 8 8 2.4.2 true + 1.3.27 diff --git a/webrtc/pom.xml b/webrtc/pom.xml index f302ae97a2..191ff11dd6 100644 --- a/webrtc/pom.xml +++ b/webrtc/pom.xml @@ -31,8 +31,4 @@ - - 1.8 - - diff --git a/wildfly/pom.xml b/wildfly/pom.xml index 7b2a474c8d..6d823bb4c9 100644 --- a/wildfly/pom.xml +++ b/wildfly/pom.xml @@ -76,8 +76,4 @@ - - 1.8 - - diff --git a/xml/pom.xml b/xml/pom.xml index 837f918b46..d2fa5c0727 100644 --- a/xml/pom.xml +++ b/xml/pom.xml @@ -75,12 +75,12 @@ org.openjdk.jmh jmh-core - ${jmh.version} + ${jmh-core.version} org.openjdk.jmh jmh-generator-annprocess - ${jmh.version} + ${jmh-generator.version} @@ -322,8 +322,8 @@ org.apache.maven.plugins maven-compiler-plugin - ${java-version} - ${java-version} + ${java.version} + ${java.version} @@ -374,17 +374,14 @@ 3.12.2 2.6.3 5.5.0 - 1.21 2.3.29 0.9.6 2.4 - 1.8 1.3.1 3.8.0 - 2.22.2 diff --git a/xml/src/main/java/com/baeldung/sax/SaxParserMain.java b/xml/src/main/java/com/baeldung/sax/SaxParserMain.java index 4908c10386..34a46fe469 100644 --- a/xml/src/main/java/com/baeldung/sax/SaxParserMain.java +++ b/xml/src/main/java/com/baeldung/sax/SaxParserMain.java @@ -28,11 +28,15 @@ public class SaxParserMain { private static final String CONTENT = "content"; private Baeldung website; - private String elementValue; + private StringBuilder elementValue; @Override public void characters(char[] ch, int start, int length) throws SAXException { - elementValue = new String(ch, start, length); + if (elementValue == null) { + elementValue = new StringBuilder(); + } else { + elementValue.append(ch, start, length); + } } @Override @@ -48,6 +52,13 @@ public class SaxParserMain { break; case ARTICLE: website.getArticleList().add(new BaeldungArticle()); + break; + case TITLE: + elementValue = new StringBuilder(); + break; + case CONTENT: + elementValue = new StringBuilder(); + break; } } @@ -55,10 +66,10 @@ public class SaxParserMain { public void endElement(String uri, String localName, String qName) throws SAXException { switch (qName) { case TITLE: - latestArticle().setTitle(elementValue); + latestArticle().setTitle(elementValue.toString()); break; case CONTENT: - latestArticle().setContent(elementValue); + latestArticle().setContent(elementValue.toString()); break; } }