From 0947c717100c5f900502c781c0eca83349b264bd Mon Sep 17 00:00:00 2001 From: 515882294 <515882294@qq.com> Date: Wed, 20 Apr 2022 20:02:59 +0800 Subject: [PATCH 01/35] BAEL-5283: Serialize a lambda in Java --- .../NotSerializableLambdaExpression.java | 8 ++ .../SerializableLambdaExpression.java | 10 +++ .../LambdaSerializationUnitTest.java | 77 +++++++++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/NotSerializableLambdaExpression.java create mode 100644 core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/SerializableLambdaExpression.java create mode 100644 core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/lambda/serialization/LambdaSerializationUnitTest.java diff --git a/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/NotSerializableLambdaExpression.java b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/NotSerializableLambdaExpression.java new file mode 100644 index 0000000000..38f87e4ba9 --- /dev/null +++ b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/NotSerializableLambdaExpression.java @@ -0,0 +1,8 @@ +package com.baeldung.java8.lambda.serialization; + +public class NotSerializableLambdaExpression { + public static Object getLambdaExpressionObject() { + Runnable r = () -> System.out.println("please serialize this message"); + return r; + } +} diff --git a/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/SerializableLambdaExpression.java b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/SerializableLambdaExpression.java new file mode 100644 index 0000000000..74541013bb --- /dev/null +++ b/core-java-modules/core-java-lambdas/src/main/java/com/baeldung/java8/lambda/serialization/SerializableLambdaExpression.java @@ -0,0 +1,10 @@ +package com.baeldung.java8.lambda.serialization; + +import java.io.Serializable; + +public class SerializableLambdaExpression { + public static Object getLambdaExpressionObject() { + Runnable r = (Runnable & Serializable) () -> System.out.println("please serialize this message"); + return r; + } +} diff --git a/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/lambda/serialization/LambdaSerializationUnitTest.java b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/lambda/serialization/LambdaSerializationUnitTest.java new file mode 100644 index 0000000000..580319c92e --- /dev/null +++ b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/lambda/serialization/LambdaSerializationUnitTest.java @@ -0,0 +1,77 @@ +package com.baeldung.java8.lambda.serialization; + +import org.junit.Test; + +import java.io.*; +import java.nio.file.Files; +import java.util.function.Consumer; +import java.util.function.Function; + +import static org.junit.Assert.assertTrue; + +public class LambdaSerializationUnitTest { + @Test(expected = NotSerializableException.class) + public void givenRunnable_whenNoCapturing_thenSerializationFailed() throws IOException, ClassNotFoundException { + Object obj = NotSerializableLambdaExpression.getLambdaExpressionObject(); + writeAndReadObject(obj, Runnable.class); + } + + @Test + public void givenIntersectionType_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException { + Object obj = SerializableLambdaExpression.getLambdaExpressionObject(); + writeAndReadObject(obj, Runnable.class); + } + + @Test + public void givenSerializableRunnable_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException { + SerializableRunnable obj = () -> System.out.println("please serialize this message"); + writeAndReadObject(obj, SerializableRunnable.class); + } + + @Test + public void givenSerializableFunction_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException { + SerializableFunction obj = message -> String.format("Hello %s", message); + writeAndReadObject(obj, SerializableFunction.class); + } + + @Test + public void givenSerializableConsumer_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException { + SerializableConsumer obj = System.out::println; + writeAndReadObject(obj, SerializableConsumer.class); + } + + @Test(expected = NotSerializableException.class) + public void givenSerializableConsumer_whenCapturingNotSerializable_thenSerializationFailed() throws IOException, ClassNotFoundException { + SerializableConsumer obj = System.out::println; + writeAndReadObject(obj, SerializableConsumer.class); + } + + private void writeAndReadObject(Object obj, Class clazz) throws IOException, ClassNotFoundException { + File file = Files.createTempFile("lambda", "ser").toFile(); + try ( + FileOutputStream fos = new FileOutputStream(file); + ObjectOutputStream oos = new ObjectOutputStream(fos) + ) { + oos.writeObject(obj); + } + + try ( + FileInputStream fis = new FileInputStream(file); + ObjectInputStream ois = new ObjectInputStream(fis) + ) { + Object newObj = ois.readObject(); + boolean isInstance = clazz.isInstance(newObj); + + assertTrue(isInstance); + } + } + + interface SerializableRunnable extends Runnable, Serializable { + } + + interface SerializableFunction extends Function, Serializable { + } + + interface SerializableConsumer extends Consumer, Serializable { + } +} From 7093bdc456b4932883f2bb5150ec3c297c0ca535 Mon Sep 17 00:00:00 2001 From: Christian Jaimes Date: Thu, 21 Apr 2022 09:29:37 -0400 Subject: [PATCH 02/35] added randomDirection method to Enum. Created RandomEnumGenerator. Added corresponding Unit Tests --- .../java/com/baeldung/enums/Direction.java | 14 ++++++++++ .../baeldung/enums/RandomEnumGenerator.java | 17 ++++++++++++ .../baeldung/enums/RandomEnumUnitTest.java | 27 +++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/RandomEnumGenerator.java create mode 100644 core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/RandomEnumUnitTest.java diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/Direction.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/Direction.java index 935aca4d65..76b63bdf50 100644 --- a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/Direction.java +++ b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/Direction.java @@ -1,11 +1,25 @@ package com.baeldung.enums; +import java.util.Random; + /** * Represents directions. */ public enum Direction { EAST, WEST, SOUTH, NORTH; + private static final Random PRNG = new Random(); + + /** + * Generate a random direction. + * + * @return a random direction + */ + public static Direction randomDirection() { + Direction[] directions = values(); + return directions[PRNG.nextInt(directions.length)]; + } + /** * Finds direction by name. * diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/RandomEnumGenerator.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/RandomEnumGenerator.java new file mode 100644 index 0000000000..ea27286044 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/RandomEnumGenerator.java @@ -0,0 +1,17 @@ +package com.baeldung.enums; + +import java.util.Random; + +public class RandomEnumGenerator> { + + private static final Random PRNG = new Random(); + private final T[] values; + + public RandomEnumGenerator(Class e) { + values = e.getEnumConstants(); + } + + public T randomEnum() { + return values[PRNG.nextInt(values.length)]; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/RandomEnumUnitTest.java b/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/RandomEnumUnitTest.java new file mode 100644 index 0000000000..937b376c29 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/RandomEnumUnitTest.java @@ -0,0 +1,27 @@ +package com.baeldung.enums; + +import org.assertj.core.api.Assertions; +import org.junit.Test; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +public class RandomEnumUnitTest { + + @Test + public void givenEnumType_whenUsingStaticMethod_valueIsRandomlyGenerated() { + Direction direction = Direction.randomDirection(); + assertThat(direction).isNotNull(); + assertThat(direction instanceof Direction); + } + + @Test + public void givenEnumType_whenGeneratingRandomValue_valueIsOfClassAndNotNull() { + RandomEnumGenerator reg = new RandomEnumGenerator(Direction.class); + Object direction = reg.randomEnum(); + assertThat(direction).isNotNull(); + assertThat(direction instanceof Direction); + } +} From 3cc6b034b8522b67934b4ce9efda17d851f22b32 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Tue, 26 Apr 2022 20:13:08 +0100 Subject: [PATCH 03/35] [JAVA-11417] Fix log4j2 JSON integration test --- .../tests/JSONLayoutIntegrationTest.java | 63 +++++++++++-------- 1 file changed, 37 insertions(+), 26 deletions(-) diff --git a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java index e842cda3d6..86cd00c6af 100644 --- a/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java +++ b/logging-modules/log4j2/src/test/java/com/baeldung/logging/log4j2/tests/JSONLayoutIntegrationTest.java @@ -1,47 +1,58 @@ package com.baeldung.logging.log4j2.tests; -import static org.junit.Assert.assertTrue; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.PrintStream; - +import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.appender.WriterAppender; +import org.apache.logging.log4j.core.layout.JsonLayout; +import org.junit.After; import org.junit.Before; import org.junit.Test; -import com.baeldung.logging.log4j2.Log4j2BaseIntegrationTest; -import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.CharArrayWriter; +import java.io.Writer; + +import static org.junit.Assert.assertTrue; public class JSONLayoutIntegrationTest extends Log4j2BaseIntegrationTest { - private static Logger logger; - private ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream(); - private PrintStream ps = new PrintStream(consoleOutput); + private Appender appender; + private Logger logger; + private final Writer writer = new CharArrayWriter(); @Before public void setUp() { - // Redirect console output to our stream - System.setOut(ps); logger = LogManager.getLogger("CONSOLE_JSON_APPENDER"); + + appender = WriterAppender.newBuilder() + .setTarget(writer) + .setLayout(JsonLayout.newBuilder().build()) + .setName("json_layout_for_testing") + .build(); + appender.start(); + + ((org.apache.logging.log4j.core.Logger) logger).addAppender(appender); } @Test - public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() { + public void whenLogLayoutInJSON_thenOutputIsCorrectJSON() throws Exception { logger.debug("Debug message"); - String currentLog = consoleOutput.toString(); - assertTrue(currentLog.isEmpty()); - assertTrue(isValidJSON(currentLog)); + + writer.flush(); + assertTrue(isValidJSON(writer.toString())); } - public static boolean isValidJSON(String jsonInString) { - try { - final ObjectMapper mapper = new ObjectMapper(); - mapper.readTree(jsonInString); - return true; - } catch (IOException e) { - return false; - } + @After + public void cleanup() { + ((org.apache.logging.log4j.core.Logger) logger).removeAppender(appender); } -} \ No newline at end of file + + private static boolean isValidJSON(String jsonInString) throws Exception { + JsonNode jsonNode = new ObjectMapper().readTree(jsonInString); + return jsonNode.get("message").asText().equals("Debug message"); + } + +} From c9a91ca3b1220c0d7c0b4a844fc08629af9345f4 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 27 Apr 2022 16:36:10 +0800 Subject: [PATCH 04/35] Update README.md --- core-java-modules/core-java-11-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-11-2/README.md b/core-java-modules/core-java-11-2/README.md index 2b0eda8d91..c42b3f0e18 100644 --- a/core-java-modules/core-java-11-2/README.md +++ b/core-java-modules/core-java-11-2/README.md @@ -11,3 +11,4 @@ This module contains articles about Java 11 core features - [Invoking a SOAP Web Service in Java](https://www.baeldung.com/java-soap-web-service) - [Java HTTPS Client Certificate Authentication](https://www.baeldung.com/java-https-client-certificate-authentication) - [Call Methods at Runtime Using Java Reflection](https://www.baeldung.com/java-method-reflection) +- [Java HttpClient Basic Authentication](https://www.baeldung.com/java-httpclient-basic-auth) From 94d3b980dc2d7309e5d14e4bd67901f63e23d7ce Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 27 Apr 2022 16:40:19 +0800 Subject: [PATCH 05/35] Update README.md --- persistence-modules/java-mongodb-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-mongodb-2/README.md b/persistence-modules/java-mongodb-2/README.md index bee5439ab1..10cb935f56 100644 --- a/persistence-modules/java-mongodb-2/README.md +++ b/persistence-modules/java-mongodb-2/README.md @@ -11,4 +11,5 @@ This module contains articles about MongoDB in Java. - [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations) - [Retrieve a Value from MongoDB by Its Key Name](https://www.baeldung.com/mongodb-get-value-by-key-name) - [Push and Set Operations in Same MongoDB Update](https://www.baeldung.com/java-mongodb-push-set) +- [Checking Connection to MongoDB](https://www.baeldung.com/mongodb-check-connection) - More articles: [[<-- prev]](../java-mongodb) From 360ca495d482549a4f1006a7864a8180b25acb39 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 27 Apr 2022 16:47:43 +0800 Subject: [PATCH 06/35] Update README.md --- core-java-modules/core-java-regex-2/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-java-modules/core-java-regex-2/README.md b/core-java-modules/core-java-regex-2/README.md index 6dafc74d41..453e2cc419 100644 --- a/core-java-modules/core-java-regex-2/README.md +++ b/core-java-modules/core-java-regex-2/README.md @@ -4,4 +4,5 @@ - [Lookahead and Lookbehind in Java Regex](https://www.baeldung.com/java-regex-lookahead-lookbehind) - [Converting Camel Case and Title Case to Words in Java](https://www.baeldung.com/java-camel-case-title-case-to-words) - [How to Use Regular Expressions to Replace Tokens in Strings in Java](https://www.baeldung.com/java-regex-token-replacement) -- More articles: [[<-- prev]](/core-java-modules/core-java-regex) \ No newline at end of file +- [Creating a Java Array from Regular Expression Matches](https://www.baeldung.com/java-array-regex-matches) +- More articles: [[<-- prev]](/core-java-modules/core-java-regex) From 98c27e6b9f682c8044a5d7ab072ce52c40665968 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 27 Apr 2022 16:53:44 +0800 Subject: [PATCH 07/35] Update README.md --- core-java-modules/core-java-collections-list-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-list-3/README.md b/core-java-modules/core-java-collections-list-3/README.md index bcc8b3f3ed..ecae0dda7d 100644 --- a/core-java-modules/core-java-collections-list-3/README.md +++ b/core-java-modules/core-java-collections-list-3/README.md @@ -12,4 +12,5 @@ This module contains articles about the Java List collection - [How to Count Duplicate Elements in Arraylist](https://www.baeldung.com/java-count-duplicate-elements-arraylist) - [Finding the Differences Between Two Lists in Java](https://www.baeldung.com/java-lists-difference) - [List vs. ArrayList in Java](https://www.baeldung.com/java-list-vs-arraylist) +- [How to Store HashMap Inside a List](https://www.baeldung.com/java-hashmap-inside-list) - [[<-- Prev]](/core-java-modules/core-java-collections-list-2) From fde9ae6880da7c85ea8c31de22bf9dd5ccad2e6c Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 27 Apr 2022 16:58:57 +0800 Subject: [PATCH 08/35] Update README.md --- graphql/graphql-java/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/graphql/graphql-java/README.md b/graphql/graphql-java/README.md index f37506a9fd..85c1497169 100644 --- a/graphql/graphql-java/README.md +++ b/graphql/graphql-java/README.md @@ -6,3 +6,4 @@ This module contains articles about GraphQL with Java - [Introduction to GraphQL](https://www.baeldung.com/graphql) - [Make a Call to a GraphQL Service from a Java Application](https://www.baeldung.com/java-call-graphql-service) +- [Return Map from GraphQL](https://www.baeldung.com/java-graphql-return-map) From 7f39e139380c4819c802aa10a55e1782542912c9 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 27 Apr 2022 17:23:04 +0800 Subject: [PATCH 09/35] Update README.md --- jersey/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/jersey/README.md b/jersey/README.md index 366e7665f3..4c8c235be5 100644 --- a/jersey/README.md +++ b/jersey/README.md @@ -10,3 +10,4 @@ This module contains articles about Jersey. - [Exploring the Jersey Test Framework](https://www.baeldung.com/jersey-test) - [Explore Jersey Request Parameters](https://www.baeldung.com/jersey-request-parameters) - [Add a Header to a Jersey SSE Client Request](https://www.baeldung.com/jersey-sse-client-request-headers) +- [Exception Handling With Jersey](https://www.baeldung.com/java-exception-handling-jersey) From f455f0b5a8495d4816edc695e9028f11f62174d2 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 27 Apr 2022 17:28:08 +0800 Subject: [PATCH 10/35] Update README.md --- core-java-modules/core-java-collections-list-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-list-3/README.md b/core-java-modules/core-java-collections-list-3/README.md index ecae0dda7d..6d0a3c7037 100644 --- a/core-java-modules/core-java-collections-list-3/README.md +++ b/core-java-modules/core-java-collections-list-3/README.md @@ -13,4 +13,5 @@ This module contains articles about the Java List collection - [Finding the Differences Between Two Lists in Java](https://www.baeldung.com/java-lists-difference) - [List vs. ArrayList in Java](https://www.baeldung.com/java-list-vs-arraylist) - [How to Store HashMap Inside a List](https://www.baeldung.com/java-hashmap-inside-list) +- [Working With a List of Lists in Java](https://www.baeldung.com/java-list-of-lists) - [[<-- Prev]](/core-java-modules/core-java-collections-list-2) From d662408b20de4f0c161c9cfa62d6f784609ba884 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 27 Apr 2022 17:34:34 +0800 Subject: [PATCH 11/35] Update README.md --- spring-security-modules/spring-security-core/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-modules/spring-security-core/README.md b/spring-security-modules/spring-security-core/README.md index 9f8e4dda53..1949b5a929 100644 --- a/spring-security-modules/spring-security-core/README.md +++ b/spring-security-modules/spring-security-core/README.md @@ -10,6 +10,7 @@ This module contains articles about core Spring Security - [Deny Access on Missing @PreAuthorize to Spring Controller Methods](https://www.baeldung.com/spring-deny-access) - [Spring Security: Check If a User Has a Role in Java](https://www.baeldung.com/spring-security-check-user-role) - [Filtering Jackson JSON Output Based on Spring Security Role](https://www.baeldung.com/spring-security-role-filter-json) +- [Handle Spring Security Exceptions](https://www.baeldung.com/spring-security-exceptions) ### Build the Project From e81d306a64c61717f08cab20c7c39651b8a77927 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 27 Apr 2022 17:38:30 +0800 Subject: [PATCH 12/35] Update README.md --- core-java-modules/core-java-networking-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-networking-3/README.md b/core-java-modules/core-java-networking-3/README.md index 82e75820ba..21f939b43e 100644 --- a/core-java-modules/core-java-networking-3/README.md +++ b/core-java-modules/core-java-networking-3/README.md @@ -10,4 +10,5 @@ This module contains articles about networking in Java - [Find Whether an IP Address Is in the Specified Range or Not in Java](https://www.baeldung.com/java-check-ip-address-range) - [Find the IP Address of a Client Connected to a Server](https://www.baeldung.com/java-client-get-ip-address) - [Unix Domain Socket in Java 16](https://www.baeldung.com/java-unix-domain-socket) +- [Get the IP Address of the Current Machine Using Java](https://www.baeldung.com/java-get-ip-address) - [[<-- Prev]](/core-java-modules/core-java-networking-2) From cd78bd7c2a7c19eed229ac5895da4447775d34df Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 27 Apr 2022 17:43:41 +0800 Subject: [PATCH 13/35] Update README.md --- core-java-modules/core-java/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md index a75805e0c2..087c5d356e 100644 --- a/core-java-modules/core-java/README.md +++ b/core-java-modules/core-java/README.md @@ -1,9 +1,11 @@ ## Core Java Cookbooks and Examples ### Relevant Articles: + - [Getting Started with Java Properties](http://www.baeldung.com/java-properties) - [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency) - [Compiling Java *.class Files with javac](http://www.baeldung.com/javac) - [Introduction to Javadoc](http://www.baeldung.com/javadoc) - [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle) - [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties) +- [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error) From 4495b45d0b450d6531bd49d882fc7a5bf26666d3 Mon Sep 17 00:00:00 2001 From: Christian Jaimes Date: Wed, 27 Apr 2022 06:51:13 -0400 Subject: [PATCH 14/35] moved files to article-specific folder --- .../java/com/baeldung/enums/Direction.java | 14 ------------ .../baeldung/enums/randomenum/Direction.java | 22 +++++++++++++++++++ .../enums/randomenum/RandomEnumGenerator.java | 17 ++++++++++++++ .../{ => randomenum}/RandomEnumUnitTest.java | 6 +---- 4 files changed, 40 insertions(+), 19 deletions(-) create mode 100644 core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/Direction.java create mode 100644 core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/RandomEnumGenerator.java rename core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/{ => randomenum}/RandomEnumUnitTest.java (79%) diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/Direction.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/Direction.java index 76b63bdf50..935aca4d65 100644 --- a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/Direction.java +++ b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/Direction.java @@ -1,25 +1,11 @@ package com.baeldung.enums; -import java.util.Random; - /** * Represents directions. */ public enum Direction { EAST, WEST, SOUTH, NORTH; - private static final Random PRNG = new Random(); - - /** - * Generate a random direction. - * - * @return a random direction - */ - public static Direction randomDirection() { - Direction[] directions = values(); - return directions[PRNG.nextInt(directions.length)]; - } - /** * Finds direction by name. * diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/Direction.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/Direction.java new file mode 100644 index 0000000000..05b398371c --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/Direction.java @@ -0,0 +1,22 @@ +package com.baeldung.enums.randomenum; + +import java.util.Random; + +/** + * Represents directions. + */ +public enum Direction { + EAST, WEST, SOUTH, NORTH; + + private static final Random PRNG = new Random(); + + /** + * Generate a random direction. + * + * @return a random direction + */ + public static Direction randomDirection() { + Direction[] directions = values(); + return directions[PRNG.nextInt(directions.length)]; + } +} diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/RandomEnumGenerator.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/RandomEnumGenerator.java new file mode 100644 index 0000000000..33d793062d --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/RandomEnumGenerator.java @@ -0,0 +1,17 @@ +package com.baeldung.enums.randomenum; + +import java.util.Random; + +public class RandomEnumGenerator> { + + private static final Random PRNG = new Random(); + private final T[] values; + + public RandomEnumGenerator(Class e) { + values = e.getEnumConstants(); + } + + public T randomEnum() { + return values[PRNG.nextInt(values.length)]; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/RandomEnumUnitTest.java b/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/randomenum/RandomEnumUnitTest.java similarity index 79% rename from core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/RandomEnumUnitTest.java rename to core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/randomenum/RandomEnumUnitTest.java index 937b376c29..76b4bf1e74 100644 --- a/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/RandomEnumUnitTest.java +++ b/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/randomenum/RandomEnumUnitTest.java @@ -1,12 +1,8 @@ -package com.baeldung.enums; +package com.baeldung.enums.randomenum; -import org.assertj.core.api.Assertions; import org.junit.Test; -import java.util.Optional; - import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; public class RandomEnumUnitTest { From fdf79fdd879183bc363597d58adcd2460a6959ba Mon Sep 17 00:00:00 2001 From: Christian Jaimes Date: Wed, 27 Apr 2022 06:54:46 -0400 Subject: [PATCH 15/35] removed unnecessary file --- .../com/baeldung/enums/RandomEnumGenerator.java | 17 ----------------- 1 file changed, 17 deletions(-) delete mode 100644 core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/RandomEnumGenerator.java diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/RandomEnumGenerator.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/RandomEnumGenerator.java deleted file mode 100644 index ea27286044..0000000000 --- a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/RandomEnumGenerator.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung.enums; - -import java.util.Random; - -public class RandomEnumGenerator> { - - private static final Random PRNG = new Random(); - private final T[] values; - - public RandomEnumGenerator(Class e) { - values = e.getEnumConstants(); - } - - public T randomEnum() { - return values[PRNG.nextInt(values.length)]; - } -} \ No newline at end of file From 7fb15d26dd47e8b07f7947e3ec5f2c2708844a01 Mon Sep 17 00:00:00 2001 From: Mayank Aggarwal Date: Thu, 28 Apr 2022 13:56:16 +0530 Subject: [PATCH 16/35] [BAEL-5438] Added Criteria Queries & Hibernate Queries (#12127) * [BAEL-5438] Added Criteria Queries for Employee * [BAEL-5438] Added tests and entities for named queries and criteria queries * [BAEL-5438] Removed unused sorting files * [BAEL-5438] Ignored spring context test Co-authored-by: Mayank Agarwal --- .../hibernate/criteria/model/Employee.java | 76 +++++++++++++++++++ .../view/EmployeeCriteriaQueries.java | 45 +++++++++++ .../java/com/baeldung/SpringContextTest.java | 2 + .../EmployeeCriteriaIntegrationTest.java | 36 +++++++++ .../hibernate/criteria/model/Employee.hbm.xml | 19 +++++ .../src/test/resources/criteria.cfg.xml | 1 + .../src/test/resources/import-db.sql | 7 ++ .../spring/data/jpa/entity/Employee.java | 18 +++++ .../jpa/repository/EmployeeRepository.java | 37 +++++++++ 9 files changed, 241 insertions(+) create mode 100644 persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java create mode 100644 persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java create mode 100644 persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/EmployeeCriteriaIntegrationTest.java create mode 100644 persistence-modules/hibernate-queries/src/test/resources/com/baeldung/hibernate/criteria/model/Employee.hbm.xml create mode 100644 persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/entity/Employee.java create mode 100644 persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/repository/EmployeeRepository.java diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java new file mode 100644 index 0000000000..994d3f3800 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java @@ -0,0 +1,76 @@ +package com.baeldung.hibernate.criteria.model; + +import java.io.Serializable; +import javax.persistence.Entity; + +@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "Employee_findByEmployeeId", query = "from Employee where id = :employeeId"), + @org.hibernate.annotations.NamedQuery(name = "Employee_findAllByEmployeeSalary", query = "from Employee where salary = :employeeSalary")}) +@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "Employee_FindByEmployeeId", query = "select * from employee emp where employeeId=:employeeId", resultClass = Employee.class)}) +@Entity +public class Employee implements Serializable { + + private static final long serialVersionUID = 1L; + private Integer id; + private String name; + private Long salary; + + // constructors + public Employee() { + } + + public Employee(final Integer id, final String name, final Long salary) { + super(); + this.id = id; + this.name = name; + this.salary = salary; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final Employee other = (Employee) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Long getSalary() { + return salary; + } + + public void setSalary(Long salary) { + this.salary = salary; + } +} diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java new file mode 100644 index 0000000000..04e27d2ec1 --- /dev/null +++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java @@ -0,0 +1,45 @@ +package com.baeldung.hibernate.criteria.view; + +import com.baeldung.hibernate.criteria.model.Employee; +import com.baeldung.hibernate.criteria.util.HibernateUtil; +import java.util.List; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import org.hibernate.Session; +import org.hibernate.query.Query; + +public class EmployeeCriteriaQueries { + + public List getAllEmployees() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Employee.class); + final Root root = cr.from(Employee.class); + cr.select(root); + Query query = session.createQuery(cr); + List results = query.getResultList(); + session.close(); + return results; + } + + // To get items having salary more than 50000 + public String[] greaterThanCriteria() { + final Session session = HibernateUtil.getHibernateSession(); + final CriteriaBuilder cb = session.getCriteriaBuilder(); + final CriteriaQuery cr = cb.createQuery(Employee.class); + final Root root = cr.from(Employee.class); + cr.select(root) + .where(cb.gt(root.get("salary"), 50000)); + Query query = session.createQuery(cr); + final List greaterThanEmployeeList = query.getResultList(); + final String employeeWithGreaterSalary[] = new String[greaterThanEmployeeList.size()]; + for (int i = 0; i < greaterThanEmployeeList.size(); i++) { + employeeWithGreaterSalary[i] = greaterThanEmployeeList.get(i) + .getName(); + } + session.close(); + return employeeWithGreaterSalary; + } + +} diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/SpringContextTest.java index 6503454abf..83af0e0be6 100644 --- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/SpringContextTest.java +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/SpringContextTest.java @@ -1,5 +1,6 @@ package com.baeldung; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; @@ -13,6 +14,7 @@ import com.baeldung.hibernate.criteria.PersistenceConfig; public class SpringContextTest { @Test + @Ignore public void whenSpringContextIsBootstrapped_thenNoExceptions() { } } diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/EmployeeCriteriaIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/EmployeeCriteriaIntegrationTest.java new file mode 100644 index 0000000000..b2ad4240bf --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/EmployeeCriteriaIntegrationTest.java @@ -0,0 +1,36 @@ +package com.baeldung.hibernate.criteria; + +import static org.junit.Assert.assertArrayEquals; + +import com.baeldung.hibernate.criteria.model.Employee; +import com.baeldung.hibernate.criteria.util.HibernateUtil; +import com.baeldung.hibernate.criteria.view.EmployeeCriteriaQueries; +import java.util.List; +import org.hibernate.Session; +import org.junit.Test; + +public class EmployeeCriteriaIntegrationTest { + + final private EmployeeCriteriaQueries employeeCriteriaQueries = new EmployeeCriteriaQueries(); + + @Test + public void testGreaterThanCriteriaQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedGreaterThanList = session.createQuery("From Employee where salary>50000").list(); + final String expectedGreaterThanEmployees[] = new String[expectedGreaterThanList.size()]; + for (int i = 0; i < expectedGreaterThanList.size(); i++) { + expectedGreaterThanEmployees[i] = expectedGreaterThanList.get(i).getName(); + } + session.close(); + assertArrayEquals(expectedGreaterThanEmployees, employeeCriteriaQueries.greaterThanCriteria()); + } + + @Test + public void testGetAllEmployeesQuery() { + final Session session = HibernateUtil.getHibernateSession(); + final List expectedSortCritEmployeeList = session.createQuery("From Employee").list(); + session.close(); + assertArrayEquals(expectedSortCritEmployeeList.toArray(), employeeCriteriaQueries.getAllEmployees().toArray()); + } + +} diff --git a/persistence-modules/hibernate-queries/src/test/resources/com/baeldung/hibernate/criteria/model/Employee.hbm.xml b/persistence-modules/hibernate-queries/src/test/resources/com/baeldung/hibernate/criteria/model/Employee.hbm.xml new file mode 100644 index 0000000000..90e1c2fefd --- /dev/null +++ b/persistence-modules/hibernate-queries/src/test/resources/com/baeldung/hibernate/criteria/model/Employee.hbm.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/resources/criteria.cfg.xml b/persistence-modules/hibernate-queries/src/test/resources/criteria.cfg.xml index 9ca9836a70..30d8168c5c 100644 --- a/persistence-modules/hibernate-queries/src/test/resources/criteria.cfg.xml +++ b/persistence-modules/hibernate-queries/src/test/resources/criteria.cfg.xml @@ -14,5 +14,6 @@ import-db.sql false + \ No newline at end of file diff --git a/persistence-modules/hibernate-queries/src/test/resources/import-db.sql b/persistence-modules/hibernate-queries/src/test/resources/import-db.sql index 52c800f6b4..7933d280b8 100644 --- a/persistence-modules/hibernate-queries/src/test/resources/import-db.sql +++ b/persistence-modules/hibernate-queries/src/test/resources/import-db.sql @@ -20,3 +20,10 @@ insert into item (item_id, item_name, item_desc, item_price) values(9,'Household insert into item (item_id, item_name, item_desc, item_price) values(10,'Office Chairs', 'Chairs for office', 395.98); insert into item (item_id, item_name, item_desc, item_price) values(11,'Outdoor Chairs', 'Chairs for outdoor activities', 1234.36); + +insert into EMPLOYEE (id, name, salary) values(1,'Steve Jobs', 55000); + +insert into EMPLOYEE (id, name, salary) values(1,'Bill Hages', 45000); + +insert into EMPLOYEE (id, name, salary) values(1,'Mark clinch', 57000); + diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/entity/Employee.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/entity/Employee.java new file mode 100644 index 0000000000..214cb09e57 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/entity/Employee.java @@ -0,0 +1,18 @@ +package com.baeldung.spring.data.jpa.entity; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; + +@Entity +public class Employee { + + @Id + @GeneratedValue + private Integer id; + + private String name; + + private Long salary; + +} diff --git a/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/repository/EmployeeRepository.java b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/repository/EmployeeRepository.java new file mode 100644 index 0000000000..652b7b93d2 --- /dev/null +++ b/persistence-modules/spring-data-jpa-query-3/src/main/java/com/baeldung/spring/data/jpa/repository/EmployeeRepository.java @@ -0,0 +1,37 @@ +package com.baeldung.spring.data.jpa.repository; + +import com.baeldung.spring.data.jpa.entity.Employee; +import java.util.List; +import net.bytebuddy.TypeCache.Sort; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +public interface EmployeeRepository extends JpaRepository { + + @Query(value = "SELECT e FROM Employee e") + List findAllEmployees(Sort sort); + + @Query("SELECT e FROM Employee e WHERE e.salary = ?1") + Employee findAllEmployeesWithSalary(Long salary); + + @Query("SELECT e FROM Employee e WHERE e.name = ?1 and e.salary = ?2") + Employee findUserByNameAndSalary(String name, Long salary); + + @Query( + value = "SELECT * FROM Employee e WHERE e.salary = ?1", + nativeQuery = true) + Employee findUserBySalaryNative(Long salary); + + @Query("SELECT e FROM Employee e WHERE e.name = :name and e.salary = :salary") + Employee findUserByEmployeeNameAndSalaryNamedParameters( + @Param("name") String employeeName, + @Param("salary") Long employeeSalary); + + @Query(value = "SELECT * FROM Employee e WHERE e.name = :name and e.salary = :salary", + nativeQuery = true) + Employee findUserByNameAndSalaryNamedParamsNative( + @Param("name") String employeeName, + @Param("salary") Long employeeSalary); + +} From 430bd13ba0a0d90df58cbfad3aae2e7407c41826 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Thu, 28 Apr 2022 18:44:01 +0530 Subject: [PATCH 17/35] JAVA-11532 Move maven related modules to maven-modules (#12133) * JAVA-11532 Move maven related modules to maven-modules * JAVA-11532 Remove moved module from parent pom --- .../animal-sniffer-mvn-plugin}/README.md | 0 .../animal-sniffer-mvn-plugin}/pom.xml | 4 ++-- .../src/main/java/com/baeldung/App.java | 0 .../src/main/resources/logback.xml | 0 .../src/test/java/com/baeldung/AppUnitTest.java | 0 .../maven-archetype}/README.md | 0 {maven-archetype => maven-modules/maven-archetype}/pom.xml | 0 .../main/resources/META-INF/maven/archetype-metadata.xml | 0 .../src/main/resources/archetype-resources/pom.xml | 0 .../archetype-resources/src/main/java/AppConfig.java | 0 .../archetype-resources/src/main/java/PingResource.java | 0 .../archetype-resources/src/main/liberty/config/server.xml | 0 .../maven-archetype}/src/main/resources/logback.xml | 0 {maven-polyglot => maven-modules/maven-polyglot}/README.md | 0 .../maven-polyglot-json-app/.mvn/extensions.xml | 0 .../maven-polyglot}/maven-polyglot-json-app/pom.json | 0 .../baeldung/maven/polyglot/MavenPolyglotApplication.java | 0 .../maven-polyglot-json-app/src/main/resources/model.json | 0 .../maven-polyglot}/maven-polyglot-json-extension/pom.xml | 4 ++-- .../main/java/com/demo/polyglot/CustomModelProcessor.java | 0 .../maven-polyglot-yml-app/.mvn/extensions.xml | 0 .../maven-polyglot}/maven-polyglot-yml-app/pom.yml | 0 .../com/baeldung/maven/polyglot/YamlDemoApplication.java | 0 .../maven-polyglot-yml-app/src/main/resources/model.json | 0 {maven-polyglot => maven-modules/maven-polyglot}/pom.xml | 4 ++-- maven-modules/pom.xml | 3 +++ pom.xml | 6 ------ 27 files changed, 9 insertions(+), 12 deletions(-) rename {animal-sniffer-mvn-plugin => maven-modules/animal-sniffer-mvn-plugin}/README.md (100%) rename {animal-sniffer-mvn-plugin => maven-modules/animal-sniffer-mvn-plugin}/pom.xml (94%) rename {animal-sniffer-mvn-plugin => maven-modules/animal-sniffer-mvn-plugin}/src/main/java/com/baeldung/App.java (100%) rename {animal-sniffer-mvn-plugin => maven-modules/animal-sniffer-mvn-plugin}/src/main/resources/logback.xml (100%) rename {animal-sniffer-mvn-plugin => maven-modules/animal-sniffer-mvn-plugin}/src/test/java/com/baeldung/AppUnitTest.java (100%) rename {maven-archetype => maven-modules/maven-archetype}/README.md (100%) rename {maven-archetype => maven-modules/maven-archetype}/pom.xml (100%) rename {maven-archetype => maven-modules/maven-archetype}/src/main/resources/META-INF/maven/archetype-metadata.xml (100%) rename {maven-archetype => maven-modules/maven-archetype}/src/main/resources/archetype-resources/pom.xml (100%) rename {maven-archetype => maven-modules/maven-archetype}/src/main/resources/archetype-resources/src/main/java/AppConfig.java (100%) rename {maven-archetype => maven-modules/maven-archetype}/src/main/resources/archetype-resources/src/main/java/PingResource.java (100%) rename {maven-archetype => maven-modules/maven-archetype}/src/main/resources/archetype-resources/src/main/liberty/config/server.xml (100%) rename {maven-archetype => maven-modules/maven-archetype}/src/main/resources/logback.xml (100%) rename {maven-polyglot => maven-modules/maven-polyglot}/README.md (100%) rename {maven-polyglot => maven-modules/maven-polyglot}/maven-polyglot-json-app/.mvn/extensions.xml (100%) rename {maven-polyglot => maven-modules/maven-polyglot}/maven-polyglot-json-app/pom.json (100%) rename {maven-polyglot => maven-modules/maven-polyglot}/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java (100%) rename {maven-polyglot => maven-modules/maven-polyglot}/maven-polyglot-json-app/src/main/resources/model.json (100%) rename {maven-polyglot => maven-modules/maven-polyglot}/maven-polyglot-json-extension/pom.xml (94%) rename {maven-polyglot => maven-modules/maven-polyglot}/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java (100%) rename {maven-polyglot => maven-modules/maven-polyglot}/maven-polyglot-yml-app/.mvn/extensions.xml (100%) rename {maven-polyglot => maven-modules/maven-polyglot}/maven-polyglot-yml-app/pom.yml (100%) rename {maven-polyglot => maven-modules/maven-polyglot}/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java (100%) rename {maven-polyglot => maven-modules/maven-polyglot}/maven-polyglot-yml-app/src/main/resources/model.json (100%) rename {maven-polyglot => maven-modules/maven-polyglot}/pom.xml (88%) diff --git a/animal-sniffer-mvn-plugin/README.md b/maven-modules/animal-sniffer-mvn-plugin/README.md similarity index 100% rename from animal-sniffer-mvn-plugin/README.md rename to maven-modules/animal-sniffer-mvn-plugin/README.md diff --git a/animal-sniffer-mvn-plugin/pom.xml b/maven-modules/animal-sniffer-mvn-plugin/pom.xml similarity index 94% rename from animal-sniffer-mvn-plugin/pom.xml rename to maven-modules/animal-sniffer-mvn-plugin/pom.xml index 9e4f25c791..1756adc27d 100644 --- a/animal-sniffer-mvn-plugin/pom.xml +++ b/maven-modules/animal-sniffer-mvn-plugin/pom.xml @@ -11,8 +11,8 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + maven-modules + 0.0.1-SNAPSHOT diff --git a/animal-sniffer-mvn-plugin/src/main/java/com/baeldung/App.java b/maven-modules/animal-sniffer-mvn-plugin/src/main/java/com/baeldung/App.java similarity index 100% rename from animal-sniffer-mvn-plugin/src/main/java/com/baeldung/App.java rename to maven-modules/animal-sniffer-mvn-plugin/src/main/java/com/baeldung/App.java diff --git a/animal-sniffer-mvn-plugin/src/main/resources/logback.xml b/maven-modules/animal-sniffer-mvn-plugin/src/main/resources/logback.xml similarity index 100% rename from animal-sniffer-mvn-plugin/src/main/resources/logback.xml rename to maven-modules/animal-sniffer-mvn-plugin/src/main/resources/logback.xml diff --git a/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java b/maven-modules/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java similarity index 100% rename from animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java rename to maven-modules/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java diff --git a/maven-archetype/README.md b/maven-modules/maven-archetype/README.md similarity index 100% rename from maven-archetype/README.md rename to maven-modules/maven-archetype/README.md diff --git a/maven-archetype/pom.xml b/maven-modules/maven-archetype/pom.xml similarity index 100% rename from maven-archetype/pom.xml rename to maven-modules/maven-archetype/pom.xml diff --git a/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml b/maven-modules/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml similarity index 100% rename from maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml rename to maven-modules/maven-archetype/src/main/resources/META-INF/maven/archetype-metadata.xml diff --git a/maven-archetype/src/main/resources/archetype-resources/pom.xml b/maven-modules/maven-archetype/src/main/resources/archetype-resources/pom.xml similarity index 100% rename from maven-archetype/src/main/resources/archetype-resources/pom.xml rename to maven-modules/maven-archetype/src/main/resources/archetype-resources/pom.xml diff --git a/maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java b/maven-modules/maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java similarity index 100% rename from maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java rename to maven-modules/maven-archetype/src/main/resources/archetype-resources/src/main/java/AppConfig.java diff --git a/maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java b/maven-modules/maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java similarity index 100% rename from maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java rename to maven-modules/maven-archetype/src/main/resources/archetype-resources/src/main/java/PingResource.java diff --git a/maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml b/maven-modules/maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml similarity index 100% rename from maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml rename to maven-modules/maven-archetype/src/main/resources/archetype-resources/src/main/liberty/config/server.xml diff --git a/maven-archetype/src/main/resources/logback.xml b/maven-modules/maven-archetype/src/main/resources/logback.xml similarity index 100% rename from maven-archetype/src/main/resources/logback.xml rename to maven-modules/maven-archetype/src/main/resources/logback.xml diff --git a/maven-polyglot/README.md b/maven-modules/maven-polyglot/README.md similarity index 100% rename from maven-polyglot/README.md rename to maven-modules/maven-polyglot/README.md diff --git a/maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml b/maven-modules/maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml similarity index 100% rename from maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml rename to maven-modules/maven-polyglot/maven-polyglot-json-app/.mvn/extensions.xml diff --git a/maven-polyglot/maven-polyglot-json-app/pom.json b/maven-modules/maven-polyglot/maven-polyglot-json-app/pom.json similarity index 100% rename from maven-polyglot/maven-polyglot-json-app/pom.json rename to maven-modules/maven-polyglot/maven-polyglot-json-app/pom.json diff --git a/maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java b/maven-modules/maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java similarity index 100% rename from maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java rename to maven-modules/maven-polyglot/maven-polyglot-json-app/src/main/java/com/baeldung/maven/polyglot/MavenPolyglotApplication.java diff --git a/maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json b/maven-modules/maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json similarity index 100% rename from maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json rename to maven-modules/maven-polyglot/maven-polyglot-json-app/src/main/resources/model.json diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-modules/maven-polyglot/maven-polyglot-json-extension/pom.xml similarity index 94% rename from maven-polyglot/maven-polyglot-json-extension/pom.xml rename to maven-modules/maven-polyglot/maven-polyglot-json-extension/pom.xml index 13d0b2099b..ade8974e0e 100644 --- a/maven-polyglot/maven-polyglot-json-extension/pom.xml +++ b/maven-modules/maven-polyglot/maven-polyglot-json-extension/pom.xml @@ -10,8 +10,8 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + maven-modules + 0.0.1-SNAPSHOT ../.. diff --git a/maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java b/maven-modules/maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java similarity index 100% rename from maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java rename to maven-modules/maven-polyglot/maven-polyglot-json-extension/src/main/java/com/demo/polyglot/CustomModelProcessor.java diff --git a/maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml b/maven-modules/maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml similarity index 100% rename from maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml rename to maven-modules/maven-polyglot/maven-polyglot-yml-app/.mvn/extensions.xml diff --git a/maven-polyglot/maven-polyglot-yml-app/pom.yml b/maven-modules/maven-polyglot/maven-polyglot-yml-app/pom.yml similarity index 100% rename from maven-polyglot/maven-polyglot-yml-app/pom.yml rename to maven-modules/maven-polyglot/maven-polyglot-yml-app/pom.yml diff --git a/maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java b/maven-modules/maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java similarity index 100% rename from maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java rename to maven-modules/maven-polyglot/maven-polyglot-yml-app/src/main/java/com/baeldung/maven/polyglot/YamlDemoApplication.java diff --git a/maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json b/maven-modules/maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json similarity index 100% rename from maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json rename to maven-modules/maven-polyglot/maven-polyglot-yml-app/src/main/resources/model.json diff --git a/maven-polyglot/pom.xml b/maven-modules/maven-polyglot/pom.xml similarity index 88% rename from maven-polyglot/pom.xml rename to maven-modules/maven-polyglot/pom.xml index 496ce58bf2..7ff375b9ba 100644 --- a/maven-polyglot/pom.xml +++ b/maven-modules/maven-polyglot/pom.xml @@ -10,8 +10,8 @@ com.baeldung - parent-modules - 1.0.0-SNAPSHOT + maven-modules + 0.0.1-SNAPSHOT diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml index 0d65e5f9f4..a9fefbbf5d 100644 --- a/maven-modules/pom.xml +++ b/maven-modules/pom.xml @@ -15,6 +15,8 @@ + animal-sniffer-mvn-plugin + maven-archetype maven-copy-files maven-custom-plugin @@ -23,6 +25,7 @@ maven-integration-test maven-multi-source maven-plugins + maven-polyglot maven-properties maven-unused-dependencies diff --git a/pom.xml b/pom.xml index 802f8ea43c..9670e57612 100644 --- a/pom.xml +++ b/pom.xml @@ -343,7 +343,6 @@ algorithms-searching algorithms-sorting algorithms-sorting-2 - animal-sniffer-mvn-plugin annotations antlr @@ -502,8 +501,6 @@ mapstruct maven-modules - maven-archetype - maven-polyglot mesos-marathon metrics @@ -820,7 +817,6 @@ algorithms-searching algorithms-sorting algorithms-sorting-2 - animal-sniffer-mvn-plugin annotations antlr @@ -981,8 +977,6 @@ mapstruct maven-modules - maven-archetype - maven-polyglot mesos-marathon metrics From 003d00daa9e5070f5f32bec31f81bc2031249b67 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Thu, 28 Apr 2022 17:12:20 +0100 Subject: [PATCH 18/35] [JAVA-8148] Fix code so application starts and some clean up --- .../reactive/webflux/EmployeeRepository.java | 44 ++++------- .../annotation/EmployeeSpringApplication.java | 7 ++ .../webflux/annotation/EmployeeWebClient.java | 12 +-- .../EmployeeControllerIntegrationTest.java | 76 ++++++++++++------- 4 files changed, 77 insertions(+), 62 deletions(-) diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java index 9aebc577b0..01d32ea57a 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/EmployeeRepository.java @@ -10,46 +10,32 @@ import java.util.Map; @Repository public class EmployeeRepository { - static Map employeeData; - - static Map employeeAccessData; + private static final Map EMPLOYEE_DATA; static { - employeeData = new HashMap<>(); - employeeData.put("1", new Employee("1", "Employee 1")); - employeeData.put("2", new Employee("2", "Employee 2")); - employeeData.put("3", new Employee("3", "Employee 3")); - employeeData.put("4", new Employee("4", "Employee 4")); - employeeData.put("5", new Employee("5", "Employee 5")); - employeeData.put("6", new Employee("6", "Employee 6")); - employeeData.put("7", new Employee("7", "Employee 7")); - employeeData.put("8", new Employee("8", "Employee 8")); - employeeData.put("9", new Employee("9", "Employee 9")); - employeeData.put("10", new Employee("10", "Employee 10")); - - employeeAccessData = new HashMap<>(); - employeeAccessData.put("1", "Employee 1 Access Key"); - employeeAccessData.put("2", "Employee 2 Access Key"); - employeeAccessData.put("3", "Employee 3 Access Key"); - employeeAccessData.put("4", "Employee 4 Access Key"); - employeeAccessData.put("5", "Employee 5 Access Key"); - employeeAccessData.put("6", "Employee 6 Access Key"); - employeeAccessData.put("7", "Employee 7 Access Key"); - employeeAccessData.put("8", "Employee 8 Access Key"); - employeeAccessData.put("9", "Employee 9 Access Key"); - employeeAccessData.put("10", "Employee 10 Access Key"); + EMPLOYEE_DATA = new HashMap<>(); + EMPLOYEE_DATA.put("1", new Employee("1", "Employee 1")); + EMPLOYEE_DATA.put("2", new Employee("2", "Employee 2")); + EMPLOYEE_DATA.put("3", new Employee("3", "Employee 3")); + EMPLOYEE_DATA.put("4", new Employee("4", "Employee 4")); + EMPLOYEE_DATA.put("5", new Employee("5", "Employee 5")); + EMPLOYEE_DATA.put("6", new Employee("6", "Employee 6")); + EMPLOYEE_DATA.put("7", new Employee("7", "Employee 7")); + EMPLOYEE_DATA.put("8", new Employee("8", "Employee 8")); + EMPLOYEE_DATA.put("9", new Employee("9", "Employee 9")); + EMPLOYEE_DATA.put("10", new Employee("10", "Employee 10")); } public Mono findEmployeeById(String id) { - return Mono.just(employeeData.get(id)); + return Mono.just(EMPLOYEE_DATA.get(id)); } public Flux findAllEmployees() { - return Flux.fromIterable(employeeData.values()); + return Flux.fromIterable(EMPLOYEE_DATA.values()); } public Mono updateEmployee(Employee employee) { - Employee existingEmployee = employeeData.get(employee.getId()); + Employee existingEmployee = EMPLOYEE_DATA.get(employee.getId()); if (existingEmployee != null) { existingEmployee.setName(employee.getName()); } diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeSpringApplication.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeSpringApplication.java index f1d21bdc77..0e3cc6bf99 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeSpringApplication.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeSpringApplication.java @@ -1,12 +1,19 @@ package com.baeldung.reactive.webflux.annotation; +import com.baeldung.reactive.webflux.EmployeeRepository; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration; +import org.springframework.context.annotation.Bean; @SpringBootApplication(exclude = MongoReactiveAutoConfiguration.class) public class EmployeeSpringApplication { + @Bean + EmployeeRepository employeeRepository() { + return new EmployeeRepository(); + } + public static void main(String[] args) { SpringApplication.run(EmployeeSpringApplication.class, args); diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebClient.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebClient.java index 611a261a1b..62978e1f58 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebClient.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebClient.java @@ -10,9 +10,9 @@ import reactor.core.publisher.Mono; public class EmployeeWebClient { private static final Logger LOGGER = LoggerFactory.getLogger(EmployeeWebClient.class); - + WebClient client = WebClient.create("http://localhost:8080"); - + public void consume() { Mono employeeMono = client.get() @@ -20,13 +20,13 @@ public class EmployeeWebClient { .retrieve() .bodyToMono(Employee.class); - employeeMono.subscribe(employee -> LOGGER.debug("Employee: {}", employee)); - + employeeMono.subscribe(employee -> LOGGER.info("Employee: {}", employee)); + Flux employeeFlux = client.get() .uri("/employees") .retrieve() .bodyToFlux(Employee.class); - - employeeFlux.subscribe(employee -> LOGGER.debug("Employee: {}", employee)); + + employeeFlux.subscribe(employee -> LOGGER.info("Employee: {}", employee)); } } \ No newline at end of file diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webflux/annotation/EmployeeControllerIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webflux/annotation/EmployeeControllerIntegrationTest.java index 24c4303e83..c4a11e7f3b 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/webflux/annotation/EmployeeControllerIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/webflux/annotation/EmployeeControllerIntegrationTest.java @@ -2,27 +2,27 @@ package com.baeldung.reactive.webflux.annotation; import com.baeldung.reactive.webflux.Employee; import com.baeldung.reactive.webflux.EmployeeRepository; -import com.baeldung.reactive.webflux.annotation.EmployeeSpringApplication; -import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes= EmployeeSpringApplication.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@SpringBootTest(webEnvironment = RANDOM_PORT, classes= EmployeeSpringApplication.class) public class EmployeeControllerIntegrationTest { @Autowired @@ -35,40 +35,62 @@ public class EmployeeControllerIntegrationTest { public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() { Employee employee = new Employee("1", "Employee 1 Name"); - + given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee)); + testClient.get() .uri("/employees/1") .exchange() - .expectStatus() - .isOk() - .expectBody(Employee.class) - .isEqualTo(employee); + .expectStatus().isOk() + .expectBody(Employee.class).isEqualTo(employee); } @Test public void whenGetAllEmployees_thenCorrectEmployees() { - - List employeeList = new ArrayList<>(); - - Employee employee1 = new Employee("1", "Employee 1 Name"); - Employee employee2 = new Employee("2", "Employee 2 Name"); - Employee employee3 = new Employee("3", "Employee 3 Name"); - - employeeList.add(employee1); - employeeList.add(employee2); - employeeList.add(employee3); - + List employeeList = Arrays.asList( + new Employee("1", "Employee 1 Name"), + new Employee("2", "Employee 2 Name"), + new Employee("3", "Employee 3 Name") + ); Flux employeeFlux = Flux.fromIterable(employeeList); given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); + testClient.get() .uri("/employees") .exchange() - .expectStatus() - .isOk() - .expectBodyList(Employee.class) - .hasSize(3) - .isEqualTo(employeeList); + .expectStatus().isOk() + .expectBodyList(Employee.class).isEqualTo(employeeList); + } + + @Test + @WithMockUser(username = "admin", roles = {"ADMIN"}) + public void givenValidUser_whenUpdateEmployee_thenEmployeeUpdated() { + Employee employee = new Employee("10", "Employee 10 Updated"); + + given(employeeRepository.updateEmployee(employee)).willReturn(Mono.just(employee)); + + testClient.post() + .uri("/employees/update") + .body(Mono.just(employee), Employee.class) + .exchange() + .expectStatus().isOk() + .expectBody(Employee.class).isEqualTo(employee); + + verify(employeeRepository).updateEmployee(employee); + } + + @Test + @WithMockUser + public void givenInvalidUser_whenUpdateEmployee_thenForbidden() { + Employee employee = new Employee("10", "Employee 10 Updated"); + + testClient.post() + .uri("/employees/update") + .body(Mono.just(employee), Employee.class) + .exchange() + .expectStatus().isForbidden(); + + verifyNoInteractions(employeeRepository); } } From 39f17dd3d13ffe470e4c0e48961761427dadaa03 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Thu, 28 Apr 2022 17:20:37 +0100 Subject: [PATCH 19/35] [JAVA-8148] Code clean up --- .../baeldung/reactive/webflux/Employee.java | 4 +- .../webflux/annotation/EmployeeWebClient.java | 14 ++--- .../annotation/EmployeeWebSecurityConfig.java | 30 +++++------ .../functional/EmployeeFunctionalConfig.java | 51 +++++++++--------- .../EmployeeControllerIntegrationTest.java | 20 +++---- ...ployeeSpringFunctionalIntegrationTest.java | 52 ++++++++----------- 6 files changed, 80 insertions(+), 91 deletions(-) diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java index d41a4f2791..dd88dcb668 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/Employee.java @@ -11,7 +11,5 @@ public class Employee { private String id; private String name; - - // standard getters and setters - + } diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebClient.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebClient.java index 62978e1f58..5ae193dc7c 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebClient.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebClient.java @@ -16,17 +16,17 @@ public class EmployeeWebClient { public void consume() { Mono employeeMono = client.get() - .uri("/employees/{id}", "1") - .retrieve() - .bodyToMono(Employee.class); + .uri("/employees/{id}", "1") + .retrieve() + .bodyToMono(Employee.class); employeeMono.subscribe(employee -> LOGGER.info("Employee: {}", employee)); Flux employeeFlux = client.get() - .uri("/employees") - .retrieve() - .bodyToFlux(Employee.class); + .uri("/employees") + .retrieve() + .bodyToFlux(Employee.class); employeeFlux.subscribe(employee -> LOGGER.info("Employee: {}", employee)); } -} \ No newline at end of file +} diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebSecurityConfig.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebSecurityConfig.java index 8dfa455ce3..fc98b70c0f 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebSecurityConfig.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/annotation/EmployeeWebSecurityConfig.java @@ -13,33 +13,31 @@ import org.springframework.security.web.server.SecurityWebFilterChain; @EnableWebFluxSecurity public class EmployeeWebSecurityConfig { - + @Bean public MapReactiveUserDetailsService userDetailsService() { UserDetails user = User - .withUsername("admin") - .password(passwordEncoder().encode("password")) - .roles("ADMIN") - .build(); + .withUsername("admin") + .password(passwordEncoder().encode("password")) + .roles("ADMIN") + .build(); return new MapReactiveUserDetailsService(user); } @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http.csrf() - .disable() - .authorizeExchange() - .pathMatchers(HttpMethod.POST, "/employees/update") - .hasRole("ADMIN") - .pathMatchers("/**") - .permitAll() - .and() - .httpBasic(); + http + .csrf().disable() + .authorizeExchange() + .pathMatchers(HttpMethod.POST, "/employees/update").hasRole("ADMIN") + .pathMatchers("/**").permitAll() + .and() + .httpBasic(); return http.build(); } - + @Bean public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); + return new BCryptPasswordEncoder(); } } diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/functional/EmployeeFunctionalConfig.java b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/functional/EmployeeFunctionalConfig.java index f97d40e4e7..8b5c7233d6 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webflux/functional/EmployeeFunctionalConfig.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webflux/functional/EmployeeFunctionalConfig.java @@ -25,50 +25,49 @@ public class EmployeeFunctionalConfig { @Bean RouterFunction getAllEmployeesRoute() { - return route(GET("/employees"), - req -> ok().body( - employeeRepository().findAllEmployees(), Employee.class)); + return route(GET("/employees"), + req -> ok().body( + employeeRepository().findAllEmployees(), Employee.class)); } @Bean RouterFunction getEmployeeByIdRoute() { - return route(GET("/employees/{id}"), - req -> ok().body( - employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class)); + return route(GET("/employees/{id}"), + req -> ok().body( + employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class)); } @Bean RouterFunction updateEmployeeRoute() { - return route(POST("/employees/update"), - req -> req.body(toMono(Employee.class)) - .doOnNext(employeeRepository()::updateEmployee) - .then(ok().build())); + return route(POST("/employees/update"), + req -> req.body(toMono(Employee.class)) + .doOnNext(employeeRepository()::updateEmployee) + .then(ok().build())); } @Bean RouterFunction composedRoutes() { - return - route(GET("/employees"), + return + route(GET("/employees"), req -> ok().body( employeeRepository().findAllEmployees(), Employee.class)) - - .and(route(GET("/employees/{id}"), - req -> ok().body( - employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class))) - - .and(route(POST("/employees/update"), - req -> req.body(toMono(Employee.class)) - .doOnNext(employeeRepository()::updateEmployee) - .then(ok().build()))); + + .and(route(GET("/employees/{id}"), + req -> ok().body( + employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class))) + + .and(route(POST("/employees/update"), + req -> req.body(toMono(Employee.class)) + .doOnNext(employeeRepository()::updateEmployee) + .then(ok().build()))); } @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { - http.csrf() - .disable() - .authorizeExchange() - .anyExchange() - .permitAll(); + http + .csrf().disable() + .authorizeExchange() + .anyExchange().permitAll(); return http.build(); } } diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webflux/annotation/EmployeeControllerIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webflux/annotation/EmployeeControllerIntegrationTest.java index c4a11e7f3b..699bc9c154 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/webflux/annotation/EmployeeControllerIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/webflux/annotation/EmployeeControllerIntegrationTest.java @@ -22,7 +22,7 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = RANDOM_PORT, classes= EmployeeSpringApplication.class) +@SpringBootTest(webEnvironment = RANDOM_PORT, classes = EmployeeSpringApplication.class) public class EmployeeControllerIntegrationTest { @Autowired @@ -39,10 +39,10 @@ public class EmployeeControllerIntegrationTest { given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee)); testClient.get() - .uri("/employees/1") - .exchange() - .expectStatus().isOk() - .expectBody(Employee.class).isEqualTo(employee); + .uri("/employees/1") + .exchange() + .expectStatus().isOk() + .expectBody(Employee.class).isEqualTo(employee); } @Test @@ -57,14 +57,14 @@ public class EmployeeControllerIntegrationTest { given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); testClient.get() - .uri("/employees") - .exchange() - .expectStatus().isOk() - .expectBodyList(Employee.class).isEqualTo(employeeList); + .uri("/employees") + .exchange() + .expectStatus().isOk() + .expectBodyList(Employee.class).isEqualTo(employeeList); } @Test - @WithMockUser(username = "admin", roles = {"ADMIN"}) + @WithMockUser(username = "admin", roles = { "ADMIN" }) public void givenValidUser_whenUpdateEmployee_thenEmployeeUpdated() { Employee employee = new Employee("10", "Employee 10 Updated"); diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webflux/functional/EmployeeSpringFunctionalIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webflux/functional/EmployeeSpringFunctionalIntegrationTest.java index da866724cc..198ec0d081 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/webflux/functional/EmployeeSpringFunctionalIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/webflux/functional/EmployeeSpringFunctionalIntegrationTest.java @@ -2,10 +2,8 @@ package com.baeldung.reactive.webflux.functional; import com.baeldung.reactive.webflux.Employee; import com.baeldung.reactive.webflux.EmployeeRepository; -import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; @@ -19,10 +17,10 @@ import java.util.List; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@SpringBootTest(webEnvironment = RANDOM_PORT, classes = EmployeeSpringFunctionalApplication.class) public class EmployeeSpringFunctionalIntegrationTest { @Autowired @@ -34,58 +32,54 @@ public class EmployeeSpringFunctionalIntegrationTest { @Test public void givenEmployeeId_whenGetEmployeeById_thenCorrectEmployee() { WebTestClient client = WebTestClient - .bindToRouterFunction(config.getEmployeeByIdRoute()) - .build(); + .bindToRouterFunction(config.getEmployeeByIdRoute()) + .build(); Employee employee = new Employee("1", "Employee 1"); given(employeeRepository.findEmployeeById("1")).willReturn(Mono.just(employee)); client.get() - .uri("/employees/1") - .exchange() - .expectStatus() - .isOk() - .expectBody(Employee.class) - .isEqualTo(employee); + .uri("/employees/1") + .exchange() + .expectStatus().isOk() + .expectBody(Employee.class).isEqualTo(employee); } @Test public void whenGetAllEmployees_thenCorrectEmployees() { WebTestClient client = WebTestClient - .bindToRouterFunction(config.getAllEmployeesRoute()) - .build(); + .bindToRouterFunction(config.getAllEmployeesRoute()) + .build(); List employees = Arrays.asList( - new Employee("1", "Employee 1"), - new Employee("2", "Employee 2")); + new Employee("1", "Employee 1"), + new Employee("2", "Employee 2") + ); Flux employeeFlux = Flux.fromIterable(employees); given(employeeRepository.findAllEmployees()).willReturn(employeeFlux); client.get() - .uri("/employees") - .exchange() - .expectStatus() - .isOk() - .expectBodyList(Employee.class) - .isEqualTo(employees); + .uri("/employees") + .exchange() + .expectStatus().isOk() + .expectBodyList(Employee.class).isEqualTo(employees); } @Test public void whenUpdateEmployee_thenEmployeeUpdated() { WebTestClient client = WebTestClient - .bindToRouterFunction(config.updateEmployeeRoute()) - .build(); + .bindToRouterFunction(config.updateEmployeeRoute()) + .build(); Employee employee = new Employee("1", "Employee 1 Updated"); client.post() - .uri("/employees/update") - .body(Mono.just(employee), Employee.class) - .exchange() - .expectStatus() - .isOk(); + .uri("/employees/update") + .body(Mono.just(employee), Employee.class) + .exchange() + .expectStatus().isOk(); verify(employeeRepository).updateEmployee(employee); } From 4690807a092e40d216c4e1083961120712966a28 Mon Sep 17 00:00:00 2001 From: freelansam <79205526+freelansam@users.noreply.github.com> Date: Thu, 28 Apr 2022 22:45:45 +0530 Subject: [PATCH 20/35] JAVA-11420: Dissolve spring-boot-1 and spring-boot-2 inside (#12122) spring-boot-modules --- spring-4/README.md | 1 + spring-4/pom.xml | 4 + .../com/baeldung/actuator/CustomEndpoint.java | 0 .../com/baeldung/actuator/HealthCheck.java | 0 .../baeldung/actuator/LoginServiceImpl.java | 0 .../com/baeldung/actuator/SpringBoot.java | 0 .../src/main/resources/application.properties | 21 ++ .../CustomEndpointIntegrationTest.java | 0 .../actuator/HealthCheckIntegrationTest.java | 0 .../actuator/HealthCheckUnitTest.java | 0 .../actuator/LoginServiceIntegrationTest.java | 0 .../actuator/LoginServiceUnitTest.java | 0 spring-boot-modules/pom.xml | 2 - .../.mvn/wrapper/maven-wrapper.properties | 1 - spring-boot-modules/spring-boot-1/README.md | 11 - spring-boot-modules/spring-boot-1/mvnw | 234 ------------- spring-boot-modules/spring-boot-1/mvnw.cmd | 143 -------- spring-boot-modules/spring-boot-1/pom.xml | 74 ----- .../src/main/resources/application.properties | 19 -- .../src/main/resources/logback.xml | 13 - .../src/test/resources/logback-test.xml | 12 - .../.mvn/wrapper/MavenWrapperDownloader.java | 117 ------- .../.mvn/wrapper/maven-wrapper.properties | 2 - spring-boot-modules/spring-boot-2/README.md | 3 - spring-boot-modules/spring-boot-2/mvnw | 310 ------------------ spring-boot-modules/spring-boot-2/mvnw.cmd | 182 ---------- spring-boot-modules/spring-boot-2/pom.xml | 71 ---- .../src/main/resources/application.properties | 3 - .../README.md | 3 +- .../spring-boot-basic-customization-2/pom.xml | 28 +- .../springStart/SpringStartApplication.java | 0 .../src/main/resources/application.properties | 7 +- .../spring-boot-data-2/README.md | 2 + .../spring-boot-data-2/pom.xml | 10 +- .../dynamicvalidation/ContactInfo.java | 0 .../ContactInfoValidator.java | 0 .../DynamicValidationApp.java | 0 .../config/CustomerController.java | 0 .../config/PersistenceConfig.java | 0 .../dao/ContactInfoExpressionRepository.java | 0 .../model/ContactInfoExpression.java | 0 .../dynamicvalidation/model/Customer.java | 0 .../src/main/resources/data-expressions.sql | 6 + .../src/main/resources/schema-expressions.sql | 5 + .../main/resources/templates/customer.html | 0 .../src/test/resources/application.properties | 0 .../spring-boot-deployment/README.md | 1 + .../ShutdownHookApplication.java | 0 .../baeldung/shutdownhooks/beans/Bean1.java | 0 .../baeldung/shutdownhooks/beans/Bean2.java | 0 .../baeldung/shutdownhooks/beans/Bean3.java | 0 .../config/ExampleServletContextListener.java | 0 .../config/ShutdownHookConfiguration.java | 0 .../spring-boot-mvc-4/README.md | 1 + .../WarInitializerApplication.java | 2 +- ...InitializerApplicationIntegrationTest.java | 0 56 files changed, 85 insertions(+), 1203 deletions(-) rename {spring-boot-modules/spring-boot-1 => spring-4}/src/main/java/com/baeldung/actuator/CustomEndpoint.java (100%) rename {spring-boot-modules/spring-boot-1 => spring-4}/src/main/java/com/baeldung/actuator/HealthCheck.java (100%) rename {spring-boot-modules/spring-boot-1 => spring-4}/src/main/java/com/baeldung/actuator/LoginServiceImpl.java (100%) rename {spring-boot-modules/spring-boot-1 => spring-4}/src/main/java/com/baeldung/actuator/SpringBoot.java (100%) rename {spring-boot-modules/spring-boot-1 => spring-4}/src/test/java/com/baeldung/actuator/CustomEndpointIntegrationTest.java (100%) rename {spring-boot-modules/spring-boot-1 => spring-4}/src/test/java/com/baeldung/actuator/HealthCheckIntegrationTest.java (100%) rename {spring-boot-modules/spring-boot-1 => spring-4}/src/test/java/com/baeldung/actuator/HealthCheckUnitTest.java (100%) rename {spring-boot-modules/spring-boot-1 => spring-4}/src/test/java/com/baeldung/actuator/LoginServiceIntegrationTest.java (100%) rename {spring-boot-modules/spring-boot-1 => spring-4}/src/test/java/com/baeldung/actuator/LoginServiceUnitTest.java (100%) delete mode 100644 spring-boot-modules/spring-boot-1/.mvn/wrapper/maven-wrapper.properties delete mode 100644 spring-boot-modules/spring-boot-1/README.md delete mode 100755 spring-boot-modules/spring-boot-1/mvnw delete mode 100644 spring-boot-modules/spring-boot-1/mvnw.cmd delete mode 100644 spring-boot-modules/spring-boot-1/pom.xml delete mode 100644 spring-boot-modules/spring-boot-1/src/main/resources/application.properties delete mode 100644 spring-boot-modules/spring-boot-1/src/main/resources/logback.xml delete mode 100644 spring-boot-modules/spring-boot-1/src/test/resources/logback-test.xml delete mode 100644 spring-boot-modules/spring-boot-2/.mvn/wrapper/MavenWrapperDownloader.java delete mode 100644 spring-boot-modules/spring-boot-2/.mvn/wrapper/maven-wrapper.properties delete mode 100644 spring-boot-modules/spring-boot-2/README.md delete mode 100644 spring-boot-modules/spring-boot-2/mvnw delete mode 100644 spring-boot-modules/spring-boot-2/mvnw.cmd delete mode 100644 spring-boot-modules/spring-boot-2/pom.xml delete mode 100644 spring-boot-modules/spring-boot-2/src/main/resources/application.properties rename spring-boot-modules/{spring-boot-2 => spring-boot-basic-customization-2}/src/main/java/com/baeldung/springStart/SpringStartApplication.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-data-2}/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-data-2}/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-data-2}/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-data-2}/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-data-2}/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-data-2}/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-data-2}/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-data-2}/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java (100%) create mode 100644 spring-boot-modules/spring-boot-data-2/src/main/resources/data-expressions.sql create mode 100644 spring-boot-modules/spring-boot-data-2/src/main/resources/schema-expressions.sql rename spring-boot-modules/{spring-boot-1 => spring-boot-data-2}/src/main/resources/templates/customer.html (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-data-2}/src/test/resources/application.properties (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-deployment}/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-deployment}/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-deployment}/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-deployment}/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-deployment}/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-deployment}/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java (100%) rename spring-boot-modules/{spring-boot-1 => spring-boot-mvc-4}/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java (93%) rename spring-boot-modules/{spring-boot-1 => spring-boot-mvc-4}/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java (100%) diff --git a/spring-4/README.md b/spring-4/README.md index 46d9b71e5c..add82c7e00 100644 --- a/spring-4/README.md +++ b/spring-4/README.md @@ -7,3 +7,4 @@ This module contains articles about Spring 4 - [Configuring a Hikari Connection Pool with Spring Boot](https://www.baeldung.com/spring-boot-hikari) - [Spring JSON-P with Jackson](https://www.baeldung.com/spring-jackson-jsonp) - [What’s New in Spring 4.3?](https://www.baeldung.com/whats-new-in-spring-4-3) +- [Spring Boot Actuator](https://www.baeldung.com/spring-boot-actuators) diff --git a/spring-4/pom.xml b/spring-4/pom.xml index 5887bd43e2..681747c1f6 100644 --- a/spring-4/pom.xml +++ b/spring-4/pom.xml @@ -31,6 +31,10 @@ + + org.springframework.boot + spring-boot-starter-actuator + com.h2database h2 diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/CustomEndpoint.java b/spring-4/src/main/java/com/baeldung/actuator/CustomEndpoint.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/CustomEndpoint.java rename to spring-4/src/main/java/com/baeldung/actuator/CustomEndpoint.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/HealthCheck.java b/spring-4/src/main/java/com/baeldung/actuator/HealthCheck.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/HealthCheck.java rename to spring-4/src/main/java/com/baeldung/actuator/HealthCheck.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/LoginServiceImpl.java b/spring-4/src/main/java/com/baeldung/actuator/LoginServiceImpl.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/LoginServiceImpl.java rename to spring-4/src/main/java/com/baeldung/actuator/LoginServiceImpl.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/SpringBoot.java b/spring-4/src/main/java/com/baeldung/actuator/SpringBoot.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/actuator/SpringBoot.java rename to spring-4/src/main/java/com/baeldung/actuator/SpringBoot.java diff --git a/spring-4/src/main/resources/application.properties b/spring-4/src/main/resources/application.properties index e67700b7be..ca6dbb5580 100644 --- a/spring-4/src/main/resources/application.properties +++ b/spring-4/src/main/resources/application.properties @@ -3,3 +3,24 @@ feature.new.foo=Y last.active.after=2018-03-14T00:00:00Z first.active.after=2999-03-15T00:00:00Z logging.level.org.flips=info + +#actuator properties +### server port +server.port=8080 +#port used to expose actuator +management.port=8081 +#CIDR allowed to hit actuator +management.address=127.0.0.1 +# Actuator Configuration +# customize /beans endpoint +endpoints.beans.id=springbeans +endpoints.beans.sensitive=false +endpoints.beans.enabled=true +# for the Spring Boot version 1.5.0 and above, we have to disable security to expose the health endpoint fully for unauthorized access. +# see: https://docs.spring.io/spring-boot/docs/1.5.x/reference/html/production-ready-monitoring.html +management.security.enabled=false +endpoints.health.sensitive=false +# customize /info endpoint +info.app.name=Spring Sample Application +info.app.description=This is my first spring boot application +info.app.version=1.0.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/CustomEndpointIntegrationTest.java b/spring-4/src/test/java/com/baeldung/actuator/CustomEndpointIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/CustomEndpointIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/actuator/CustomEndpointIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/HealthCheckIntegrationTest.java b/spring-4/src/test/java/com/baeldung/actuator/HealthCheckIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/HealthCheckIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/actuator/HealthCheckIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/HealthCheckUnitTest.java b/spring-4/src/test/java/com/baeldung/actuator/HealthCheckUnitTest.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/HealthCheckUnitTest.java rename to spring-4/src/test/java/com/baeldung/actuator/HealthCheckUnitTest.java diff --git a/spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/LoginServiceIntegrationTest.java b/spring-4/src/test/java/com/baeldung/actuator/LoginServiceIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/LoginServiceIntegrationTest.java rename to spring-4/src/test/java/com/baeldung/actuator/LoginServiceIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/LoginServiceUnitTest.java b/spring-4/src/test/java/com/baeldung/actuator/LoginServiceUnitTest.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/actuator/LoginServiceUnitTest.java rename to spring-4/src/test/java/com/baeldung/actuator/LoginServiceUnitTest.java diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 939add1147..003a52db13 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -17,8 +17,6 @@ - spring-boot-1 - spring-boot-2 spring-boot-admin spring-boot-angular spring-boot-annotations diff --git a/spring-boot-modules/spring-boot-1/.mvn/wrapper/maven-wrapper.properties b/spring-boot-modules/spring-boot-1/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 9dda3b659b..0000000000 --- a/spring-boot-modules/spring-boot-1/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1 +0,0 @@ -distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip diff --git a/spring-boot-modules/spring-boot-1/README.md b/spring-boot-modules/spring-boot-1/README.md deleted file mode 100644 index 8e5214c69a..0000000000 --- a/spring-boot-modules/spring-boot-1/README.md +++ /dev/null @@ -1,11 +0,0 @@ -## Spring Boot 1.x Actuator - -This module contains articles about Spring Boot Actuator in Spring Boot version 1.x. - -## Relevant articles: -- [Spring Boot Actuator](https://www.baeldung.com/spring-boot-actuators) -- [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer) -- [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks) -- [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) - - diff --git a/spring-boot-modules/spring-boot-1/mvnw b/spring-boot-modules/spring-boot-1/mvnw deleted file mode 100755 index b74391fdf4..0000000000 --- a/spring-boot-modules/spring-boot-1/mvnw +++ /dev/null @@ -1,234 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven2 Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ]; then - - if [ -f /etc/mavenrc ]; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ]; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false -darwin=false -mingw=false -case "$(uname)" in -CYGWIN*) cygwin=true ;; -MINGW*) mingw=true ;; -Darwin*) - darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="$(/usr/libexec/java_home)" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ]; then - if [ -r /etc/gentoo-release ]; then - JAVA_HOME=$(java-config --jre-home) - fi -fi - -if [ -z "$M2_HOME" ]; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ]; do - ls=$(ls -ld "$PRG") - link=$(expr "$ls" : '.*-> \(.*\)$') - if expr "$link" : '/.*' >/dev/null; then - PRG="$link" - else - PRG="$(dirname "$PRG")/$link" - fi - done - - saveddir=$(pwd) - - M2_HOME=$(dirname "$PRG")/.. - - # make it fully qualified - M2_HOME=$(cd "$M2_HOME" && pwd) - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=$(cygpath --unix "$M2_HOME") - [ -n "$JAVA_HOME" ] && - JAVA_HOME=$(cygpath --unix "$JAVA_HOME") - [ -n "$CLASSPATH" ] && - CLASSPATH=$(cygpath --path --unix "$CLASSPATH") -fi - -# For Migwn, ensure paths are in UNIX format before anything is touched -if $mingw; then - [ -n "$M2_HOME" ] && - M2_HOME="$( ( - cd "$M2_HOME" - pwd - ))" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="$( ( - cd "$JAVA_HOME" - pwd - ))" - # TODO classpath? -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="$(which javac)" - if [ -n "$javaExecutable" ] && ! [ "$(expr \"$javaExecutable\" : '\([^ ]*\)')" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=$(which readlink) - if [ ! $(expr "$readLink" : '\([^ ]*\)') = "no" ]; then - if $darwin; then - javaHome="$(dirname \"$javaExecutable\")" - javaExecutable="$(cd \"$javaHome\" && pwd -P)/javac" - else - javaExecutable="$(readlink -f \"$javaExecutable\")" - fi - javaHome="$(dirname \"$javaExecutable\")" - javaHome=$(expr "$javaHome" : '\(.*\)/bin') - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ]; then - if [ -n "$JAVA_HOME" ]; then - if [ -x "$JAVA_HOME/jre/sh/java" ]; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="$(which java)" - fi -fi - -if [ ! -x "$JAVACMD" ]; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ]; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ]; then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ]; do - if [ -d "$wdir"/.mvn ]; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=$( - cd "$wdir/.." - pwd - ) - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' <"$1")" - fi -} - -BASE_DIR=$(find_maven_basedir "$(pwd)") -if [ -z "$BASE_DIR" ]; then - exit 1 -fi - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -echo $MAVEN_PROJECTBASEDIR -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=$(cygpath --path --windows "$M2_HOME") - [ -n "$JAVA_HOME" ] && - JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") - [ -n "$CLASSPATH" ] && - CLASSPATH=$(cygpath --path --windows "$CLASSPATH") - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") -fi - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/spring-boot-modules/spring-boot-1/mvnw.cmd b/spring-boot-modules/spring-boot-1/mvnw.cmd deleted file mode 100644 index 019bd74d76..0000000000 --- a/spring-boot-modules/spring-boot-1/mvnw.cmd +++ /dev/null @@ -1,143 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven2 Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" - -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/spring-boot-modules/spring-boot-1/pom.xml b/spring-boot-modules/spring-boot-1/pom.xml deleted file mode 100644 index 594e6459a4..0000000000 --- a/spring-boot-modules/spring-boot-1/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - 4.0.0 - spring-boot-1 - jar - Module for Spring Boot version 1.x - - - - com.baeldung - parent-boot-1 - 0.0.1-SNAPSHOT - ../../parent-boot-1 - - - - - org.springframework.boot - spring-boot-starter - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-starter-data-jpa - - - org.apache.logging.log4j - log4j-core - ${log4j2.version} - - - com.h2database - h2 - test - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - - - - - 2.17.1 - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1/src/main/resources/application.properties b/spring-boot-modules/spring-boot-1/src/main/resources/application.properties deleted file mode 100644 index ac095e1cab..0000000000 --- a/spring-boot-modules/spring-boot-1/src/main/resources/application.properties +++ /dev/null @@ -1,19 +0,0 @@ -### server port -server.port=8080 -#port used to expose actuator -management.port=8081 -#CIDR allowed to hit actuator -management.address=127.0.0.1 -# Actuator Configuration -# customize /beans endpoint -endpoints.beans.id=springbeans -endpoints.beans.sensitive=false -endpoints.beans.enabled=true -# for the Spring Boot version 1.5.0 and above, we have to disable security to expose the health endpoint fully for unauthorized access. -# see: https://docs.spring.io/spring-boot/docs/1.5.x/reference/html/production-ready-monitoring.html -management.security.enabled=false -endpoints.health.sensitive=false -# customize /info endpoint -info.app.name=Spring Sample Application -info.app.description=This is my first spring boot application -info.app.version=1.0.0 \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1/src/main/resources/logback.xml b/spring-boot-modules/spring-boot-1/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-boot-modules/spring-boot-1/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1/src/test/resources/logback-test.xml b/spring-boot-modules/spring-boot-1/src/test/resources/logback-test.xml deleted file mode 100644 index 8d4771e308..0000000000 --- a/spring-boot-modules/spring-boot-1/src/test/resources/logback-test.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n - - - - - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-2/.mvn/wrapper/MavenWrapperDownloader.java b/spring-boot-modules/spring-boot-2/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index b901097f2d..0000000000 --- a/spring-boot-modules/spring-boot-2/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if(mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if(mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if(!outputFile.getParentFile().exists()) { - if(!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/spring-boot-modules/spring-boot-2/.mvn/wrapper/maven-wrapper.properties b/spring-boot-modules/spring-boot-2/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 642d572ce9..0000000000 --- a/spring-boot-modules/spring-boot-2/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/spring-boot-modules/spring-boot-2/README.md b/spring-boot-modules/spring-boot-2/README.md deleted file mode 100644 index 7ea97f80c5..0000000000 --- a/spring-boot-modules/spring-boot-2/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Speed up Spring Boot Startup Time](https://www.baeldung.com/spring-boot-startup-speed) diff --git a/spring-boot-modules/spring-boot-2/mvnw b/spring-boot-modules/spring-boot-2/mvnw deleted file mode 100644 index 41c0f0c23d..0000000000 --- a/spring-boot-modules/spring-boot-2/mvnw +++ /dev/null @@ -1,310 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/spring-boot-modules/spring-boot-2/mvnw.cmd b/spring-boot-modules/spring-boot-2/mvnw.cmd deleted file mode 100644 index 86115719e5..0000000000 --- a/spring-boot-modules/spring-boot-2/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@REM ---------------------------------------------------------------------------- -@REM Licensed to the Apache Software Foundation (ASF) under one -@REM or more contributor license agreements. See the NOTICE file -@REM distributed with this work for additional information -@REM regarding copyright ownership. The ASF licenses this file -@REM to you under the Apache License, Version 2.0 (the -@REM "License"); you may not use this file except in compliance -@REM with the License. You may obtain a copy of the License at -@REM -@REM http://www.apache.org/licenses/LICENSE-2.0 -@REM -@REM Unless required by applicable law or agreed to in writing, -@REM software distributed under the License is distributed on an -@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -@REM KIND, either express or implied. See the License for the -@REM specific language governing permissions and limitations -@REM under the License. -@REM ---------------------------------------------------------------------------- - -@REM ---------------------------------------------------------------------------- -@REM Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/spring-boot-modules/spring-boot-2/pom.xml b/spring-boot-modules/spring-boot-2/pom.xml deleted file mode 100644 index 0da07eaf00..0000000000 --- a/spring-boot-modules/spring-boot-2/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - spring-boot-2 - jar - Module for Spring Boot version 2.x - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - org.springframework.boot - spring-boot-starter-security - - - org.apache.logging.log4j - log4j-core - ${log4j2.version} - - - org.springframework - spring-context-indexer - ${spring-core.version} - true - - - - - - - org.springframework.boot - spring-boot-maven-plugin - ${spring-boot.version} - - springStartupApp - com.baeldung.springStart.SpringStartApplication - - - - - repackage - - - - - - - - - 2.17.1 - 5.3.15 - 11 - 11 - - - \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-2/src/main/resources/application.properties deleted file mode 100644 index 4a5f46a7b1..0000000000 --- a/spring-boot-modules/spring-boot-2/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -spring.main.lazy-initialization=true -logging.level.org.springframework.boot.autoconfigure=DEBUG -spring.jmx.enabled=false \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization-2/README.md b/spring-boot-modules/spring-boot-basic-customization-2/README.md index bfd24a0475..0f4167d25b 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/README.md +++ b/spring-boot-modules/spring-boot-basic-customization-2/README.md @@ -9,4 +9,5 @@ This module contains articles about Spring Boot customization 2 - [What Is OncePerRequestFilter?](https://www.baeldung.com/spring-onceperrequestfilter) - [Spring Boot Exit Codes](https://www.baeldung.com/spring-boot-exit-codes) - [Guide to Spring Type Conversions](https://www.baeldung.com/spring-type-conversions) - - [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) \ No newline at end of file + - [Container Configuration in Spring Boot 2](https://www.baeldung.com/embeddedservletcontainercustomizer-configurableembeddedservletcontainer-spring-boot) + - [Speed up Spring Boot Startup Time](https://www.baeldung.com/spring-boot-startup-speed) \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-basic-customization-2/pom.xml b/spring-boot-modules/spring-boot-basic-customization-2/pom.xml index b537f43c23..439051c7e6 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/pom.xml +++ b/spring-boot-modules/spring-boot-basic-customization-2/pom.xml @@ -23,7 +23,11 @@ org.springframework.boot spring-boot-starter-data-jpa - + + org.springframework.boot + spring-boot-starter-actuator + + com.h2database h2 @@ -31,11 +35,31 @@ org.springframework.boot spring-boot-starter-test - + com.google.guava guava ${guava.version} + + + + org.springframework.boot + spring-boot-maven-plugin + + springStartupApp + com.baeldung.springStart.SpringStartApplication + + + + + repackage + + + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-2/src/main/java/com/baeldung/springStart/SpringStartApplication.java b/spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/springStart/SpringStartApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-2/src/main/java/com/baeldung/springStart/SpringStartApplication.java rename to spring-boot-modules/spring-boot-basic-customization-2/src/main/java/com/baeldung/springStart/SpringStartApplication.java diff --git a/spring-boot-modules/spring-boot-basic-customization-2/src/main/resources/application.properties b/spring-boot-modules/spring-boot-basic-customization-2/src/main/resources/application.properties index ab9de92c82..370ea40d73 100644 --- a/spring-boot-modules/spring-boot-basic-customization-2/src/main/resources/application.properties +++ b/spring-boot-modules/spring-boot-basic-customization-2/src/main/resources/application.properties @@ -1 +1,6 @@ -sample=string loaded from properties! \ No newline at end of file +sample=string loaded from properties! + +#startup time properties +spring.main.lazy-initialization=true +logging.level.org.springframework.boot.autoconfigure=DEBUG +spring.jmx.enabled=false \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data-2/README.md b/spring-boot-modules/spring-boot-data-2/README.md index fd9d034f8a..e7d39a78e9 100644 --- a/spring-boot-modules/spring-boot-data-2/README.md +++ b/spring-boot-modules/spring-boot-data-2/README.md @@ -6,3 +6,5 @@ - [Creating a Read-Only Repository with Spring Data](https://www.baeldung.com/spring-data-read-only-repository) - [Using JaVers for Data Model Auditing in Spring Data](https://www.baeldung.com/spring-data-javers-audit) - [BootstrapMode for JPA Repositories](https://github.com/eugenp/tutorials/tree/master/spring-boot-modules/spring-boot-data-2) +- [Dynamic DTO Validation Config Retrieved from the Database](https://www.baeldung.com/spring-dynamic-dto-validation) + diff --git a/spring-boot-modules/spring-boot-data-2/pom.xml b/spring-boot-modules/spring-boot-data-2/pom.xml index ea5de6d4b5..cd03d1b9b1 100644 --- a/spring-boot-modules/spring-boot-data-2/pom.xml +++ b/spring-boot-modules/spring-boot-data-2/pom.xml @@ -16,6 +16,14 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-validation + org.springframework.boot spring-boot-starter-data-jpa @@ -31,7 +39,7 @@ runtime - + 6.5.3 diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/ContactInfo.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/config/CustomerController.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/config/PersistenceConfig.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/dao/ContactInfoExpressionRepository.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/model/ContactInfoExpression.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java b/spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java rename to spring-boot-modules/spring-boot-data-2/src/main/java/com/baeldung/dynamicvalidation/model/Customer.java diff --git a/spring-boot-modules/spring-boot-data-2/src/main/resources/data-expressions.sql b/spring-boot-modules/spring-boot-data-2/src/main/resources/data-expressions.sql new file mode 100644 index 0000000000..5a16ceceb9 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-2/src/main/resources/data-expressions.sql @@ -0,0 +1,6 @@ +insert into contact_info_expression values ('email', + '[a-z0-9!#$%&*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?') +insert into contact_info_expression values ('phone', + '^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})$') +insert into contact_info_expression values ('website', + '^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$') \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-data-2/src/main/resources/schema-expressions.sql b/spring-boot-modules/spring-boot-data-2/src/main/resources/schema-expressions.sql new file mode 100644 index 0000000000..532faefde1 --- /dev/null +++ b/spring-boot-modules/spring-boot-data-2/src/main/resources/schema-expressions.sql @@ -0,0 +1,5 @@ +CREATE TABLE contact_info_expression( + expression_type varchar(50) not null, + pattern varchar(500) not null, + PRIMARY KEY ( expression_type ) +); \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-1/src/main/resources/templates/customer.html b/spring-boot-modules/spring-boot-data-2/src/main/resources/templates/customer.html similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/resources/templates/customer.html rename to spring-boot-modules/spring-boot-data-2/src/main/resources/templates/customer.html diff --git a/spring-boot-modules/spring-boot-1/src/test/resources/application.properties b/spring-boot-modules/spring-boot-data-2/src/test/resources/application.properties similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/resources/application.properties rename to spring-boot-modules/spring-boot-data-2/src/test/resources/application.properties diff --git a/spring-boot-modules/spring-boot-deployment/README.md b/spring-boot-modules/spring-boot-deployment/README.md index 85f288d33b..125de43a88 100644 --- a/spring-boot-modules/spring-boot-deployment/README.md +++ b/spring-boot-modules/spring-boot-deployment/README.md @@ -7,3 +7,4 @@ This module contains articles about deployment of a Spring Boot Application - [Spring Boot Console Application](https://www.baeldung.com/spring-boot-console-app) - [Comparing Embedded Servlet Containers in Spring Boot](https://www.baeldung.com/spring-boot-servlet-containers) - [Graceful Shutdown of a Spring Boot Application](https://www.baeldung.com/spring-boot-graceful-shutdown) + - [Spring Shutdown Callbacks](https://www.baeldung.com/spring-shutdown-callbacks) diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/ShutdownHookApplication.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/beans/Bean1.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/beans/Bean2.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/beans/Bean3.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/config/ExampleServletContextListener.java diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java b/spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java rename to spring-boot-modules/spring-boot-deployment/src/main/java/com/baeldung/shutdownhooks/config/ShutdownHookConfiguration.java diff --git a/spring-boot-modules/spring-boot-mvc-4/README.md b/spring-boot-modules/spring-boot-mvc-4/README.md index c6820ce930..d215525ab5 100644 --- a/spring-boot-modules/spring-boot-mvc-4/README.md +++ b/spring-boot-modules/spring-boot-mvc-4/README.md @@ -7,4 +7,5 @@ This module contains articles about Spring Web MVC in Spring Boot projects. - [How to Register a Servlet in Java](https://www.baeldung.com/register-servlet) - [Guide to Spring WebUtils and ServletRequestUtils](https://www.baeldung.com/spring-webutils-servletrequestutils) - [Configure a Spring Boot Web Application](https://www.baeldung.com/spring-boot-application-configuration) +- [A Quick Intro to the SpringBootServletInitializer](https://www.baeldung.com/spring-boot-servlet-initializer) - [A Guide to Spring in Eclipse STS](https://www.baeldung.com/eclipse-sts-spring) diff --git a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java similarity index 93% rename from spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java rename to spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java index 0aa0f0ae0b..5b9ce1271e 100644 --- a/spring-boot-modules/spring-boot-1/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java +++ b/spring-boot-modules/spring-boot-mvc-4/src/main/java/com/baeldung/servletinitializer/WarInitializerApplication.java @@ -5,7 +5,7 @@ import java.time.LocalDateTime; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; diff --git a/spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java b/spring-boot-modules/spring-boot-mvc-4/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java similarity index 100% rename from spring-boot-modules/spring-boot-1/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java rename to spring-boot-modules/spring-boot-mvc-4/src/test/java/com/baeldung/servletinitializer/WarInitializerApplicationIntegrationTest.java From 31a903b5522175518788c56c7952a8ac3f37fba5 Mon Sep 17 00:00:00 2001 From: lucaCambi77 Date: Fri, 29 Apr 2022 01:20:55 +0200 Subject: [PATCH 21/35] fix: move to spring-data-mongodb (#12089) --- .../spring-data-mongodb/pom.xml | 7 +++ .../baeldung/projection/model/InStock.java | 0 .../baeldung/projection/model/Inventory.java | 3 +- .../com/baeldung/projection/model/Size.java | 0 .../repository/InventoryRepository.java | 0 .../projection/AbstractTestProjection.java | 39 ----------------- .../MongoTemplateProjectionUnitTest.java | 17 +++++--- .../RepositoryProjectionUnitTest.java | 12 +++--- .../projection/config/ProjectionConfig.java | 43 +++++++++++++++++++ 9 files changed, 71 insertions(+), 50 deletions(-) rename persistence-modules/{spring-boot-persistence-mongodb => spring-data-mongodb}/src/main/java/com/baeldung/projection/model/InStock.java (100%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-data-mongodb}/src/main/java/com/baeldung/projection/model/Inventory.java (96%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-data-mongodb}/src/main/java/com/baeldung/projection/model/Size.java (100%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-data-mongodb}/src/main/java/com/baeldung/projection/repository/InventoryRepository.java (100%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-data-mongodb}/src/test/java/com/baeldung/projection/AbstractTestProjection.java (54%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-data-mongodb}/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java (92%) rename persistence-modules/{spring-boot-persistence-mongodb => spring-data-mongodb}/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java (94%) create mode 100644 persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/config/ProjectionConfig.java diff --git a/persistence-modules/spring-data-mongodb/pom.xml b/persistence-modules/spring-data-mongodb/pom.xml index ef5a0f0550..afb5e8b9c1 100644 --- a/persistence-modules/spring-data-mongodb/pom.xml +++ b/persistence-modules/spring-data-mongodb/pom.xml @@ -73,6 +73,12 @@ querydsl-apt ${querydsl.version} + + de.flapdoodle.embed + de.flapdoodle.embed.mongo + ${embed.mongo.version} + test + @@ -103,6 +109,7 @@ 4.1.0 3.2.0.RELEASE 4.0.5 + 3.2.6 \ No newline at end of file diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/InStock.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/InStock.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/InStock.java rename to persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/InStock.java diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/Inventory.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/Inventory.java similarity index 96% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/Inventory.java rename to persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/Inventory.java index 28e6607dc9..0f4cf6b814 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/Inventory.java +++ b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/Inventory.java @@ -3,13 +3,14 @@ package com.baeldung.projection.model; import java.util.List; import java.util.Objects; +import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.MongoId; @Document(collection = "inventory") public class Inventory { - @MongoId + @Id private String id; private String item; private String status; diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/Size.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/Size.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/model/Size.java rename to persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/model/Size.java diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/repository/InventoryRepository.java b/persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/repository/InventoryRepository.java similarity index 100% rename from persistence-modules/spring-boot-persistence-mongodb/src/main/java/com/baeldung/projection/repository/InventoryRepository.java rename to persistence-modules/spring-data-mongodb/src/main/java/com/baeldung/projection/repository/InventoryRepository.java diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/AbstractTestProjection.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/AbstractTestProjection.java similarity index 54% rename from persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/AbstractTestProjection.java rename to persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/AbstractTestProjection.java index c86d8c170e..b197ada7aa 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/AbstractTestProjection.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/AbstractTestProjection.java @@ -1,54 +1,15 @@ package com.baeldung.projection; -import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.jupiter.api.AfterEach; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.util.SocketUtils; - import com.baeldung.projection.model.InStock; import com.baeldung.projection.model.Inventory; import com.baeldung.projection.model.Size; -import com.mongodb.client.MongoClients; - -import de.flapdoodle.embed.mongo.MongodExecutable; -import de.flapdoodle.embed.mongo.MongodStarter; -import de.flapdoodle.embed.mongo.config.ImmutableMongodConfig; -import de.flapdoodle.embed.mongo.config.MongodConfig; -import de.flapdoodle.embed.mongo.config.Net; -import de.flapdoodle.embed.mongo.distribution.Version; -import de.flapdoodle.embed.process.runtime.Network; abstract class AbstractTestProjection { - private static final String CONNECTION_STRING = "mongodb://%s:%d"; - - protected MongodExecutable mongodExecutable; - protected MongoTemplate mongoTemplate; - - @AfterEach - void clean() { - mongodExecutable.stop(); - } - - void setUp() throws IOException { - String ip = "localhost"; - int port = SocketUtils.findAvailableTcpPort(); - - ImmutableMongodConfig mongodbConfig = MongodConfig.builder() - .version(Version.Main.PRODUCTION) - .net(new Net(ip, port, Network.localhostIsIPv6())) - .build(); - - MongodStarter starter = MongodStarter.getDefaultInstance(); - mongodExecutable = starter.prepare(mongodbConfig); - mongodExecutable.start(); - mongoTemplate = new MongoTemplate(MongoClients.create(String.format(CONNECTION_STRING, ip, port)), "test"); - } - public List getInventories() { Inventory journal = new Inventory(); journal.setItem("journal"); diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java similarity index 92% rename from persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java rename to persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java index a174b73f2c..1cd6415a1b 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/MongoTemplateProjectionUnitTest.java @@ -10,20 +10,27 @@ import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import com.baeldung.projection.config.ProjectionConfig; import com.baeldung.projection.model.InStock; import com.baeldung.projection.model.Inventory; import com.baeldung.projection.model.Size; -@SpringBootTest +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = ProjectionConfig.class) public class MongoTemplateProjectionUnitTest extends AbstractTestProjection { - @BeforeEach - void setup() throws Exception { - super.setUp(); + @Autowired + private MongoTemplate mongoTemplate; + @BeforeEach + void setup() { List inventoryList = getInventories(); mongoTemplate.insert(inventoryList, Inventory.class); diff --git a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java similarity index 94% rename from persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java rename to persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java index 6b0fa7f7fd..e8f2d4bf7d 100644 --- a/persistence-modules/spring-boot-persistence-mongodb/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/RepositoryProjectionUnitTest.java @@ -10,24 +10,26 @@ import java.util.List; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import com.baeldung.projection.config.ProjectionConfig; import com.baeldung.projection.model.InStock; import com.baeldung.projection.model.Inventory; import com.baeldung.projection.model.Size; import com.baeldung.projection.repository.InventoryRepository; -@SpringBootTest +@ExtendWith(SpringExtension.class) +@ContextConfiguration(classes = ProjectionConfig.class) public class RepositoryProjectionUnitTest extends AbstractTestProjection { @Autowired private InventoryRepository inventoryRepository; @BeforeEach - void setup() throws Exception { - super.setUp(); - + void setup() { List inventoryList = getInventories(); inventoryRepository.saveAll(inventoryList); diff --git a/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/config/ProjectionConfig.java b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/config/ProjectionConfig.java new file mode 100644 index 0000000000..06260c0295 --- /dev/null +++ b/persistence-modules/spring-data-mongodb/src/test/java/com/baeldung/projection/config/ProjectionConfig.java @@ -0,0 +1,43 @@ +package com.baeldung.projection.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; +import org.springframework.util.SocketUtils; + +import com.mongodb.client.MongoClients; + +import de.flapdoodle.embed.mongo.MongodExecutable; +import de.flapdoodle.embed.mongo.MongodStarter; +import de.flapdoodle.embed.mongo.config.ImmutableMongodConfig; +import de.flapdoodle.embed.mongo.config.MongodConfig; +import de.flapdoodle.embed.mongo.config.Net; +import de.flapdoodle.embed.mongo.distribution.Version; +import de.flapdoodle.embed.process.runtime.Network; + +@Configuration +@ComponentScan(basePackages = "com.baeldung.projection") +@EnableMongoRepositories(basePackages = "com.baeldung.projection.repository") +public class ProjectionConfig { + + private static final String CONNECTION_STRING = "mongodb://%s:%d"; + private static final String HOST = "localhost"; + + @Bean + public MongoTemplate mongoTemplate() throws Exception { + int randomPort = SocketUtils.findAvailableTcpPort(); + + ImmutableMongodConfig mongoDbConfig = MongodConfig.builder() + .version(Version.Main.PRODUCTION) + .net(new Net(HOST, randomPort, Network.localhostIsIPv6())) + .build(); + + MongodStarter starter = MongodStarter.getDefaultInstance(); + MongodExecutable mongodExecutable = starter.prepare(mongoDbConfig); + mongodExecutable.start(); + + return new MongoTemplate(MongoClients.create(String.format(CONNECTION_STRING, HOST, randomPort)), "mongo_auth"); + } +} From 45085ce61ca5797c998fafc669cc6c6407a0ad5c Mon Sep 17 00:00:00 2001 From: Shaun Phillips <61982125+ShaPhi7@users.noreply.github.com> Date: Fri, 29 Apr 2022 04:34:58 +0100 Subject: [PATCH 22/35] BAEL-4356 add disable-plugins-examples (#12121) * BAEL-4356 add disable-plugins-examples * GTSIS-4356 change tabs to four spaces --- .../empty-phase/pom.xml | 31 +++++++++++ .../phase-none/pom.xml | 31 +++++++++++ .../plugin-enabled/pom.xml | 17 ++++++ .../src/file-that-must-exist.txt | 1 + .../disable-plugin-examples/pom.xml | 55 +++++++++++++++++++ .../skip-parameter/pom.xml | 28 ++++++++++ .../src/file-that-must-exist.txt | 1 + .../maven-parent-pom-resolution/pom.xml | 1 + 8 files changed, 165 insertions(+) create mode 100644 maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml create mode 100644 maven-modules/maven-parent-pom-resolution/disable-plugin-examples/phase-none/pom.xml create mode 100644 maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/pom.xml create mode 100644 maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/src/file-that-must-exist.txt create mode 100644 maven-modules/maven-parent-pom-resolution/disable-plugin-examples/pom.xml create mode 100644 maven-modules/maven-parent-pom-resolution/disable-plugin-examples/skip-parameter/pom.xml create mode 100644 maven-modules/maven-parent-pom-resolution/disable-plugin-examples/src/file-that-must-exist.txt diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml new file mode 100644 index 0000000000..28ea8b6359 --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/empty-phase/pom.xml @@ -0,0 +1,31 @@ + + + 4.0.0 + com.baeldung.maven-parent-pom-resolution + empty-phase + 1.0.0-SNAPSHOT + pom + + + com.baeldung.maven-parent-pom-resolution + disable-plugin-examples + 1.0.0-SNAPSHOT + + + + + + maven-enforcer-plugin + + + enforce-file-exists + + + + + + + + \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/phase-none/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/phase-none/pom.xml new file mode 100644 index 0000000000..8870f28fd2 --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/phase-none/pom.xml @@ -0,0 +1,31 @@ + + + 4.0.0 + com.baeldung.maven-parent-pom-resolution + phase-none + 1.0.0-SNAPSHOT + pom + + + com.baeldung.maven-parent-pom-resolution + disable-plugin-examples + 1.0.0-SNAPSHOT + + + + + + maven-enforcer-plugin + + + enforce-file-exists + any-value-that-is-not-a-phase + + + + + + + \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/pom.xml new file mode 100644 index 0000000000..e3ff22aaf7 --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + com.baeldung.maven-parent-pom-resolution + plugin-enabled + 1.0.0-SNAPSHOT + pom + + + com.baeldung.maven-parent-pom-resolution + disable-plugin-examples + 1.0.0-SNAPSHOT + + + \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/src/file-that-must-exist.txt b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/src/file-that-must-exist.txt new file mode 100644 index 0000000000..2a6fae012f --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/plugin-enabled/src/file-that-must-exist.txt @@ -0,0 +1 @@ +Example source file \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/pom.xml new file mode 100644 index 0000000000..2a2e5b00ea --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + com.baeldung.maven-parent-pom-resolution + disable-plugin-examples + 1.0.0-SNAPSHOT + pom + + + com.baeldung + maven-parent-pom-resolution + 1.0.0-SNAPSHOT + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0 + + + enforce-file-exists + + enforce + + + + + + ${project.basedir}/src/file-that-must-exist.txt + + + + + + + + + + + + plugin-enabled + skip-parameter + phase-none + empty-phase + + + + UTF-8 + + + \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/skip-parameter/pom.xml b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/skip-parameter/pom.xml new file mode 100644 index 0000000000..31415bec24 --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/skip-parameter/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + com.baeldung.maven-parent-pom-resolution + skip-parameter + 1.0.0-SNAPSHOT + pom + + + com.baeldung.maven-parent-pom-resolution + disable-plugin-examples + 1.0.0-SNAPSHOT + + + + + + maven-enforcer-plugin + + true + + + + + + \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/src/file-that-must-exist.txt b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/src/file-that-must-exist.txt new file mode 100644 index 0000000000..2a6fae012f --- /dev/null +++ b/maven-modules/maven-parent-pom-resolution/disable-plugin-examples/src/file-that-must-exist.txt @@ -0,0 +1 @@ +Example source file \ No newline at end of file diff --git a/maven-modules/maven-parent-pom-resolution/pom.xml b/maven-modules/maven-parent-pom-resolution/pom.xml index e5340032b7..8506f1c5fa 100644 --- a/maven-modules/maven-parent-pom-resolution/pom.xml +++ b/maven-modules/maven-parent-pom-resolution/pom.xml @@ -10,6 +10,7 @@ aggregator + disable-plugin-examples From bce3dd832d7ec9cde67c0adad7dd071fd1582385 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Fri, 29 Apr 2022 11:53:35 +0200 Subject: [PATCH 23/35] JAVA-10839: Update md5 hash of the sample file --- .../java/com/baeldung/download/FileDownloadIntegrationTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java index 987a69582f..0aba09a539 100644 --- a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java +++ b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/download/FileDownloadIntegrationTest.java @@ -19,7 +19,7 @@ public class FileDownloadIntegrationTest { static String FILE_URL = "https://s3.amazonaws.com/baeldung.com/Do+JSON+with+Jackson+by+Baeldung.pdf"; static String FILE_NAME = "file.dat"; - static String FILE_MD5_HASH = "c959feb066b37f5c4f0e0f45bbbb4f86"; + static String FILE_MD5_HASH = "753197aa27f162faa3e3c2e48ee5eb07"; @Test public void givenJavaIO_whenDownloadingFile_thenDownloadShouldBeCorrect() throws NoSuchAlgorithmException, IOException { From 05cdb533d7db91d486209ae5a91050909b0c364c Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Fri, 29 Apr 2022 23:19:37 +0530 Subject: [PATCH 24/35] JAVA-8271 Uncommenting spring-boot-keycloak module --- spring-boot-modules/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 003a52db13..999c006f5e 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -44,7 +44,7 @@ spring-boot-groovy spring-boot-jasypt - + spring-boot-keycloak spring-boot-libraries spring-boot-libraries-2 spring-boot-libraries-comparison From a9eba4ed49e0754609dc39c39e8da8375c355010 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 30 Apr 2022 14:09:10 +0530 Subject: [PATCH 25/35] JAVA-11775 Remove usage of deprecated JUnitPlatform.class in junit-5-basics module --- testing-modules/junit-5-basics/pom.xml | 10 +++++----- .../src/test/java/com/baeldung/GreetingsUnitTest.java | 3 --- .../java/com/baeldung/JUnit5NewFeaturesUnitTest.java | 1 - .../junit5/AnnotationTestExampleUnitTest.java | 3 --- .../migration/junit5/AssertionsExampleUnitTest.java | 3 --- .../BeforeAllAndAfterAllAnnotationsUnitTest.java | 3 --- .../BeforeEachAndAfterEachAnnotationsUnitTest.java | 3 --- .../baeldung/migration/junit5/RuleExampleUnitTest.java | 6 ++---- .../src/test/java/com/baeldung/suites/AllUnitTest.java | 9 +++++---- .../java/com/baeldung/tags/EmployeeDAOTestSuite.java | 3 --- 10 files changed, 12 insertions(+), 32 deletions(-) diff --git a/testing-modules/junit-5-basics/pom.xml b/testing-modules/junit-5-basics/pom.xml index e6636e3239..e240efe514 100644 --- a/testing-modules/junit-5-basics/pom.xml +++ b/testing-modules/junit-5-basics/pom.xml @@ -15,12 +15,12 @@ - - org.junit.platform - junit-platform-runner - ${junit-platform.version} + + org.junit.platform + junit-platform-suite + ${junit-platform.version} test - + org.junit.jupiter junit-jupiter-migrationsupport diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java index a07162ceed..1ff21548b8 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/GreetingsUnitTest.java @@ -3,12 +3,9 @@ package com.baeldung; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import com.baeldung.junit5.Greetings; -@RunWith(JUnitPlatform.class) public class GreetingsUnitTest { @Test diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java index 311c62f425..252bbdb2ce 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/JUnit5NewFeaturesUnitTest.java @@ -10,7 +10,6 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -//@RunWith(JUnitPlatform.class) public class JUnit5NewFeaturesUnitTest { private static final Logger log = Logger.getLogger(JUnit5NewFeaturesUnitTest.class.getName()); diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java index c2bbfd4d07..b324910ab7 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AnnotationTestExampleUnitTest.java @@ -6,12 +6,9 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; @Tag("annotations") @Tag("junit5") -@RunWith(JUnitPlatform.class) public class AnnotationTestExampleUnitTest { @Test public void shouldRaiseAnException() throws Exception { diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java index c35611aad1..14b1162ecf 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/AssertionsExampleUnitTest.java @@ -6,10 +6,7 @@ import java.util.List; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; -@RunWith(JUnitPlatform.class) public class AssertionsExampleUnitTest { @Test @Disabled diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java index 5181d54a46..68bb66657e 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeAllAndAfterAllAnnotationsUnitTest.java @@ -3,12 +3,9 @@ package com.baeldung.migration.junit5; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@RunWith(JUnitPlatform.class) public class BeforeAllAndAfterAllAnnotationsUnitTest { private static final Logger LOG = LoggerFactory.getLogger(BeforeAllAndAfterAllAnnotationsUnitTest.class); diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java index b2112ef2c3..283665798d 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/BeforeEachAndAfterEachAnnotationsUnitTest.java @@ -9,12 +9,9 @@ import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@RunWith(JUnitPlatform.class) public class BeforeEachAndAfterEachAnnotationsUnitTest { private static final Logger LOG = LoggerFactory.getLogger(BeforeEachAndAfterEachAnnotationsUnitTest.class); diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java index c67a57dcbd..5c878ef7d3 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/migration/junit5/RuleExampleUnitTest.java @@ -1,14 +1,12 @@ package com.baeldung.migration.junit5; -import com.baeldung.migration.junit5.extensions.TraceUnitExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.platform.runner.JUnitPlatform; -import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@RunWith(JUnitPlatform.class) +import com.baeldung.migration.junit5.extensions.TraceUnitExtension; + @ExtendWith(TraceUnitExtension.class) public class RuleExampleUnitTest { diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java index 30b92ad428..b14440f1f2 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/suites/AllUnitTest.java @@ -1,12 +1,13 @@ package com.baeldung.suites; -import org.junit.platform.runner.JUnitPlatform; +import org.junit.platform.suite.api.ExcludePackages; import org.junit.platform.suite.api.SelectPackages; -import org.junit.runner.RunWith; +import org.junit.platform.suite.api.Suite; -@RunWith(JUnitPlatform.class) +@Suite @SelectPackages("com.baeldung") -// @SelectClasses({AssertionTest.class, AssumptionTest.class, ExceptionTest.class}) +@ExcludePackages("com.baeldung.suites") public class AllUnitTest { } + \ No newline at end of file diff --git a/testing-modules/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java b/testing-modules/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java index 783e5a81a2..cddb76381f 100644 --- a/testing-modules/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java +++ b/testing-modules/junit-5-basics/src/test/java/com/baeldung/tags/EmployeeDAOTestSuite.java @@ -1,11 +1,8 @@ package com.baeldung.tags; -import org.junit.platform.runner.JUnitPlatform; import org.junit.platform.suite.api.IncludeTags; import org.junit.platform.suite.api.SelectPackages; -import org.junit.runner.RunWith; -@RunWith(JUnitPlatform.class) @SelectPackages("com.baeldung.tags") @IncludeTags("UnitTest") public class EmployeeDAOTestSuite { From b64024d0039ac143fd2deeb495eb07a7446040f2 Mon Sep 17 00:00:00 2001 From: ACHRAF TAITAI <43656331+achraftt@users.noreply.github.com> Date: Sat, 30 Apr 2022 11:40:27 +0200 Subject: [PATCH 26/35] Bael 5381 update (#12142) * BAEL-5381: Java Scanner.skip method with examples * BAEL-5381: Edit unitTest class name * BAEL-5381: update code after review --- .../test/java/com/baeldung/scanner/ScannerUnitTest.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/core-java-modules/core-java-io-4/src/test/java/com/baeldung/scanner/ScannerUnitTest.java b/core-java-modules/core-java-io-4/src/test/java/com/baeldung/scanner/ScannerUnitTest.java index f11f3d032d..cb6ce5fb2d 100644 --- a/core-java-modules/core-java-io-4/src/test/java/com/baeldung/scanner/ScannerUnitTest.java +++ b/core-java-modules/core-java-io-4/src/test/java/com/baeldung/scanner/ScannerUnitTest.java @@ -8,26 +8,27 @@ import java.util.regex.*; import static org.junit.jupiter.api.Assertions.assertEquals; public class ScannerUnitTest { - @Test public void scannerSkipUsingPattern() { + @Test public void givenScannerWithPattern_thenSkipUsingPattern() { String str = "Java scanner skip tutorial"; // Instantiates Scanner Scanner sc = new Scanner(str); // By using skip(Pattern) method is to skip that meets the given pattern sc.skip(Pattern.compile(".ava")); - assertEquals(sc.nextLine(), " scanner skip tutorial"); + + assertEquals(" scanner skip tutorial", sc.nextLine()); // Scanner closed sc.close(); } - @Test public void scannerSkipUsingStringPattern() { + @Test public void givenScannerWithString_thenSkipUsingStringPattern() { String str = "Java scanner skip tutorial"; // Instantiates Scanner Scanner sc = new Scanner(str); // By using skip(String) method is to skip that meets the given // pattern constructed from the given String sc.skip("Java"); - assertEquals(sc.nextLine(), " scanner skip tutorial"); + assertEquals(" scanner skip tutorial", sc.nextLine()); // Scanner closed sc.close(); } From ab97eda9d93eb1e63495ebe9bdff01026acf1e20 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Sat, 30 Apr 2022 12:26:59 +0100 Subject: [PATCH 27/35] [JAVA-8145] Fix formatting --- .../webclient/WebClientIntegrationTest.java | 235 +++++++++--------- 1 file changed, 120 insertions(+), 115 deletions(-) diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebClientIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebClientIntegrationTest.java index 28b4c19a10..22c545c362 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebClientIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebClientIntegrationTest.java @@ -45,41 +45,41 @@ import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(classes = WebClientApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class WebClientIntegrationTest { - @LocalServerPort - private int port; - private static final String BODY_VALUE = "bodyValue"; private static final ParameterizedTypeReference> MAP_RESPONSE_REF = new ParameterizedTypeReference>() { }; + @LocalServerPort + private int port; + @Test public void givenDifferentWebClientCreationMethods_whenUsed_thenObtainExpectedResponse() { // WebClient creation WebClient client1 = WebClient.create(); WebClient client2 = WebClient.create("http://localhost:" + port); WebClient client3 = WebClient.builder() - .baseUrl("http://localhost:" + port) - .defaultCookie("cookieKey", "cookieValue") - .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) - .build(); + .baseUrl("http://localhost:" + port) + .defaultCookie("cookieKey", "cookieValue") + .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .defaultUriVariables(Collections.singletonMap("url", "http://localhost:8080")) + .build(); // response assertions StepVerifier.create(retrieveResponse(client1.post() .uri("http://localhost:" + port + "/resource"))) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(client2)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(client3)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); // assert response without specifying URI StepVerifier.create(retrieveResponse(client1)) - .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() - .contains("Connection refused")) - .verify(); + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() + .contains("Connection refused")) + .verify(); } @Test @@ -91,60 +91,64 @@ public class WebClientIntegrationTest { // response assertions StepVerifier.create(retrieveResponse(uriSpecPost1)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(uriSpecPost2)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveGetResponse(requestGet)) - .expectNextMatches(nextMap -> nextMap.get("field") - .equals("value")) - .verifyComplete(); + .expectNextMatches(nextMap -> nextMap.get("field") + .equals("value")) + .verifyComplete(); } @Test public void givenDifferentUriSpecifications_whenUsed_thenObtainExpectedResponse() { // uri specification RequestBodySpec bodySpecUsingString = createDefaultPostRequest().uri("/resource"); - RequestBodySpec bodySpecUsingUriBuilder = createDefaultPostRequest().uri(uriBuilder -> uriBuilder.pathSegment("resource") + RequestBodySpec bodySpecUsingUriBuilder = createDefaultPostRequest().uri( + uriBuilder -> uriBuilder.pathSegment("resource") .build()); - RequestBodySpec bodySpecusingURI = createDefaultPostRequest().uri(URI.create("http://localhost:" + port + "/resource")); + RequestBodySpec bodySpecusingURI = createDefaultPostRequest().uri( + URI.create("http://localhost:" + port + "/resource")); RequestBodySpec bodySpecOverridenBaseUri = createDefaultPostRequest().uri(URI.create("/resource")); RequestBodySpec bodySpecOverridenBaseUri2 = WebClient.builder() - .baseUrl("http://localhost:" + port) - .build() - .post() - .uri(URI.create("/resource")); + .baseUrl("http://localhost:" + port) + .build() + .post() + .uri(URI.create("/resource")); // response assertions StepVerifier.create(retrieveResponse(bodySpecUsingString)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(bodySpecUsingUriBuilder)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(bodySpecusingURI)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); // assert sending request overriding base URI StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri)) - .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() - .contains("Connection refused")) - .verify(); + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() + .contains("Connection refused")) + .verify(); StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri2)) - .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() - .contains("Connection refused")) - .verify(); + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() + .contains("Connection refused")) + .verify(); } @Test public void givenDifferentBodySpecifications_whenUsed_thenObtainExpectedResponse() { // request body specifications - RequestHeadersSpec headersSpecPost1 = createDefaultPostResourceRequest().body(BodyInserters.fromPublisher(Mono.just(BODY_VALUE), String.class)); - RequestHeadersSpec headersSpecPost2 = createDefaultPostResourceRequest().body(BodyInserters.fromValue(BODY_VALUE)); + RequestHeadersSpec headersSpecPost1 = createDefaultPostResourceRequest().body( + BodyInserters.fromPublisher(Mono.just(BODY_VALUE), String.class)); + RequestHeadersSpec headersSpecPost2 = createDefaultPostResourceRequest().body( + BodyInserters.fromValue(BODY_VALUE)); RequestHeadersSpec headersSpecPost3 = createDefaultPostResourceRequest().bodyValue(BODY_VALUE); RequestHeadersSpec headersSpecFooPost = createDefaultPostRequest().uri("/resource-foo") - .body(Mono.just(new Foo("fooName")), Foo.class); + .body(Mono.just(new Foo("fooName")), Foo.class); BodyInserter inserterPlainObject = BodyInserters.fromValue(new Object()); RequestHeadersSpec headersSpecPlainObject = createDefaultPostResourceRequest().body(inserterPlainObject); @@ -152,54 +156,57 @@ public class WebClientIntegrationTest { LinkedMultiValueMap map = new LinkedMultiValueMap<>(); map.add("key1", "multipartValue1"); map.add("key2", "multipartValue2"); - BodyInserter, ClientHttpRequest> inserterMultipart = BodyInserters.fromMultipartData(map); + BodyInserter, ClientHttpRequest> inserterMultipart = BodyInserters.fromMultipartData( + map); RequestHeadersSpec headersSpecInserterMultipart = createDefaultPostRequest().uri("/resource-multipart") - .body(inserterMultipart); + .body(inserterMultipart); // response assertions StepVerifier.create(retrieveResponse(headersSpecPost1)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(headersSpecPost2)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(headersSpecPost3)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(retrieveResponse(headersSpecFooPost)) - .expectNext("processedFoo-fooName") - .verifyComplete(); + .expectNext("processedFoo-fooName") + .verifyComplete(); StepVerifier.create(retrieveResponse(headersSpecInserterMultipart)) - .expectNext("processed-multipartValue1-multipartValue2") - .verifyComplete(); + .expectNext("processed-multipartValue1-multipartValue2") + .verifyComplete(); // assert error plain `new Object()` as request body StepVerifier.create(retrieveResponse(headersSpecPlainObject)) - .expectError(CodecException.class) - .verify(); + .expectError(CodecException.class) + .verify(); // assert response for request with no body - Mono> responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono(responseHandler -> { - assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); - return responseHandler.bodyToMono(MAP_RESPONSE_REF); - }); + Mono> responsePostWithNoBody = createDefaultPostResourceRequest().exchangeToMono( + responseHandler -> { + assertThat(responseHandler.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + return responseHandler.bodyToMono(MAP_RESPONSE_REF); + }); StepVerifier.create(responsePostWithNoBody) - .expectNextMatches(nextMap -> nextMap.get("error") - .equals("Bad Request")) - .verifyComplete(); + .expectNextMatches(nextMap -> nextMap.get("error") + .equals("Bad Request")) + .verifyComplete(); } @Test public void givenPostSpecifications_whenHeadersAdded_thenObtainExpectedResponse() { // request header specification - RequestHeadersSpec headersSpecInserterStringWithHeaders = createDefaultPostResourceRequestResponse().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) - .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) - .acceptCharset(StandardCharsets.UTF_8) - .ifNoneMatch("*") - .ifModifiedSince(ZonedDateTime.now()); + RequestHeadersSpec headersSpecInserterStringWithHeaders = createDefaultPostResourceRequestResponse().header( + HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) + .acceptCharset(StandardCharsets.UTF_8) + .ifNoneMatch("*") + .ifModifiedSince(ZonedDateTime.now()); // response assertions StepVerifier.create(retrieveResponse(headersSpecInserterStringWithHeaders)) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); } @Test @@ -209,68 +216,66 @@ public class WebClientIntegrationTest { Mono responsePostString2 = createDefaultPostResourceRequestResponse().exchangeToMono(response -> { if (response.statusCode() == HttpStatus.OK) { return response.bodyToMono(String.class); - } else if (response.statusCode() - .is4xxClientError()) { + } else if (response.statusCode().is4xxClientError()) { return Mono.just("Error response"); } else { return response.createException() - .flatMap(Mono::error); + .flatMap(Mono::error); } }); Mono responsePostNoBody = createDefaultPostResourceRequest().exchangeToMono(response -> { if (response.statusCode() == HttpStatus.OK) { return response.bodyToMono(String.class); - } else if (response.statusCode() - .is4xxClientError()) { + } else if (response.statusCode().is4xxClientError()) { return Mono.just("Error response"); } else { return response.createException() - .flatMap(Mono::error); + .flatMap(Mono::error); } }); Mono> responseGet = createDefaultClient().get() - .uri("/resource") - .retrieve() - .bodyToMono(MAP_RESPONSE_REF); + .uri("/resource") + .retrieve() + .bodyToMono(MAP_RESPONSE_REF); // response assertions StepVerifier.create(responsePostString) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(responsePostString2) - .expectNext("processed-bodyValue") - .verifyComplete(); + .expectNext("processed-bodyValue") + .verifyComplete(); StepVerifier.create(responsePostNoBody) - .expectNext("Error response") - .verifyComplete(); + .expectNext("Error response") + .verifyComplete(); StepVerifier.create(responseGet) - .expectNextMatches(nextMap -> nextMap.get("field") - .equals("value")) - .verifyComplete(); + .expectNextMatches(nextMap -> nextMap.get("field") + .equals("value")) + .verifyComplete(); } @Test public void givenWebClientWithTimeoutConfigurations_whenRequestUsingWronglyConfiguredPublisher_thenObtainTimeout() { HttpClient httpClient = HttpClient.create() - .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000) - .responseTimeout(Duration.ofMillis(1000)) - .doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(1000, TimeUnit.MILLISECONDS)) - .addHandlerLast(new WriteTimeoutHandler(1000, TimeUnit.MILLISECONDS))); + .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000) + .responseTimeout(Duration.ofMillis(1000)) + .doOnConnected(conn -> conn.addHandlerLast(new ReadTimeoutHandler(1000, TimeUnit.MILLISECONDS)) + .addHandlerLast(new WriteTimeoutHandler(1000, TimeUnit.MILLISECONDS))); WebClient timeoutClient = WebClient.builder() - .baseUrl("http://localhost:" + port) - .clientConnector(new ReactorClientHttpConnector(httpClient)) - .build(); + .baseUrl("http://localhost:" + port) + .clientConnector(new ReactorClientHttpConnector(httpClient)) + .build(); RequestHeadersSpec neverendingMonoBodyRequest = timeoutClient.post() - .uri("/resource") - .body(Mono.never(), String.class); + .uri("/resource") + .body(Mono.never(), String.class); StepVerifier.create(neverendingMonoBodyRequest.retrieve() .bodyToMono(String.class)) - .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ReadTimeoutException.class.isAssignableFrom(ex.getCause() - .getClass())) - .verify(); + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) + && ReadTimeoutException.class.isAssignableFrom(ex.getCause().getClass())) + .verify(); } // helper methods to create default instances @@ -293,33 +298,33 @@ public class WebClientIntegrationTest { // helper methods to retrieve a response based on different steps of the process (specs) private Mono retrieveResponse(WebClient client) { return client.post() - .uri("/resource") - .bodyValue(BODY_VALUE) - .retrieve() - .bodyToMono(String.class); + .uri("/resource") + .bodyValue(BODY_VALUE) + .retrieve() + .bodyToMono(String.class); } private Mono retrieveResponse(RequestBodyUriSpec spec) { return spec.uri("/resource") - .bodyValue(BODY_VALUE) - .retrieve() - .bodyToMono(String.class); + .bodyValue(BODY_VALUE) + .retrieve() + .bodyToMono(String.class); } private Mono> retrieveGetResponse(RequestHeadersUriSpec spec) { return spec.uri("/resource") - .retrieve() - .bodyToMono(MAP_RESPONSE_REF); + .retrieve() + .bodyToMono(MAP_RESPONSE_REF); } private Mono retrieveResponse(RequestBodySpec spec) { return spec.bodyValue(BODY_VALUE) - .retrieve() - .bodyToMono(String.class); + .retrieve() + .bodyToMono(String.class); } private Mono retrieveResponse(RequestHeadersSpec spec) { return spec.retrieve() - .bodyToMono(String.class); + .bodyToMono(String.class); } } From 6df424bff4fe1dc87f1fca183181a402aa27e061 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Sat, 30 Apr 2022 12:27:13 +0100 Subject: [PATCH 28/35] [JAVA-8145] Update and cleanup code --- .../com/baeldung/reactive/webclient/Foo.java | 24 ++--- .../webclient/WebClientApplication.java | 9 +- .../WebControllerIntegrationTest.java | 36 ++++---- .../WebTestClientIntegrationTest.java | 91 ++++++++----------- 4 files changed, 67 insertions(+), 93 deletions(-) diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webclient/Foo.java b/spring-reactive/src/main/java/com/baeldung/reactive/webclient/Foo.java index a58d672686..246ba30667 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webclient/Foo.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webclient/Foo.java @@ -1,24 +1,14 @@ package com.baeldung.reactive.webclient; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor public class Foo { private String name; - public Foo() { - super(); - } - - public Foo(String name) { - super(); - this.name = name; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - } diff --git a/spring-reactive/src/main/java/com/baeldung/reactive/webclient/WebClientApplication.java b/spring-reactive/src/main/java/com/baeldung/reactive/webclient/WebClientApplication.java index fd1cb8aff1..3a62e7b8a5 100644 --- a/spring-reactive/src/main/java/com/baeldung/reactive/webclient/WebClientApplication.java +++ b/spring-reactive/src/main/java/com/baeldung/reactive/webclient/WebClientApplication.java @@ -15,11 +15,10 @@ public class WebClientApplication { } @Bean - public SecurityWebFilterChain functionalValidationsSpringSecurityFilterChain(ServerHttpSecurity http) { - http.authorizeExchange() - .anyExchange() - .permitAll(); - http.csrf().disable(); + public SecurityWebFilterChain filterChain(ServerHttpSecurity http) { + http.csrf().disable() + .authorizeExchange() + .anyExchange().permitAll(); return http.build(); } } diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebControllerIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebControllerIntegrationTest.java index 3ab687bb41..22bd2829d3 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebControllerIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebControllerIntegrationTest.java @@ -1,22 +1,22 @@ package com.baeldung.reactive.webclient; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; -@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS) -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = WebClientApplication.class) +import static org.springframework.test.annotation.DirtiesContext.ClassMode.BEFORE_CLASS; + +@DirtiesContext(classMode = BEFORE_CLASS) +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = WebClientApplication.class) public class WebControllerIntegrationTest { @LocalServerPort - int randomServerPort; + private int randomServerPort; @Autowired private WebTestClient testClient; @@ -24,30 +24,26 @@ public class WebControllerIntegrationTest { @Autowired private WebController webController; - @Before - public void setup() { + @BeforeEach + void setup() { webController.setServerPort(randomServerPort); } @Test - public void whenEndpointWithBlockingClientIsCalled_thenThreeTweetsAreReceived() { + void whenEndpointWithBlockingClientIsCalled_thenThreeTweetsAreReceived() { testClient.get() .uri("/tweets-blocking") .exchange() - .expectStatus() - .isOk() - .expectBodyList(Tweet.class) - .hasSize(3); + .expectStatus().isOk() + .expectBodyList(Tweet.class).hasSize(3); } @Test - public void whenEndpointWithNonBlockingClientIsCalled_thenThreeTweetsAreReceived() { + void whenEndpointWithNonBlockingClientIsCalled_thenThreeTweetsAreReceived() { testClient.get() .uri("/tweets-non-blocking") .exchange() - .expectStatus() - .isOk() - .expectBodyList(Tweet.class) - .hasSize(3); + .expectStatus().isOk() + .expectBodyList(Tweet.class).hasSize(3); } } \ No newline at end of file diff --git a/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebTestClientIntegrationTest.java b/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebTestClientIntegrationTest.java index 90f4a0eca2..dc2a2a30b9 100644 --- a/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebTestClientIntegrationTest.java +++ b/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebTestClientIntegrationTest.java @@ -3,6 +3,7 @@ package com.baeldung.reactive.webclient; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ApplicationContext; import org.springframework.security.test.context.support.WithMockUser; @@ -14,7 +15,7 @@ import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.WebHandler; import reactor.core.publisher.Mono; -@SpringBootTest(classes = WebClientApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@SpringBootTest(classes = WebClientApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class WebTestClientIntegrationTest { @LocalServerPort @@ -26,73 +27,61 @@ public class WebTestClientIntegrationTest { @Autowired private WebClientController controller; - private final RouterFunction ROUTER_FUNCTION = RouterFunctions.route(RequestPredicates.GET("/resource"), request -> ServerResponse.ok() - .build()); - private final WebHandler WEB_HANDLER = exchange -> Mono.empty(); - @Test - public void testWebTestClientWithServerWebHandler() { - WebTestClient.bindToWebHandler(WEB_HANDLER) - .build(); + public void whenBindToWebHandler_thenRequestProcessed() { + WebHandler webHandler = exchange -> Mono.empty(); + + WebTestClient.bindToWebHandler(webHandler) + .build() + .get() + .exchange() + .expectBody().isEmpty(); } @Test - public void testWebTestClientWithRouterFunction() { - WebTestClient.bindToRouterFunction(ROUTER_FUNCTION) - .build() - .get() - .uri("/resource") - .exchange() - .expectStatus() - .isOk() - .expectBody() - .isEmpty(); + public void whenBindToRouter_thenRequestProcessed() { + RouterFunction routerFunction = RouterFunctions.route( + RequestPredicates.GET("/resource"), + request -> ServerResponse.ok().build() + ); + + WebTestClient.bindToRouterFunction(routerFunction) + .build() + .get().uri("/resource") + .exchange() + .expectStatus().isOk() + .expectBody().isEmpty(); } @Test @WithMockUser - public void testWebTestClientWithServerURL() { + public void whenBindToServer_thenRequestProcessed() { WebTestClient.bindToServer() - .baseUrl("http://localhost:" + port) - .build() - .get() - .uri("/resource") - .exchange() - .expectStatus() - .isOk() - .expectBody() - .jsonPath("field") - .isEqualTo("value"); - ; + .baseUrl("http://localhost:" + port).build() + .get().uri("/resource") + .exchange() + .expectStatus().isOk() + .expectBody().jsonPath("field").isEqualTo("value"); } @Test @WithMockUser - public void testWebTestClientWithApplicationContext() { + public void whenBindToApplicationContext_thenRequestProcessed() { WebTestClient.bindToApplicationContext(context) - .build() - .get() - .uri("/resource") - .exchange() - .expectStatus() - .isOk() - .expectBody() - .jsonPath("field") - .isEqualTo("value"); + .build() + .get().uri("/resource") + .exchange() + .expectStatus().isOk() + .expectBody().jsonPath("field").isEqualTo("value"); } @Test - public void testWebTestClientWithController() { + public void whenBindToController_thenRequestProcessed() { WebTestClient.bindToController(controller) - .build() - .get() - .uri("/resource") - .exchange() - .expectStatus() - .isOk() - .expectBody() - .jsonPath("field") - .isEqualTo("value"); + .build() + .get().uri("/resource") + .exchange() + .expectStatus().isOk() + .expectBody().jsonPath("field").isEqualTo("value"); } - } From 47adb0759dd52d864368aad437f803988d60a4b2 Mon Sep 17 00:00:00 2001 From: 515882294 <515882294@qq.com> Date: Sun, 1 May 2022 11:18:18 +0800 Subject: [PATCH 29/35] BAEL-5283: fix unit test failed --- .../java8/lambda/serialization/LambdaSerializationUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/lambda/serialization/LambdaSerializationUnitTest.java b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/lambda/serialization/LambdaSerializationUnitTest.java index 580319c92e..bb71e3bdb9 100644 --- a/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/lambda/serialization/LambdaSerializationUnitTest.java +++ b/core-java-modules/core-java-lambdas/src/test/java/com/baeldung/java8/lambda/serialization/LambdaSerializationUnitTest.java @@ -36,7 +36,7 @@ public class LambdaSerializationUnitTest { @Test public void givenSerializableConsumer_whenNoCapturing_thenSerializationSuccess() throws IOException, ClassNotFoundException { - SerializableConsumer obj = System.out::println; + SerializableConsumer obj = message -> System.out.println(message); writeAndReadObject(obj, SerializableConsumer.class); } From e4f84e6aa16e2d4faed23a629dfe7f560e251f7f Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Mon, 2 May 2022 13:47:08 +0200 Subject: [PATCH 30/35] JAVA-11524: Disable failing spring-cloud-security module --- spring-cloud/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index 9205416cd5..cac7453b0d 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -38,7 +38,7 @@ spring-cloud-archaius spring-cloud-functions spring-cloud-vault - spring-cloud-security + spring-cloud-task spring-cloud-zuul spring-cloud-zuul-fallback From c2cceb1d7ee88cf93931db4f25bfdb3e94d1fef8 Mon Sep 17 00:00:00 2001 From: Dmytry Kovalenko Date: Mon, 2 May 2022 19:11:24 +0300 Subject: [PATCH 31/35] [BAEL-5553] Check whether a string is valid JSON in Java (#12136) * [BAEL-5553] Check whether a string is valid JSON in Java * [BAEL-5553] Move implementation to json-2 package * [BAEL-5553] Move mapper creation outside method --- json-2/pom.xml | 6 ++++ .../jsonvalidation/GsonValidator.java | 32 +++++++++++++++++ .../jsonvalidation/JacksonValidator.java | 18 ++++++++++ .../jsonvalidation/JsonValidator.java | 30 ++++++++++++++++ .../jsonvalidation/GsonValidatorUnitTest.java | 35 +++++++++++++++++++ .../JacksonValidatorUnitTest.java | 29 +++++++++++++++ .../jsonvalidation/JsonValidatorUnitTest.java | 35 +++++++++++++++++++ 7 files changed, 185 insertions(+) create mode 100644 json-2/src/main/java/com/baeldung/jsonvalidation/GsonValidator.java create mode 100644 json-2/src/main/java/com/baeldung/jsonvalidation/JacksonValidator.java create mode 100644 json-2/src/main/java/com/baeldung/jsonvalidation/JsonValidator.java create mode 100644 json-2/src/test/java/com/baeldung/jsonvalidation/GsonValidatorUnitTest.java create mode 100644 json-2/src/test/java/com/baeldung/jsonvalidation/JacksonValidatorUnitTest.java create mode 100644 json-2/src/test/java/com/baeldung/jsonvalidation/JsonValidatorUnitTest.java diff --git a/json-2/pom.xml b/json-2/pom.xml index 751199d394..3e12fccc29 100644 --- a/json-2/pom.xml +++ b/json-2/pom.xml @@ -14,6 +14,11 @@ + + org.json + json + ${json.version} + com.alibaba fastjson @@ -148,6 +153,7 @@ 0.9.23 1.9.2 1.2.21 + 20211205 \ No newline at end of file diff --git a/json-2/src/main/java/com/baeldung/jsonvalidation/GsonValidator.java b/json-2/src/main/java/com/baeldung/jsonvalidation/GsonValidator.java new file mode 100644 index 0000000000..841513fc28 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsonvalidation/GsonValidator.java @@ -0,0 +1,32 @@ +package com.baeldung.jsonvalidation; + +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; +import com.google.gson.TypeAdapter; + +public class GsonValidator { + + final TypeAdapter strictAdapter = new Gson().getAdapter(JsonElement.class); + + public boolean isValid(String json) { + try { + JsonParser.parseString(json); + } catch (JsonSyntaxException e) { + return false; + } + return true; + } + + public boolean isValidStrict(String json) { + try { + strictAdapter.fromJson(json); + } catch (JsonSyntaxException | IOException e) { + return false; + } + return true; + } +} diff --git a/json-2/src/main/java/com/baeldung/jsonvalidation/JacksonValidator.java b/json-2/src/main/java/com/baeldung/jsonvalidation/JacksonValidator.java new file mode 100644 index 0000000000..8c339f46c8 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsonvalidation/JacksonValidator.java @@ -0,0 +1,18 @@ +package com.baeldung.jsonvalidation; + +import com.fasterxml.jackson.core.JacksonException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class JacksonValidator { + + final ObjectMapper mapper = new ObjectMapper(); + + public boolean isValid(String json) { + try { + mapper.readTree(json); + } catch (JacksonException e) { + return false; + } + return true; + } +} diff --git a/json-2/src/main/java/com/baeldung/jsonvalidation/JsonValidator.java b/json-2/src/main/java/com/baeldung/jsonvalidation/JsonValidator.java new file mode 100644 index 0000000000..e4183e2322 --- /dev/null +++ b/json-2/src/main/java/com/baeldung/jsonvalidation/JsonValidator.java @@ -0,0 +1,30 @@ +package com.baeldung.jsonvalidation; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +public class JsonValidator { + + public boolean isValidObject(String json) { + try { + new JSONObject(json); + } catch (JSONException e) { + return false; + } + return true; + } + + public boolean isValidJson(String json) { + try { + new JSONObject(json); + } catch (JSONException e) { + try { + new JSONArray(json); + } catch (JSONException ne) { + return false; + } + } + return true; + } +} diff --git a/json-2/src/test/java/com/baeldung/jsonvalidation/GsonValidatorUnitTest.java b/json-2/src/test/java/com/baeldung/jsonvalidation/GsonValidatorUnitTest.java new file mode 100644 index 0000000000..3b8989bdb5 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/jsonvalidation/GsonValidatorUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jsonvalidation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class GsonValidatorUnitTest { + + private final GsonValidator validator = new GsonValidator(); + + @Test + public void givenValidObjectJson_whenValidatingNonStrict_thenValid() { + String json = "{\"email\": \"example@com\", \"name\": \"John\"}"; + assertTrue(validator.isValid(json)); + } + + @Test + public void givenValidArrayJson_whenValidatingNonStrict_thenValid() { + String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]"; + assertTrue(validator.isValid(json)); + } + + @Test + public void givenInvalidJson_whenValidatingNonStrict_thenValid() { + String json = "Invalid_Json"; + assertTrue(validator.isValid(json)); + } + + @Test + public void givenInvalidJson_whenValidatingStrict_thenInvalid() { + String json = "Invalid_Json"; + assertFalse(validator.isValidStrict(json)); + } +} diff --git a/json-2/src/test/java/com/baeldung/jsonvalidation/JacksonValidatorUnitTest.java b/json-2/src/test/java/com/baeldung/jsonvalidation/JacksonValidatorUnitTest.java new file mode 100644 index 0000000000..b633af7fdc --- /dev/null +++ b/json-2/src/test/java/com/baeldung/jsonvalidation/JacksonValidatorUnitTest.java @@ -0,0 +1,29 @@ +package com.baeldung.jsonvalidation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class JacksonValidatorUnitTest { + + private final JacksonValidator validator = new JacksonValidator(); + + @Test + public void givenValidObjectJson_whenValidating_thenValid() { + String json = "{\"email\": \"example@com\", \"name\": \"John\"}"; + assertTrue(validator.isValid(json)); + } + + @Test + public void givenValidArrayJson_whenValidating_thenValid() { + String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]"; + assertTrue(validator.isValid(json)); + } + + @Test + public void givenInvalidJson_whenValidating_thenInvalid() { + String json = "Invalid_Json"; + assertFalse(validator.isValid(json)); + } +} diff --git a/json-2/src/test/java/com/baeldung/jsonvalidation/JsonValidatorUnitTest.java b/json-2/src/test/java/com/baeldung/jsonvalidation/JsonValidatorUnitTest.java new file mode 100644 index 0000000000..a590b3f709 --- /dev/null +++ b/json-2/src/test/java/com/baeldung/jsonvalidation/JsonValidatorUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.jsonvalidation; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class JsonValidatorUnitTest { + + private final JsonValidator validator = new JsonValidator(); + + @Test + public void givenValidObjectJson_whenValidatingObject_thenValid() { + String json = "{\"email\": \"example@com\", \"name\": \"John\"}"; + assertTrue(validator.isValidObject(json)); + } + + @Test + public void givenInvalidJson_whenValidating_thenInvalid() { + String json = "Invalid_Json"; + assertFalse(validator.isValidObject(json)); + } + + @Test + public void givenValidArrayJson_whenValidatingObject_thenInvalid() { + String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]"; + assertFalse(validator.isValidObject(json)); + } + + @Test + public void givenValidJson_whenValidatingJson_thenValid() { + String json = "[{\"email\": \"example@com\", \"name\": \"John\"},{\"email\": \"example1@com\", \"name\": \"Bob\"}]"; + assertTrue(validator.isValidJson(json)); + } +} From 833e3f9e9f470e8704d9357a701d3f32fbc2d091 Mon Sep 17 00:00:00 2001 From: sebx59 Date: Mon, 2 May 2022 18:29:06 +0200 Subject: [PATCH 32/35] BAEL-5559 - Swap two variables using Java (#12113) * BAEL-5559 - Swap two variables using Java initial commit * Updating tests names Co-authored-by: HARDEMAN Sebastien --- .../math/swap/SwappingVariablesUnitTest.java | 157 ++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/math/swap/SwappingVariablesUnitTest.java diff --git a/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/math/swap/SwappingVariablesUnitTest.java b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/math/swap/SwappingVariablesUnitTest.java new file mode 100644 index 0000000000..bbfa0ee4f1 --- /dev/null +++ b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/math/swap/SwappingVariablesUnitTest.java @@ -0,0 +1,157 @@ +package com.baeldung.math.swap; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class SwappingVariablesUnitTest { + + @Test + public void givenTwoStrings_whenSwappingInMethod_thenFails() { + + String a = "a"; + String b = "b"; + + swap(a, b); + + Assertions.assertFalse(a.equals("b")); + Assertions.assertFalse(b.equals("a")); + } + + @Test + public void givenTwoWrappers_whenSwappingInMethod_thenSuccess() { + + Wrapper a = new Wrapper("a"); + Wrapper b = new Wrapper("b"); + + swap(a, b); + + Assertions.assertTrue(a.string.equals("b")); + Assertions.assertTrue(b.string.equals("a")); + } + + @Test + public void givenTwoIntegers_whenSwappingUsingAdditionSubstraction_thenSuccess() { + + int a = 5; + int b = 10; + + a = a + b; + b = a - b; + a = a - b; + + Assertions.assertTrue(a == 10); + Assertions.assertTrue(b == 5); + } + + @Test + public void givenTwoIntegers_whenSwappingUsingMultiplicationDivision_thenSuccess() { + + int a = 5; + int b = 10; + + a = a * b; + b = a / b; + a = a / b; + + Assertions.assertTrue(a == 10); + Assertions.assertTrue(b == 5); + } + + @Test + public void givenTwoIntegers_whenSwappingWithOverflow_thenFails() { + + int a = Integer.MAX_VALUE; + int b = 10; + + a = a * b; + b = a / b; + a = a / b; + + Assertions.assertTrue(a == 10); + Assertions.assertFalse(b == Integer.MAX_VALUE); + } + + @Test + public void givenTwoChars_whenSwappingWithCast_thenSuccess() { + + char a = 'a'; + char b = 'b'; + + a = (char)(a * b); + b = (char)(a / b); + a = (char)(a / b); + + Assertions.assertTrue(a == 'b'); + Assertions.assertTrue(b == 'a'); + } + + @Test + public void givenTwoIntegers_whenSwappingUsingXor_thenSuccess() { + + int a = 5; + int b = 10; + + a = a ^ b; + b = a ^ b; + a = a ^ b; + + Assertions.assertTrue(a == 10); + Assertions.assertTrue(b == 5); + } + + @Test + public void givenTwoIntegers_whenSwappingUsingSingleLineXor_thenSuccess() { + + int a = 5; + int b = 10; + + a = a ^ b ^ (b = a); + + Assertions.assertTrue(a == 10); + Assertions.assertTrue(b == 5); + } + + @Test + public void givenTwoIntegers_whenSwappingUsingAdditionSubstractionSingleLine_thenSuccess() { + + int a = 5; + int b = 10; + + b = (a + b) - (a = b); + + Assertions.assertTrue(a == 10); + Assertions.assertTrue(b == 5); + } + + /** + * Illustrates that swapping in a method doesn't work + */ + private void swap(String a, String b) { + + String temp = b; + b = a; + a = temp; + } + + /** + * Illustrates swapping in a method with Wrapper class + */ + private void swap(Wrapper a, Wrapper b) { + + String temp = b.string; + b.string = a.string; + a.string = temp; + } + + class Wrapper { + + public String string; + + public Wrapper(String string) { + + this.string = string; + } + + + } +} From c1cb62d793e60dd8170b38e54cd13fb2da67a751 Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Mon, 2 May 2022 22:37:59 +0100 Subject: [PATCH 33/35] [JAVA-11827] Fix groupId reference in pom files --- spring-cloud/pom.xml | 2 +- spring-cloud/spring-cloud-security/auth-client/pom.xml | 2 +- spring-cloud/spring-cloud-security/auth-resource/pom.xml | 2 +- spring-cloud/spring-cloud-security/auth-server/pom.xml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-cloud/pom.xml b/spring-cloud/pom.xml index cac7453b0d..9205416cd5 100644 --- a/spring-cloud/pom.xml +++ b/spring-cloud/pom.xml @@ -38,7 +38,7 @@ spring-cloud-archaius spring-cloud-functions spring-cloud-vault - + spring-cloud-security spring-cloud-task spring-cloud-zuul spring-cloud-zuul-fallback diff --git a/spring-cloud/spring-cloud-security/auth-client/pom.xml b/spring-cloud/spring-cloud-security/auth-client/pom.xml index cdbb056a45..1ec56ce9ef 100644 --- a/spring-cloud/spring-cloud-security/auth-client/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-client/pom.xml @@ -9,7 +9,7 @@ Spring Cloud Security APP Client Module - com.baeldung + com.baeldung.spring.cloud spring-cloud-security 1.0.0-SNAPSHOT diff --git a/spring-cloud/spring-cloud-security/auth-resource/pom.xml b/spring-cloud/spring-cloud-security/auth-resource/pom.xml index c999030c07..9362a71931 100644 --- a/spring-cloud/spring-cloud-security/auth-resource/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-resource/pom.xml @@ -9,7 +9,7 @@ Spring Cloud Security APP Resource Module - com.baeldung + com.baeldung.spring.cloud spring-cloud-security 1.0.0-SNAPSHOT diff --git a/spring-cloud/spring-cloud-security/auth-server/pom.xml b/spring-cloud/spring-cloud-security/auth-server/pom.xml index c0330aad43..234d9cde78 100644 --- a/spring-cloud/spring-cloud-security/auth-server/pom.xml +++ b/spring-cloud/spring-cloud-security/auth-server/pom.xml @@ -8,7 +8,7 @@ Spring Cloud Security APP Server Module - com.baeldung + com.baeldung.spring.cloud spring-cloud-security 1.0.0-SNAPSHOT From 26d944ceaada03dff29a0b0da62e53b2c8f69ee7 Mon Sep 17 00:00:00 2001 From: psevestre Date: Tue, 3 May 2022 02:42:41 -0300 Subject: [PATCH 34/35] [BAEL-5584] Article code (#12157) --- spring-security-modules/pom.xml | 1 + .../spring-security-opa/pom.xml | 49 ++++++++ .../baeldung/security/opa/Application.java | 13 +++ .../security/opa/config/OpaConfiguration.java | 25 ++++ .../security/opa/config/OpaProperties.java | 14 +++ .../opa/config/SecurityConfiguration.java | 110 ++++++++++++++++++ .../opa/controller/AccountController.java | 23 ++++ .../baeldung/security/opa/domain/Account.java | 25 ++++ .../security/opa/service/AccountService.java | 37 ++++++ .../src/main/resources/application.yaml | 3 + .../controller/AccountControllerLiveTest.java | 67 +++++++++++ .../src/test/rego/account.rego | 43 +++++++ 12 files changed, 410 insertions(+) create mode 100644 spring-security-modules/spring-security-opa/pom.xml create mode 100644 spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/Application.java create mode 100644 spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaConfiguration.java create mode 100644 spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaProperties.java create mode 100644 spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/SecurityConfiguration.java create mode 100644 spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/controller/AccountController.java create mode 100644 spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/domain/Account.java create mode 100644 spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/service/AccountService.java create mode 100644 spring-security-modules/spring-security-opa/src/main/resources/application.yaml create mode 100644 spring-security-modules/spring-security-opa/src/test/java/com/baeldung/security/opa/controller/AccountControllerLiveTest.java create mode 100644 spring-security-modules/spring-security-opa/src/test/rego/account.rego diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index 9fdfde282d..bb36909c79 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -46,6 +46,7 @@ spring-security-web-x509 spring-session spring-social-login + spring-security-opa \ No newline at end of file diff --git a/spring-security-modules/spring-security-opa/pom.xml b/spring-security-modules/spring-security-opa/pom.xml new file mode 100644 index 0000000000..6665c33db3 --- /dev/null +++ b/spring-security-modules/spring-security-opa/pom.xml @@ -0,0 +1,49 @@ + + 4.0.0 + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + spring-security-opa + Spring Security with OPA authorization + + + + org.springframework.boot + spring-boot-starter-webflux + + + + org.springframework.boot + spring-boot-starter-security + + + + org.projectlombok + lombok + + + + com.google.guava + guava + 31.0.1-jre + + + + org.springframework.boot + spring-boot-devtools + + + + org.springframework.security + spring-security-test + + + org.springframework.boot + spring-boot-configuration-processor + true + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/Application.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/Application.java new file mode 100644 index 0000000000..789a1f803f --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/Application.java @@ -0,0 +1,13 @@ +package com.baeldung.security.opa; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + +} diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaConfiguration.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaConfiguration.java new file mode 100644 index 0000000000..e24fdbcf35 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaConfiguration.java @@ -0,0 +1,25 @@ +package com.baeldung.security.opa.config; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.client.WebClient; + +import lombok.RequiredArgsConstructor; + +@Configuration +@RequiredArgsConstructor +@EnableConfigurationProperties(OpaProperties.class) +public class OpaConfiguration { + + private final OpaProperties opaProperties; + + @Bean + public WebClient opaWebClient(WebClient.Builder builder) { + + return builder + .baseUrl(opaProperties.getEndpoint()) + .build(); + } + +} diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaProperties.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaProperties.java new file mode 100644 index 0000000000..acc23a2fd2 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/OpaProperties.java @@ -0,0 +1,14 @@ +package com.baeldung.security.opa.config; + +import javax.annotation.Nonnull; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +import lombok.Data; + +@ConfigurationProperties(prefix = "opa") +@Data +public class OpaProperties { + @Nonnull + private String endpoint = "http://localhost:8181"; +} diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/SecurityConfiguration.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/SecurityConfiguration.java new file mode 100644 index 0000000000..7e10cb2e8a --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/config/SecurityConfiguration.java @@ -0,0 +1,110 @@ +package com.baeldung.security.opa.config; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; + +import org.reactivestreams.Publisher; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.MediaType; +import org.springframework.http.client.reactive.ClientHttpRequest; +import org.springframework.security.authentication.AnonymousAuthenticationToken; +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.authorization.ReactiveAuthorizationManager; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.security.web.server.authorization.AuthorizationContext; +import org.springframework.web.reactive.function.BodyInserter; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.client.WebClient; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.collect.ImmutableMap; + +import reactor.core.publisher.Mono; + +@Configuration +public class SecurityConfiguration { + + + @Bean + public SecurityWebFilterChain accountAuthorization(ServerHttpSecurity http, @Qualifier("opaWebClient")WebClient opaWebClient) { + + // @formatter:on + return http + .httpBasic() + .and() + .authorizeExchange(exchanges -> { + exchanges + .pathMatchers("/account/*") + .access(opaAuthManager(opaWebClient)); + }) + .build(); + // @formatter:on + + } + + @Bean + public ReactiveAuthorizationManager opaAuthManager(WebClient opaWebClient) { + + return (auth, context) -> { + return opaWebClient.post() + .accept(MediaType.APPLICATION_JSON) + .contentType(MediaType.APPLICATION_JSON) + .body(toAuthorizationPayload(auth,context), Map.class) + .exchangeToMono(this::toDecision); + }; + } + + private Mono toDecision(ClientResponse response) { + + if ( !response.statusCode().is2xxSuccessful()) { + return Mono.just(new AuthorizationDecision(false)); + } + + return response + .bodyToMono(ObjectNode.class) + .map(node -> { + boolean authorized = node.path("result").path("authorized").asBoolean(false); + return new AuthorizationDecision(authorized); + }); + + } + + private Publisher> toAuthorizationPayload(Mono auth, AuthorizationContext context) { + // @formatter:off + return auth + .defaultIfEmpty(new AnonymousAuthenticationToken("**ANONYMOUS**", new Object(), Arrays.asList(new SimpleGrantedAuthority("ANONYMOUS")))) + .map( a -> { + + Map headers = context.getExchange().getRequest() + .getHeaders() + .toSingleValueMap(); + + Map attributes = ImmutableMap.builder() + .put("principal",a.getName()) + .put("authorities", + a.getAuthorities() + .stream() + .map(g -> g.getAuthority()) + .collect(Collectors.toList())) + .put("uri", context.getExchange().getRequest().getURI().getPath()) + .put("headers",headers) + .build(); + + Map input = ImmutableMap.builder() + .put("input",attributes) + .build(); + + return input; + }); + // @formatter:on + } +} diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/controller/AccountController.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/controller/AccountController.java new file mode 100644 index 0000000000..ba0ff61554 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/controller/AccountController.java @@ -0,0 +1,23 @@ +package com.baeldung.security.opa.controller; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +import com.baeldung.security.opa.domain.Account; +import com.baeldung.security.opa.service.AccountService; + +import lombok.RequiredArgsConstructor; +import reactor.core.publisher.Mono; + +@RestController +@RequiredArgsConstructor +public class AccountController { + + private final AccountService accountService; + + @GetMapping("/account/{accountId}") + public Mono getAccount(@PathVariable("accountId") String accountId) { + return accountService.findByAccountId(accountId); + } +} diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/domain/Account.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/domain/Account.java new file mode 100644 index 0000000000..db494627a8 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/domain/Account.java @@ -0,0 +1,25 @@ +package com.baeldung.security.opa.domain; + +import java.math.BigDecimal; + +import lombok.Data; + +@Data +public class Account { + + private String id; + private BigDecimal balance; + private String currency; + + + public static Account of(String id, BigDecimal balance, String currency) { + Account acc = new Account(); + acc.setId(id); + acc.setBalance(balance); + acc.setCurrency(currency); + + return acc; + } + + +} diff --git a/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/service/AccountService.java b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/service/AccountService.java new file mode 100644 index 0000000000..18968019f9 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/java/com/baeldung/security/opa/service/AccountService.java @@ -0,0 +1,37 @@ +/** + * + */ +package com.baeldung.security.opa.service; + +import java.math.BigDecimal; +import java.util.Map; + +import org.springframework.stereotype.Service; + +import com.baeldung.security.opa.domain.Account; +import com.google.common.collect.ImmutableMap; + +import reactor.core.publisher.Mono; + +/** + * @author Philippe + * + */ +@Service +public class AccountService { + + private Map accounts = ImmutableMap.builder() + .put("0001", Account.of("0001", BigDecimal.valueOf(100.00), "USD")) + .put("0002", Account.of("0002", BigDecimal.valueOf(101.00), "EUR")) + .put("0003", Account.of("0003", BigDecimal.valueOf(102.00), "BRL")) + .put("0004", Account.of("0004", BigDecimal.valueOf(103.00), "AUD")) + .put("0005", Account.of("0005", BigDecimal.valueOf(10400.00), "JPY")) + .build(); + + + public Mono findByAccountId(String accountId) { + return Mono.just(accounts.get(accountId)) + .switchIfEmpty(Mono.error(new IllegalArgumentException("invalid.account"))); + } + +} diff --git a/spring-security-modules/spring-security-opa/src/main/resources/application.yaml b/spring-security-modules/spring-security-opa/src/main/resources/application.yaml new file mode 100644 index 0000000000..6fb9200277 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/main/resources/application.yaml @@ -0,0 +1,3 @@ +# OPA configuration properties +opa: + endpoint: http://localhost:8181/v1/data/baeldung/auth/account \ No newline at end of file diff --git a/spring-security-modules/spring-security-opa/src/test/java/com/baeldung/security/opa/controller/AccountControllerLiveTest.java b/spring-security-modules/spring-security-opa/src/test/java/com/baeldung/security/opa/controller/AccountControllerLiveTest.java new file mode 100644 index 0000000000..7469fd327c --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/test/java/com/baeldung/security/opa/controller/AccountControllerLiveTest.java @@ -0,0 +1,67 @@ +package com.baeldung.security.opa.controller; + +import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.reactive.server.WebTestClient; + +// !!! NOTICE: Start OPA server before running this test class !!! +@SpringBootTest +@ActiveProfiles("test") +class AccountControllerLiveTest { + + @Autowired + ApplicationContext context; + WebTestClient rest; + + @BeforeEach + public void setup() { + this.rest = WebTestClient.bindToApplicationContext(this.context) + .apply(springSecurity()) + .configureClient() + .build(); + } + + + @Test + @WithMockUser(username = "user1", roles = { "account:read:0001"} ) + void testGivenValidUser_thenSuccess() { + rest.get() + .uri("/account/0001") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .is2xxSuccessful(); + } + + @Test + @WithMockUser(username = "user1", roles = { "account:read:0002"} ) + void testGivenValidUser_thenUnauthorized() { + rest.get() + .uri("/account/0001") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isForbidden(); + } + + @Test + @WithMockUser(username = "user1", roles = {} ) + void testGivenNoAuthorities_thenForbidden() { + rest.get() + .uri("/account/0001") + .accept(MediaType.APPLICATION_JSON) + .exchange() + .expectStatus() + .isForbidden(); + } + + +} diff --git a/spring-security-modules/spring-security-opa/src/test/rego/account.rego b/spring-security-modules/spring-security-opa/src/test/rego/account.rego new file mode 100644 index 0000000000..567d531bb4 --- /dev/null +++ b/spring-security-modules/spring-security-opa/src/test/rego/account.rego @@ -0,0 +1,43 @@ +# +# Simple authorization rule for accounts +# +# Assumes an input document with the following properties: +# +# resource: requested resource +# method: request method +# authorities: Granted authorities +# headers: Request headers +# +package baeldung.auth.account + +# Not authorized by default +default authorized = false + +# Authorize when there are no rules that deny access to the resource and +# there's at least one rule allowing +authorized = true { + count(deny) == 0 + count(allow) > 0 +} + +# Allow access to /public +allow["public"] { + regex.match("^/public/.*",input.uri) +} + +# Account API requires authenticated user +deny["account_api_authenticated"] { + regex.match("^/account/.*",input.uri) + regex.match("ANONYMOUS",input.principal) +} + +# Authorize access to account if principal has +# matching authority +allow["account_api_authorized"] { + regex.match("^/account/.+",input.uri) + parts := split(input.uri,"/") + account := parts[2] + role := concat(":",[ "ROLE_account", "read", account] ) + role == input.authorities[i] +} + From 15867c393d7b0f36d19d27daba9b60a6b9861012 Mon Sep 17 00:00:00 2001 From: Krzysiek Date: Tue, 3 May 2022 10:38:57 +0200 Subject: [PATCH 35/35] Revert "JAVA-8271 Uncommenting spring-boot-keycloak module" This reverts commit 05cdb533d7db91d486209ae5a91050909b0c364c. --- spring-boot-modules/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-boot-modules/pom.xml b/spring-boot-modules/pom.xml index 999c006f5e..003a52db13 100644 --- a/spring-boot-modules/pom.xml +++ b/spring-boot-modules/pom.xml @@ -44,7 +44,7 @@ spring-boot-groovy spring-boot-jasypt - spring-boot-keycloak + spring-boot-libraries spring-boot-libraries-2 spring-boot-libraries-comparison