From 421d15b1324cde53a91abc359d5a88ab93b99a1a Mon Sep 17 00:00:00 2001 From: mrsoto Date: Sat, 14 Dec 2019 22:03:27 -0300 Subject: [PATCH 01/91] Cleanup and function references --- .../convertlisttomap/ConvertListToMapService.java | 3 ++- .../CollectionToArrayListUnitTest.java | 12 ++++++------ .../ConvertIteratorToListServiceUnitTest.java | 6 +++--- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/java-collections-conversions/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java b/java-collections-conversions/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java index 6527d35742..57579e948f 100644 --- a/java-collections-conversions/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java +++ b/java-collections-conversions/src/main/java/com/baeldung/convertlisttomap/ConvertListToMapService.java @@ -6,6 +6,7 @@ import org.apache.commons.collections4.MapUtils; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.function.Function; import java.util.stream.Collectors; public class ConvertListToMapService { @@ -21,7 +22,7 @@ public class ConvertListToMapService { } public Map convertListAfterJava8(List list) { - Map map = list.stream().collect(Collectors.toMap(Animal::getId, animal -> animal)); + Map map = list.stream().collect(Collectors.toMap(Animal::getId, Function.identity())); return map; } diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java index ad2ab2a756..15960c300d 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertcollectiontoarraylist/CollectionToArrayListUnitTest.java @@ -53,14 +53,14 @@ public class CollectionToArrayListUnitTest { verifyShallowCopy(srcCollection, newList); } - + /** * Section 5. Deep Copy */ @Test public void whenUsingDeepCopy_thenVerifyDeepCopy() { ArrayList newList = srcCollection.stream() - .map(foo -> foo.deepCopy()) + .map(Foo::deepCopy) .collect(toCollection(ArrayList::new)); verifyDeepCopy(srcCollection, newList); @@ -83,13 +83,13 @@ public class CollectionToArrayListUnitTest { * @param a * @param b */ - private void verifyShallowCopy(Collection a, Collection b) { + private void verifyShallowCopy(Collection a, Collection b) { assertEquals("Collections have different lengths", a.size(), b.size()); Iterator iterA = a.iterator(); Iterator iterB = b.iterator(); while (iterA.hasNext()) { // use '==' to test instance identity - assertTrue("Foo instances differ!", iterA.next() == iterB.next()); + assertSame("Foo instances differ!", iterA.next(), iterB.next()); } } @@ -98,7 +98,7 @@ public class CollectionToArrayListUnitTest { * @param a * @param b */ - private void verifyDeepCopy(Collection a, Collection b) { + private void verifyDeepCopy(Collection a, Collection b) { assertEquals("Collections have different lengths", a.size(), b.size()); Iterator iterA = a.iterator(); Iterator iterB = b.iterator(); @@ -106,7 +106,7 @@ public class CollectionToArrayListUnitTest { Foo nextA = iterA.next(); Foo nextB = iterB.next(); // should not be same instance - assertFalse("Foo instances are the same!", nextA == nextB); + assertNotSame("Foo instances are the same!", nextA, nextB); // but should have same content assertFalse("Foo instances have different content!", fooDiff(nextA, nextB)); } diff --git a/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java b/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java index 4d6cba7d27..7d94f88d21 100644 --- a/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java +++ b/java-collections-conversions/src/test/java/com/baeldung/convertiteratortolist/ConvertIteratorToListServiceUnitTest.java @@ -23,7 +23,7 @@ public class ConvertIteratorToListServiceUnitTest { Iterator iterator; @Before - public void setUp() throws Exception { + public void setUp() { iterator = Arrays.asList(1, 2, 3) .iterator(); } @@ -31,7 +31,7 @@ public class ConvertIteratorToListServiceUnitTest { @Test public void givenAnIterator_whenConvertIteratorToListUsingWhileLoop_thenReturnAList() { - List actualList = new ArrayList(); + List actualList = new ArrayList<>(); // Convert Iterator to List using while loop dsf while (iterator.hasNext()) { @@ -44,7 +44,7 @@ public class ConvertIteratorToListServiceUnitTest { @Test public void givenAnIterator_whenConvertIteratorToListAfterJava8_thenReturnAList() { - List actualList = new ArrayList(); + List actualList = new ArrayList<>(); // Convert Iterator to List using Java 8 iterator.forEachRemaining(actualList::add); From eb4e462b36f2e486e7b51865ea6e9a62c161d928 Mon Sep 17 00:00:00 2001 From: crist Date: Tue, 4 Feb 2020 18:20:00 +0200 Subject: [PATCH 02/91] [BAEL-3750] Breaking YAML Strings Over Multiple Lines --- yaml/README.md | 7 ++ yaml/pom.xml | 29 ++++++ .../multiline/MultiLineStringsUnitTest.java | 90 +++++++++++++++++++ .../src/test/resources/multi-line/folded.yaml | 4 + .../test/resources/multi-line/folded2.yaml | 9 ++ .../resources/multi-line/folded_keep.yaml | 6 ++ .../resources/multi-line/folded_strip.yaml | 7 ++ .../test/resources/multi-line/literal.yaml | 4 + .../test/resources/multi-line/literal2.yaml | 10 +++ .../resources/multi-line/literal_keep.yaml | 5 ++ .../resources/multi-line/literal_strip.yaml | 5 ++ .../multi-line/plain_double_quotes.yaml | 1 + .../multi-line/plain_single_quotes.yaml | 3 + 13 files changed, 180 insertions(+) create mode 100644 yaml/README.md create mode 100644 yaml/pom.xml create mode 100644 yaml/src/test/java/com/baeldung/multiline/MultiLineStringsUnitTest.java create mode 100644 yaml/src/test/resources/multi-line/folded.yaml create mode 100644 yaml/src/test/resources/multi-line/folded2.yaml create mode 100644 yaml/src/test/resources/multi-line/folded_keep.yaml create mode 100644 yaml/src/test/resources/multi-line/folded_strip.yaml create mode 100644 yaml/src/test/resources/multi-line/literal.yaml create mode 100644 yaml/src/test/resources/multi-line/literal2.yaml create mode 100644 yaml/src/test/resources/multi-line/literal_keep.yaml create mode 100644 yaml/src/test/resources/multi-line/literal_strip.yaml create mode 100644 yaml/src/test/resources/multi-line/plain_double_quotes.yaml create mode 100644 yaml/src/test/resources/multi-line/plain_single_quotes.yaml diff --git a/yaml/README.md b/yaml/README.md new file mode 100644 index 0000000000..ebf403eb57 --- /dev/null +++ b/yaml/README.md @@ -0,0 +1,7 @@ +## YAML + +This module contains articles about YAML + +### Relevant articles + + diff --git a/yaml/pom.xml b/yaml/pom.xml new file mode 100644 index 0000000000..c801505c6a --- /dev/null +++ b/yaml/pom.xml @@ -0,0 +1,29 @@ + + + + 4.0.0 + yaml + 1.0-SNAPSHOT + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.yaml + snakeyaml + 1.21 + + + + + 1.8 + 1.21 + + + \ No newline at end of file diff --git a/yaml/src/test/java/com/baeldung/multiline/MultiLineStringsUnitTest.java b/yaml/src/test/java/com/baeldung/multiline/MultiLineStringsUnitTest.java new file mode 100644 index 0000000000..c97faa355a --- /dev/null +++ b/yaml/src/test/java/com/baeldung/multiline/MultiLineStringsUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.multiline; + +import org.junit.Before; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; + +import java.io.File; +import java.io.InputStream; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class MultiLineStringsUnitTest { + + private Yaml yaml; + + @Before + public void setup() { + yaml = new Yaml(); + } + + @Test + public void whenLiteral_ThenLineBreaksArePresent() { + String key = parseYamlKey("literal.yaml"); + assertEquals("Line1\nLine2\nLine3", key); + } + + @Test + public void whenLiteral_ThenEndingBreaksAreReducedToOne() { + String key = parseYamlKey("literal2.yaml"); + assertEquals("\n\nLine1\n\nLine2\n\nLine3\n", key); + } + + @Test + public void whenFolded_ThenLineBreaksAreReplaced() { + String key = parseYamlKey("folded.yaml"); + assertEquals("Line1 Line2 Line3", key); + } + + @Test + public void whenFolded_ThenEmptyLinesAreReducedToOne() { + String key = parseYamlKey("folded2.yaml"); + assertEquals("Line1\nLine2\n\nLine3\n", key); + } + + @Test + public void whenLiteralKeep_ThenLastEmptyLinesArePresent() { + String key = parseYamlKey("literal_keep.yaml"); + assertEquals("Line1\nLine2\nLine3\n\n", key); + } + + @Test + public void whenLiteralStrip_ThenLastEmptyLinesAreRemoved() { + String key = parseYamlKey("literal_strip.yaml"); + assertEquals("Line1\nLine2\nLine3", key); + } + + @Test + public void whenFoldedKeep_ThenLastEmptyLinesArePresent() { + String key = parseYamlKey("folded_keep.yaml"); + assertEquals("Line1 Line2 Line3\n\n\n", key); + } + + @Test + public void whenFoldedStrip_ThenLastEmptyLinesAreRemoved() { + String key = parseYamlKey("folded_strip.yaml"); + assertEquals("Line1 Line2 Line3", key); + } + + @Test + public void whenDoubleQuotes_ThenExplicitBreaksArePreserved() { + String key = parseYamlKey("plain_double_quotes.yaml"); + assertEquals("Line1\nLine2\nLine3", key); + } + + @Test + public void whenSingleQuotes_ThenExplicitBreaksAreIgnored() { + String key = parseYamlKey("plain_single_quotes.yaml"); + assertEquals("Line1\\nLine2\nLine3", key); + } + + private String parseYamlKey(String fileName) { + InputStream inputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("multi-line" + File.separator + fileName); + Map parsed = yaml.load(inputStream); + return parsed.get("key"); + } + +} diff --git a/yaml/src/test/resources/multi-line/folded.yaml b/yaml/src/test/resources/multi-line/folded.yaml new file mode 100644 index 0000000000..c5fa743a08 --- /dev/null +++ b/yaml/src/test/resources/multi-line/folded.yaml @@ -0,0 +1,4 @@ +key: > + Line1 + Line2 + Line3 \ No newline at end of file diff --git a/yaml/src/test/resources/multi-line/folded2.yaml b/yaml/src/test/resources/multi-line/folded2.yaml new file mode 100644 index 0000000000..a7f244994a --- /dev/null +++ b/yaml/src/test/resources/multi-line/folded2.yaml @@ -0,0 +1,9 @@ +key: > + Line1 + + Line2 + + + Line3 + + diff --git a/yaml/src/test/resources/multi-line/folded_keep.yaml b/yaml/src/test/resources/multi-line/folded_keep.yaml new file mode 100644 index 0000000000..555291fd26 --- /dev/null +++ b/yaml/src/test/resources/multi-line/folded_keep.yaml @@ -0,0 +1,6 @@ +key: >+ + Line1 + Line2 + Line3 + + diff --git a/yaml/src/test/resources/multi-line/folded_strip.yaml b/yaml/src/test/resources/multi-line/folded_strip.yaml new file mode 100644 index 0000000000..0a3a246dc2 --- /dev/null +++ b/yaml/src/test/resources/multi-line/folded_strip.yaml @@ -0,0 +1,7 @@ +key: >- + Line1 + Line2 + Line3 + + + diff --git a/yaml/src/test/resources/multi-line/literal.yaml b/yaml/src/test/resources/multi-line/literal.yaml new file mode 100644 index 0000000000..7e02501a33 --- /dev/null +++ b/yaml/src/test/resources/multi-line/literal.yaml @@ -0,0 +1,4 @@ +key: | + Line1 + Line2 + Line3 \ No newline at end of file diff --git a/yaml/src/test/resources/multi-line/literal2.yaml b/yaml/src/test/resources/multi-line/literal2.yaml new file mode 100644 index 0000000000..7c7fed0163 --- /dev/null +++ b/yaml/src/test/resources/multi-line/literal2.yaml @@ -0,0 +1,10 @@ +key: | + + + Line1 + + Line2 + + Line3 + + diff --git a/yaml/src/test/resources/multi-line/literal_keep.yaml b/yaml/src/test/resources/multi-line/literal_keep.yaml new file mode 100644 index 0000000000..37f22684dd --- /dev/null +++ b/yaml/src/test/resources/multi-line/literal_keep.yaml @@ -0,0 +1,5 @@ +key: |+ + Line1 + Line2 + Line3 + diff --git a/yaml/src/test/resources/multi-line/literal_strip.yaml b/yaml/src/test/resources/multi-line/literal_strip.yaml new file mode 100644 index 0000000000..0791e13d5d --- /dev/null +++ b/yaml/src/test/resources/multi-line/literal_strip.yaml @@ -0,0 +1,5 @@ +key: |- + Line1 + Line2 + Line3 + diff --git a/yaml/src/test/resources/multi-line/plain_double_quotes.yaml b/yaml/src/test/resources/multi-line/plain_double_quotes.yaml new file mode 100644 index 0000000000..ccab040a27 --- /dev/null +++ b/yaml/src/test/resources/multi-line/plain_double_quotes.yaml @@ -0,0 +1 @@ +key: "Line1\nLine2\nLine3" \ No newline at end of file diff --git a/yaml/src/test/resources/multi-line/plain_single_quotes.yaml b/yaml/src/test/resources/multi-line/plain_single_quotes.yaml new file mode 100644 index 0000000000..acbf35a462 --- /dev/null +++ b/yaml/src/test/resources/multi-line/plain_single_quotes.yaml @@ -0,0 +1,3 @@ +key: 'Line1\nLine2 + + Line3' \ No newline at end of file From a1d246f2e1c6849abd0bdca347f910d3ee9f183b Mon Sep 17 00:00:00 2001 From: crist Date: Tue, 4 Feb 2020 18:22:20 +0200 Subject: [PATCH 03/91] Added yamo module to appropriate profiles --- pom.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pom.xml b/pom.xml index 2a0ae0d8d8..379c741648 100644 --- a/pom.xml +++ b/pom.xml @@ -781,6 +781,7 @@ wildfly xml xstream + yaml @@ -1304,6 +1305,7 @@ wildfly xml xstream + yaml From e2de2a78d19dd74eb4f66b212693644c5448bbf5 Mon Sep 17 00:00:00 2001 From: crist Date: Thu, 6 Feb 2020 02:32:40 +0200 Subject: [PATCH 04/91] Article improvements --- .../multiline/MultiLineStringsUnitTest.java | 26 +++++++++---------- .../test/resources/multi-line/folded2.yaml | 2 +- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/yaml/src/test/java/com/baeldung/multiline/MultiLineStringsUnitTest.java b/yaml/src/test/java/com/baeldung/multiline/MultiLineStringsUnitTest.java index c97faa355a..a99de63a47 100644 --- a/yaml/src/test/java/com/baeldung/multiline/MultiLineStringsUnitTest.java +++ b/yaml/src/test/java/com/baeldung/multiline/MultiLineStringsUnitTest.java @@ -21,70 +21,70 @@ public class MultiLineStringsUnitTest { @Test public void whenLiteral_ThenLineBreaksArePresent() { - String key = parseYamlKey("literal.yaml"); + String key = parseYamlKey("literal.yaml", "key"); assertEquals("Line1\nLine2\nLine3", key); } @Test public void whenLiteral_ThenEndingBreaksAreReducedToOne() { - String key = parseYamlKey("literal2.yaml"); + String key = parseYamlKey("literal2.yaml", "key"); assertEquals("\n\nLine1\n\nLine2\n\nLine3\n", key); } @Test public void whenFolded_ThenLineBreaksAreReplaced() { - String key = parseYamlKey("folded.yaml"); + String key = parseYamlKey("folded.yaml", "key"); assertEquals("Line1 Line2 Line3", key); } @Test public void whenFolded_ThenEmptyLinesAreReducedToOne() { - String key = parseYamlKey("folded2.yaml"); - assertEquals("Line1\nLine2\n\nLine3\n", key); + String key = parseYamlKey("folded2.yaml", "key"); + assertEquals("Line1 Line2\n\nLine3\n", key); } @Test public void whenLiteralKeep_ThenLastEmptyLinesArePresent() { - String key = parseYamlKey("literal_keep.yaml"); + String key = parseYamlKey("literal_keep.yaml", "key"); assertEquals("Line1\nLine2\nLine3\n\n", key); } @Test public void whenLiteralStrip_ThenLastEmptyLinesAreRemoved() { - String key = parseYamlKey("literal_strip.yaml"); + String key = parseYamlKey("literal_strip.yaml", "key"); assertEquals("Line1\nLine2\nLine3", key); } @Test public void whenFoldedKeep_ThenLastEmptyLinesArePresent() { - String key = parseYamlKey("folded_keep.yaml"); + String key = parseYamlKey("folded_keep.yaml", "key"); assertEquals("Line1 Line2 Line3\n\n\n", key); } @Test public void whenFoldedStrip_ThenLastEmptyLinesAreRemoved() { - String key = parseYamlKey("folded_strip.yaml"); + String key = parseYamlKey("folded_strip.yaml", "key"); assertEquals("Line1 Line2 Line3", key); } @Test public void whenDoubleQuotes_ThenExplicitBreaksArePreserved() { - String key = parseYamlKey("plain_double_quotes.yaml"); + String key = parseYamlKey("plain_double_quotes.yaml", "key"); assertEquals("Line1\nLine2\nLine3", key); } @Test public void whenSingleQuotes_ThenExplicitBreaksAreIgnored() { - String key = parseYamlKey("plain_single_quotes.yaml"); + String key = parseYamlKey("plain_single_quotes.yaml", "key"); assertEquals("Line1\\nLine2\nLine3", key); } - private String parseYamlKey(String fileName) { + String parseYamlKey(String fileName, String key) { InputStream inputStream = this.getClass() .getClassLoader() .getResourceAsStream("multi-line" + File.separator + fileName); Map parsed = yaml.load(inputStream); - return parsed.get("key"); + return parsed.get(key); } } diff --git a/yaml/src/test/resources/multi-line/folded2.yaml b/yaml/src/test/resources/multi-line/folded2.yaml index a7f244994a..5c55ef62f2 100644 --- a/yaml/src/test/resources/multi-line/folded2.yaml +++ b/yaml/src/test/resources/multi-line/folded2.yaml @@ -1,9 +1,9 @@ key: > Line1 - Line2 Line3 +... \ No newline at end of file From 845f66ee2e21265beedbc78eaeaeaf1a02e90cf3 Mon Sep 17 00:00:00 2001 From: crist Date: Thu, 6 Feb 2020 02:37:44 +0200 Subject: [PATCH 05/91] Fix --- yaml/src/test/resources/multi-line/folded2.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/yaml/src/test/resources/multi-line/folded2.yaml b/yaml/src/test/resources/multi-line/folded2.yaml index 5c55ef62f2..735abf9b2f 100644 --- a/yaml/src/test/resources/multi-line/folded2.yaml +++ b/yaml/src/test/resources/multi-line/folded2.yaml @@ -6,4 +6,3 @@ key: > Line3 -... \ No newline at end of file From 2b51ce0ebcfda726fc43dbf3439a216cf209a483 Mon Sep 17 00:00:00 2001 From: crist Date: Mon, 10 Feb 2020 15:26:56 +0200 Subject: [PATCH 06/91] [BAEL-3750] Moved multi line yaml files from the yaml module to the libraries-data-io folder --- .../snakeyaml/MultiLineStringsUnitTest.java | 90 +++++++++++++++++++ .../test/resources/yaml/multiline/folded.yaml | 4 + .../resources/yaml/multiline/folded2.yaml | 8 ++ .../resources/yaml/multiline/folded_keep.yaml | 6 ++ .../yaml/multiline/folded_strip.yaml | 7 ++ .../resources/yaml/multiline/literal.yaml | 4 + .../resources/yaml/multiline/literal2.yaml | 10 +++ .../yaml/multiline/literal_keep.yaml | 5 ++ .../yaml/multiline/literal_strip.yaml | 5 ++ .../yaml/multiline/plain_double_quotes.yaml | 1 + .../yaml/multiline/plain_single_quotes.yaml | 3 + 11 files changed, 143 insertions(+) create mode 100644 libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/MultiLineStringsUnitTest.java create mode 100644 libraries-data-io/src/test/resources/yaml/multiline/folded.yaml create mode 100644 libraries-data-io/src/test/resources/yaml/multiline/folded2.yaml create mode 100644 libraries-data-io/src/test/resources/yaml/multiline/folded_keep.yaml create mode 100644 libraries-data-io/src/test/resources/yaml/multiline/folded_strip.yaml create mode 100644 libraries-data-io/src/test/resources/yaml/multiline/literal.yaml create mode 100644 libraries-data-io/src/test/resources/yaml/multiline/literal2.yaml create mode 100644 libraries-data-io/src/test/resources/yaml/multiline/literal_keep.yaml create mode 100644 libraries-data-io/src/test/resources/yaml/multiline/literal_strip.yaml create mode 100644 libraries-data-io/src/test/resources/yaml/multiline/plain_double_quotes.yaml create mode 100644 libraries-data-io/src/test/resources/yaml/multiline/plain_single_quotes.yaml diff --git a/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/MultiLineStringsUnitTest.java b/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/MultiLineStringsUnitTest.java new file mode 100644 index 0000000000..836ac86339 --- /dev/null +++ b/libraries-data-io/src/test/java/com/baeldung/libraries/snakeyaml/MultiLineStringsUnitTest.java @@ -0,0 +1,90 @@ +package com.baeldung.libraries.snakeyaml; + +import org.junit.Before; +import org.junit.Test; +import org.yaml.snakeyaml.Yaml; + +import java.io.File; +import java.io.InputStream; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class MultiLineStringsUnitTest { + + private Yaml yaml; + + @Before + public void setup() { + yaml = new Yaml(); + } + + @Test + public void whenLiteral_ThenLineBreaksArePresent() { + String key = parseYamlKey("literal.yaml", "key"); + assertEquals("Line1\nLine2\nLine3", key); + } + + @Test + public void whenLiteral_ThenEndingBreaksAreReducedToOne() { + String key = parseYamlKey("literal2.yaml", "key"); + assertEquals("\n\nLine1\n\nLine2\n\nLine3\n", key); + } + + @Test + public void whenFolded_ThenLineBreaksAreReplaced() { + String key = parseYamlKey("folded.yaml", "key"); + assertEquals("Line1 Line2 Line3", key); + } + + @Test + public void whenFolded_ThenEmptyLinesAreReducedToOne() { + String key = parseYamlKey("folded2.yaml", "key"); + assertEquals("Line1 Line2\n\nLine3\n", key); + } + + @Test + public void whenLiteralKeep_ThenLastEmptyLinesArePresent() { + String key = parseYamlKey("literal_keep.yaml", "key"); + assertEquals("Line1\nLine2\nLine3\n\n", key); + } + + @Test + public void whenLiteralStrip_ThenLastEmptyLinesAreRemoved() { + String key = parseYamlKey("literal_strip.yaml", "key"); + assertEquals("Line1\nLine2\nLine3", key); + } + + @Test + public void whenFoldedKeep_ThenLastEmptyLinesArePresent() { + String key = parseYamlKey("folded_keep.yaml", "key"); + assertEquals("Line1 Line2 Line3\n\n\n", key); + } + + @Test + public void whenFoldedStrip_ThenLastEmptyLinesAreRemoved() { + String key = parseYamlKey("folded_strip.yaml", "key"); + assertEquals("Line1 Line2 Line3", key); + } + + @Test + public void whenDoubleQuotes_ThenExplicitBreaksArePreserved() { + String key = parseYamlKey("plain_double_quotes.yaml", "key"); + assertEquals("Line1\nLine2\nLine3", key); + } + + @Test + public void whenSingleQuotes_ThenExplicitBreaksAreIgnored() { + String key = parseYamlKey("plain_single_quotes.yaml", "key"); + assertEquals("Line1\\nLine2\nLine3", key); + } + + String parseYamlKey(String fileName, String key) { + InputStream inputStream = this.getClass() + .getClassLoader() + .getResourceAsStream("yaml" + File.separator + "multiline" + File.separator + fileName); + Map parsed = yaml.load(inputStream); + return parsed.get(key); + } + +} diff --git a/libraries-data-io/src/test/resources/yaml/multiline/folded.yaml b/libraries-data-io/src/test/resources/yaml/multiline/folded.yaml new file mode 100644 index 0000000000..c5fa743a08 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/folded.yaml @@ -0,0 +1,4 @@ +key: > + Line1 + Line2 + Line3 \ No newline at end of file diff --git a/libraries-data-io/src/test/resources/yaml/multiline/folded2.yaml b/libraries-data-io/src/test/resources/yaml/multiline/folded2.yaml new file mode 100644 index 0000000000..735abf9b2f --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/folded2.yaml @@ -0,0 +1,8 @@ +key: > + Line1 + Line2 + + + Line3 + + diff --git a/libraries-data-io/src/test/resources/yaml/multiline/folded_keep.yaml b/libraries-data-io/src/test/resources/yaml/multiline/folded_keep.yaml new file mode 100644 index 0000000000..555291fd26 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/folded_keep.yaml @@ -0,0 +1,6 @@ +key: >+ + Line1 + Line2 + Line3 + + diff --git a/libraries-data-io/src/test/resources/yaml/multiline/folded_strip.yaml b/libraries-data-io/src/test/resources/yaml/multiline/folded_strip.yaml new file mode 100644 index 0000000000..0a3a246dc2 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/folded_strip.yaml @@ -0,0 +1,7 @@ +key: >- + Line1 + Line2 + Line3 + + + diff --git a/libraries-data-io/src/test/resources/yaml/multiline/literal.yaml b/libraries-data-io/src/test/resources/yaml/multiline/literal.yaml new file mode 100644 index 0000000000..7e02501a33 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/literal.yaml @@ -0,0 +1,4 @@ +key: | + Line1 + Line2 + Line3 \ No newline at end of file diff --git a/libraries-data-io/src/test/resources/yaml/multiline/literal2.yaml b/libraries-data-io/src/test/resources/yaml/multiline/literal2.yaml new file mode 100644 index 0000000000..7c7fed0163 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/literal2.yaml @@ -0,0 +1,10 @@ +key: | + + + Line1 + + Line2 + + Line3 + + diff --git a/libraries-data-io/src/test/resources/yaml/multiline/literal_keep.yaml b/libraries-data-io/src/test/resources/yaml/multiline/literal_keep.yaml new file mode 100644 index 0000000000..37f22684dd --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/literal_keep.yaml @@ -0,0 +1,5 @@ +key: |+ + Line1 + Line2 + Line3 + diff --git a/libraries-data-io/src/test/resources/yaml/multiline/literal_strip.yaml b/libraries-data-io/src/test/resources/yaml/multiline/literal_strip.yaml new file mode 100644 index 0000000000..0791e13d5d --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/literal_strip.yaml @@ -0,0 +1,5 @@ +key: |- + Line1 + Line2 + Line3 + diff --git a/libraries-data-io/src/test/resources/yaml/multiline/plain_double_quotes.yaml b/libraries-data-io/src/test/resources/yaml/multiline/plain_double_quotes.yaml new file mode 100644 index 0000000000..ccab040a27 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/plain_double_quotes.yaml @@ -0,0 +1 @@ +key: "Line1\nLine2\nLine3" \ No newline at end of file diff --git a/libraries-data-io/src/test/resources/yaml/multiline/plain_single_quotes.yaml b/libraries-data-io/src/test/resources/yaml/multiline/plain_single_quotes.yaml new file mode 100644 index 0000000000..acbf35a462 --- /dev/null +++ b/libraries-data-io/src/test/resources/yaml/multiline/plain_single_quotes.yaml @@ -0,0 +1,3 @@ +key: 'Line1\nLine2 + + Line3' \ No newline at end of file From 7feb9bfb1ec7e9502d482fef57867439f831f6b4 Mon Sep 17 00:00:00 2001 From: crist Date: Mon, 10 Feb 2020 15:29:53 +0200 Subject: [PATCH 07/91] [BAEL-3750] deleted the yaml module --- pom.xml | 2 - yaml/README.md | 7 -- yaml/pom.xml | 29 ------ .../multiline/MultiLineStringsUnitTest.java | 90 ------------------- .../src/test/resources/multi-line/folded.yaml | 4 - .../test/resources/multi-line/folded2.yaml | 8 -- .../resources/multi-line/folded_keep.yaml | 6 -- .../resources/multi-line/folded_strip.yaml | 7 -- .../test/resources/multi-line/literal.yaml | 4 - .../test/resources/multi-line/literal2.yaml | 10 --- .../resources/multi-line/literal_keep.yaml | 5 -- .../resources/multi-line/literal_strip.yaml | 5 -- .../multi-line/plain_double_quotes.yaml | 1 - .../multi-line/plain_single_quotes.yaml | 3 - 14 files changed, 181 deletions(-) delete mode 100644 yaml/README.md delete mode 100644 yaml/pom.xml delete mode 100644 yaml/src/test/java/com/baeldung/multiline/MultiLineStringsUnitTest.java delete mode 100644 yaml/src/test/resources/multi-line/folded.yaml delete mode 100644 yaml/src/test/resources/multi-line/folded2.yaml delete mode 100644 yaml/src/test/resources/multi-line/folded_keep.yaml delete mode 100644 yaml/src/test/resources/multi-line/folded_strip.yaml delete mode 100644 yaml/src/test/resources/multi-line/literal.yaml delete mode 100644 yaml/src/test/resources/multi-line/literal2.yaml delete mode 100644 yaml/src/test/resources/multi-line/literal_keep.yaml delete mode 100644 yaml/src/test/resources/multi-line/literal_strip.yaml delete mode 100644 yaml/src/test/resources/multi-line/plain_double_quotes.yaml delete mode 100644 yaml/src/test/resources/multi-line/plain_single_quotes.yaml diff --git a/pom.xml b/pom.xml index b0d3f2297d..0c9896cf35 100644 --- a/pom.xml +++ b/pom.xml @@ -782,7 +782,6 @@ wildfly xml xstream - yaml @@ -1307,7 +1306,6 @@ wildfly xml xstream - yaml diff --git a/yaml/README.md b/yaml/README.md deleted file mode 100644 index ebf403eb57..0000000000 --- a/yaml/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## YAML - -This module contains articles about YAML - -### Relevant articles - - diff --git a/yaml/pom.xml b/yaml/pom.xml deleted file mode 100644 index c801505c6a..0000000000 --- a/yaml/pom.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - 4.0.0 - yaml - 1.0-SNAPSHOT - - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - - - - - org.yaml - snakeyaml - 1.21 - - - - - 1.8 - 1.21 - - - \ No newline at end of file diff --git a/yaml/src/test/java/com/baeldung/multiline/MultiLineStringsUnitTest.java b/yaml/src/test/java/com/baeldung/multiline/MultiLineStringsUnitTest.java deleted file mode 100644 index a99de63a47..0000000000 --- a/yaml/src/test/java/com/baeldung/multiline/MultiLineStringsUnitTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.baeldung.multiline; - -import org.junit.Before; -import org.junit.Test; -import org.yaml.snakeyaml.Yaml; - -import java.io.File; -import java.io.InputStream; -import java.util.Map; - -import static org.junit.Assert.assertEquals; - -public class MultiLineStringsUnitTest { - - private Yaml yaml; - - @Before - public void setup() { - yaml = new Yaml(); - } - - @Test - public void whenLiteral_ThenLineBreaksArePresent() { - String key = parseYamlKey("literal.yaml", "key"); - assertEquals("Line1\nLine2\nLine3", key); - } - - @Test - public void whenLiteral_ThenEndingBreaksAreReducedToOne() { - String key = parseYamlKey("literal2.yaml", "key"); - assertEquals("\n\nLine1\n\nLine2\n\nLine3\n", key); - } - - @Test - public void whenFolded_ThenLineBreaksAreReplaced() { - String key = parseYamlKey("folded.yaml", "key"); - assertEquals("Line1 Line2 Line3", key); - } - - @Test - public void whenFolded_ThenEmptyLinesAreReducedToOne() { - String key = parseYamlKey("folded2.yaml", "key"); - assertEquals("Line1 Line2\n\nLine3\n", key); - } - - @Test - public void whenLiteralKeep_ThenLastEmptyLinesArePresent() { - String key = parseYamlKey("literal_keep.yaml", "key"); - assertEquals("Line1\nLine2\nLine3\n\n", key); - } - - @Test - public void whenLiteralStrip_ThenLastEmptyLinesAreRemoved() { - String key = parseYamlKey("literal_strip.yaml", "key"); - assertEquals("Line1\nLine2\nLine3", key); - } - - @Test - public void whenFoldedKeep_ThenLastEmptyLinesArePresent() { - String key = parseYamlKey("folded_keep.yaml", "key"); - assertEquals("Line1 Line2 Line3\n\n\n", key); - } - - @Test - public void whenFoldedStrip_ThenLastEmptyLinesAreRemoved() { - String key = parseYamlKey("folded_strip.yaml", "key"); - assertEquals("Line1 Line2 Line3", key); - } - - @Test - public void whenDoubleQuotes_ThenExplicitBreaksArePreserved() { - String key = parseYamlKey("plain_double_quotes.yaml", "key"); - assertEquals("Line1\nLine2\nLine3", key); - } - - @Test - public void whenSingleQuotes_ThenExplicitBreaksAreIgnored() { - String key = parseYamlKey("plain_single_quotes.yaml", "key"); - assertEquals("Line1\\nLine2\nLine3", key); - } - - String parseYamlKey(String fileName, String key) { - InputStream inputStream = this.getClass() - .getClassLoader() - .getResourceAsStream("multi-line" + File.separator + fileName); - Map parsed = yaml.load(inputStream); - return parsed.get(key); - } - -} diff --git a/yaml/src/test/resources/multi-line/folded.yaml b/yaml/src/test/resources/multi-line/folded.yaml deleted file mode 100644 index c5fa743a08..0000000000 --- a/yaml/src/test/resources/multi-line/folded.yaml +++ /dev/null @@ -1,4 +0,0 @@ -key: > - Line1 - Line2 - Line3 \ No newline at end of file diff --git a/yaml/src/test/resources/multi-line/folded2.yaml b/yaml/src/test/resources/multi-line/folded2.yaml deleted file mode 100644 index 735abf9b2f..0000000000 --- a/yaml/src/test/resources/multi-line/folded2.yaml +++ /dev/null @@ -1,8 +0,0 @@ -key: > - Line1 - Line2 - - - Line3 - - diff --git a/yaml/src/test/resources/multi-line/folded_keep.yaml b/yaml/src/test/resources/multi-line/folded_keep.yaml deleted file mode 100644 index 555291fd26..0000000000 --- a/yaml/src/test/resources/multi-line/folded_keep.yaml +++ /dev/null @@ -1,6 +0,0 @@ -key: >+ - Line1 - Line2 - Line3 - - diff --git a/yaml/src/test/resources/multi-line/folded_strip.yaml b/yaml/src/test/resources/multi-line/folded_strip.yaml deleted file mode 100644 index 0a3a246dc2..0000000000 --- a/yaml/src/test/resources/multi-line/folded_strip.yaml +++ /dev/null @@ -1,7 +0,0 @@ -key: >- - Line1 - Line2 - Line3 - - - diff --git a/yaml/src/test/resources/multi-line/literal.yaml b/yaml/src/test/resources/multi-line/literal.yaml deleted file mode 100644 index 7e02501a33..0000000000 --- a/yaml/src/test/resources/multi-line/literal.yaml +++ /dev/null @@ -1,4 +0,0 @@ -key: | - Line1 - Line2 - Line3 \ No newline at end of file diff --git a/yaml/src/test/resources/multi-line/literal2.yaml b/yaml/src/test/resources/multi-line/literal2.yaml deleted file mode 100644 index 7c7fed0163..0000000000 --- a/yaml/src/test/resources/multi-line/literal2.yaml +++ /dev/null @@ -1,10 +0,0 @@ -key: | - - - Line1 - - Line2 - - Line3 - - diff --git a/yaml/src/test/resources/multi-line/literal_keep.yaml b/yaml/src/test/resources/multi-line/literal_keep.yaml deleted file mode 100644 index 37f22684dd..0000000000 --- a/yaml/src/test/resources/multi-line/literal_keep.yaml +++ /dev/null @@ -1,5 +0,0 @@ -key: |+ - Line1 - Line2 - Line3 - diff --git a/yaml/src/test/resources/multi-line/literal_strip.yaml b/yaml/src/test/resources/multi-line/literal_strip.yaml deleted file mode 100644 index 0791e13d5d..0000000000 --- a/yaml/src/test/resources/multi-line/literal_strip.yaml +++ /dev/null @@ -1,5 +0,0 @@ -key: |- - Line1 - Line2 - Line3 - diff --git a/yaml/src/test/resources/multi-line/plain_double_quotes.yaml b/yaml/src/test/resources/multi-line/plain_double_quotes.yaml deleted file mode 100644 index ccab040a27..0000000000 --- a/yaml/src/test/resources/multi-line/plain_double_quotes.yaml +++ /dev/null @@ -1 +0,0 @@ -key: "Line1\nLine2\nLine3" \ No newline at end of file diff --git a/yaml/src/test/resources/multi-line/plain_single_quotes.yaml b/yaml/src/test/resources/multi-line/plain_single_quotes.yaml deleted file mode 100644 index acbf35a462..0000000000 --- a/yaml/src/test/resources/multi-line/plain_single_quotes.yaml +++ /dev/null @@ -1,3 +0,0 @@ -key: 'Line1\nLine2 - - Line3' \ No newline at end of file From 2401a9af7d767d42b37d99e4d1ab6ae356c316bc Mon Sep 17 00:00:00 2001 From: Nacho Verdu Date: Mon, 16 Mar 2020 18:37:46 +0000 Subject: [PATCH 08/91] BAEL-3912: Changes done --- .../getweeknumber/GetWeekNumberNewJava.java | 29 +++++++++++++++ .../getweeknumber/GetWeekNumberOldJava.java | 35 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberNewJava.java create mode 100644 core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberOldJava.java diff --git a/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberNewJava.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberNewJava.java new file mode 100644 index 0000000000..abe9367fc2 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberNewJava.java @@ -0,0 +1,29 @@ +package com.baeldung.getweeknumber; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +public class GetWeekNumberNewJava { + private LocalDate date; + + public GetWeekNumberNewJava(String day, String dayFormat) { + date = LocalDate.parse(day, DateTimeFormatter.ofPattern(dayFormat)); + } + + public GetWeekNumberNewJava(int year, int month, int day) { + date = LocalDate.of(year, month, day); + } + + public DayOfWeek getDayOfWeek() { + return date.getDayOfWeek(); + } + + public static void main(String[] args) { + GetWeekNumberNewJava example1 = new GetWeekNumberNewJava(2020, 3, 2); + System.out.println(example1.getDayOfWeek()); + + GetWeekNumberNewJava example2 = new GetWeekNumberNewJava("20200302", "yyyyMMdd"); + System.out.println(example2.getDayOfWeek().getValue()); + } +} diff --git a/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberOldJava.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberOldJava.java new file mode 100644 index 0000000000..6a63d24607 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberOldJava.java @@ -0,0 +1,35 @@ +package com.baeldung.getweeknumber; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +public class GetWeekNumberOldJava { + private Calendar calendar; + + public GetWeekNumberOldJava(String day, String dayFormat) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat(dayFormat); + + calendar = Calendar.getInstance(); + Date date = sdf.parse(day); + calendar.setTime(date); + } + + public GetWeekNumberOldJava(int year, int month, int day) { + calendar = Calendar.getInstance(); + calendar.set(year, month, day); + } + + public int getDayOfWeek() { + return calendar.get(Calendar.DAY_OF_WEEK); + } + + public static void main(String[] args) throws ParseException { + GetWeekNumberOldJava example1 = new GetWeekNumberOldJava(2020, 2, 2); + System.out.println(example1.getDayOfWeek()); + + GetWeekNumberOldJava example2 = new GetWeekNumberOldJava("20200302", "yyyyMMdd"); + System.out.println(example2.getDayOfWeek()); + } +} From 5249021b680b550922c2fed9a4770601ce38c4a1 Mon Sep 17 00:00:00 2001 From: Nacho Verdu Date: Wed, 18 Mar 2020 18:22:32 +0000 Subject: [PATCH 09/91] BAEL-3912: Changes done for comments BAEL-3912: Changes done for comments BAEL-3912: Changes done for comments BAEL-3912: Changes done for comments BAEL-3912: Changes done for comments BAEL-3912: Changes done for comments BAEL-3912: Changes done for comments --- .../getweeknumber/GetWeekNumberNewJava.java | 29 ----------- .../getweeknumber/GetWeekNumberOldJava.java | 35 ------------- .../weeknumber/WeekNumberUsingCalendar.java | 41 ++++++++++++++++ .../weeknumber/WeekNumberUsingLocalDate.java | 30 ++++++++++++ .../WeekNumberUsingCalendarUnitTest.java | 46 +++++++++++++++++ .../WeekNumberUsingLocalDateUnitTest.java | 49 +++++++++++++++++++ 6 files changed, 166 insertions(+), 64 deletions(-) delete mode 100644 core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberNewJava.java delete mode 100644 core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberOldJava.java create mode 100644 core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/weeknumber/WeekNumberUsingCalendar.java create mode 100644 core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/weeknumber/WeekNumberUsingLocalDate.java create mode 100644 core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/weeknumber/WeekNumberUsingCalendarUnitTest.java create mode 100644 core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/weeknumber/WeekNumberUsingLocalDateUnitTest.java diff --git a/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberNewJava.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberNewJava.java deleted file mode 100644 index abe9367fc2..0000000000 --- a/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberNewJava.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.getweeknumber; - -import java.time.DayOfWeek; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; - -public class GetWeekNumberNewJava { - private LocalDate date; - - public GetWeekNumberNewJava(String day, String dayFormat) { - date = LocalDate.parse(day, DateTimeFormatter.ofPattern(dayFormat)); - } - - public GetWeekNumberNewJava(int year, int month, int day) { - date = LocalDate.of(year, month, day); - } - - public DayOfWeek getDayOfWeek() { - return date.getDayOfWeek(); - } - - public static void main(String[] args) { - GetWeekNumberNewJava example1 = new GetWeekNumberNewJava(2020, 3, 2); - System.out.println(example1.getDayOfWeek()); - - GetWeekNumberNewJava example2 = new GetWeekNumberNewJava("20200302", "yyyyMMdd"); - System.out.println(example2.getDayOfWeek().getValue()); - } -} diff --git a/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberOldJava.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberOldJava.java deleted file mode 100644 index 6a63d24607..0000000000 --- a/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/getweeknumber/GetWeekNumberOldJava.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.getweeknumber; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; - -public class GetWeekNumberOldJava { - private Calendar calendar; - - public GetWeekNumberOldJava(String day, String dayFormat) throws ParseException { - SimpleDateFormat sdf = new SimpleDateFormat(dayFormat); - - calendar = Calendar.getInstance(); - Date date = sdf.parse(day); - calendar.setTime(date); - } - - public GetWeekNumberOldJava(int year, int month, int day) { - calendar = Calendar.getInstance(); - calendar.set(year, month, day); - } - - public int getDayOfWeek() { - return calendar.get(Calendar.DAY_OF_WEEK); - } - - public static void main(String[] args) throws ParseException { - GetWeekNumberOldJava example1 = new GetWeekNumberOldJava(2020, 2, 2); - System.out.println(example1.getDayOfWeek()); - - GetWeekNumberOldJava example2 = new GetWeekNumberOldJava("20200302", "yyyyMMdd"); - System.out.println(example2.getDayOfWeek()); - } -} diff --git a/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/weeknumber/WeekNumberUsingCalendar.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/weeknumber/WeekNumberUsingCalendar.java new file mode 100644 index 0000000000..db32421aa4 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/weeknumber/WeekNumberUsingCalendar.java @@ -0,0 +1,41 @@ +package com.baeldung.weeknumber; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; + +public class WeekNumberUsingCalendar { + + public int getWeekNumberFrom(String day, String dateFormat, Locale locale) throws ParseException { + SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); + + Calendar calendar = Calendar.getInstance(locale); + Date date = sdf.parse(day); + calendar.setTime(date); + + return calendar.get(Calendar.WEEK_OF_YEAR); + } + + public int getWeekNumberFrom(int year, int month, int day, Locale locale) { + Calendar calendar = Calendar.getInstance(locale); + calendar.set(year, month, day); + + return calendar.get(Calendar.WEEK_OF_YEAR); + } + + public int getWeekNumberFrom(int year, int month, int day, int firstDayOfWeek, int minimalDaysInFirstWeek, Locale locale) { + Calendar calendar = Calendar.getInstance(locale); + calendar.setFirstDayOfWeek(firstDayOfWeek); + calendar.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek); + calendar.set(year, month, day); + + return calendar.get(Calendar.WEEK_OF_YEAR); + } + + public static void main(String[] args) { + WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar(); + System.out.println(calendar.getWeekNumberFrom(2020, 2, 22, Locale.CANADA)); + } +} diff --git a/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/weeknumber/WeekNumberUsingLocalDate.java b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/weeknumber/WeekNumberUsingLocalDate.java new file mode 100644 index 0000000000..4e1b7be3be --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/main/java/com/baeldung/weeknumber/WeekNumberUsingLocalDate.java @@ -0,0 +1,30 @@ +package com.baeldung.weeknumber; + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoField; +import java.time.temporal.WeekFields; +import java.util.Locale; + +public class WeekNumberUsingLocalDate { + + public Integer getWeekNumberUsingWeekFiedsFrom(String day, String dayFormat, Locale locale) { + LocalDate date = LocalDate.parse(day, DateTimeFormatter.ofPattern(dayFormat)); + + return date.get(WeekFields.of(locale) + .weekOfYear()); + } + + public Integer getWeekNumberUsinWeekFieldsFrom(int year, int month, int day, Locale locale) { + LocalDate date = LocalDate.of(year, month, day); + + return date.get(WeekFields.of(locale) + .weekOfYear()); + } + + public Integer getWeekNumberUsingChronoFieldFrom(int year, int month, int day) { + LocalDate date = LocalDate.of(year, month, day); + + return date.get(ChronoField.ALIGNED_WEEK_OF_YEAR); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/weeknumber/WeekNumberUsingCalendarUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/weeknumber/WeekNumberUsingCalendarUnitTest.java new file mode 100644 index 0000000000..587a459277 --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/weeknumber/WeekNumberUsingCalendarUnitTest.java @@ -0,0 +1,46 @@ +package com.baeldung.weeknumber; + +import static org.junit.Assert.assertEquals; + +import java.text.ParseException; +import java.util.Calendar; +import java.util.Locale; + +import org.junit.Test; + +public class WeekNumberUsingCalendarUnitTest { + @Test + public void givenDateInStringAndDateFormatUsingLocaleItaly_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() throws ParseException { + WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar(); + + assertEquals(12, calendar.getWeekNumberFrom("20200322", "yyyyMMdd", Locale.ITALY)); + } + + @Test + public void givenDateInStringAndDateFormatUsingLocaleCanada_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() throws ParseException { + WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar(); + + assertEquals(13, calendar.getWeekNumberFrom("20200322", "yyyyMMdd", Locale.CANADA)); + } + + @Test + public void givenDateInYearMonthDayNumbersLocaleItaly_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() { + WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar(); + + assertEquals(12, calendar.getWeekNumberFrom(2020, 2, 22, Locale.ITALY)); + } + + @Test + public void givenDateInYearMonthDayNumbersLocaleItalyChangingWeekCalculationSettings_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() { + WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar(); + + assertEquals(13, calendar.getWeekNumberFrom(2020, 2, 22, Calendar.SUNDAY, 4, Locale.ITALY)); + } + + @Test + public void givenDateInYearMonthDayNumbersLocaleCanada_thenGettingWeekNumberUsingCalendarIsCorrectlyReturned() { + WeekNumberUsingCalendar calendar = new WeekNumberUsingCalendar(); + + assertEquals(13, calendar.getWeekNumberFrom(2020, 2, 22, Locale.CANADA)); + } +} diff --git a/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/weeknumber/WeekNumberUsingLocalDateUnitTest.java b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/weeknumber/WeekNumberUsingLocalDateUnitTest.java new file mode 100644 index 0000000000..9b98222ece --- /dev/null +++ b/core-java-modules/core-java-date-operations-2/src/test/java/com/baeldung/weeknumber/WeekNumberUsingLocalDateUnitTest.java @@ -0,0 +1,49 @@ +package com.baeldung.weeknumber; + +import static org.junit.Assert.assertEquals; + +import java.util.Locale; + +import org.junit.Test; + +public class WeekNumberUsingLocalDateUnitTest { + @Test + public void givenDateInStringAndDateFormatUsingWeekFieldsWithLocaleItaly_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() { + WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate(); + + assertEquals(12, localDate.getWeekNumberUsingWeekFiedsFrom("20200322", "yyyyMMdd", Locale.ITALY) + .longValue()); + } + + @Test + public void givenDateInStringAndDateFormatUsingWeekFieldsWithLocaleCanada_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() { + WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate(); + + assertEquals(13, localDate.getWeekNumberUsingWeekFiedsFrom("20200322", "yyyyMMdd", Locale.CANADA) + .longValue()); + } + + @Test + public void givenDateInStringAndDateFormatUsingChronoFieds_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() { + WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate(); + + assertEquals(12, localDate.getWeekNumberUsingChronoFieldFrom(2020, 3, 22) + .longValue()); + } + + @Test + public void givenDateInYearMonthDayNumbersUsingWeekFieldsWithLocaleItaly_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() { + WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate(); + + assertEquals(12, localDate.getWeekNumberUsinWeekFieldsFrom(2020, 3, 22, Locale.ITALY) + .longValue()); + } + + @Test + public void givenDateInYearMonthDayNumbersUsingWeekFieldsWithLocaleCanada_thenGettingWeekNumberUsingLocalDateIsCorrectlyReturned() { + WeekNumberUsingLocalDate localDate = new WeekNumberUsingLocalDate(); + + assertEquals(13, localDate.getWeekNumberUsinWeekFieldsFrom(2020, 3, 22, Locale.CANADA) + .longValue()); + } +} From 5b59902cb254becc9521689d8a01c3d184f941b2 Mon Sep 17 00:00:00 2001 From: Kyle Doyle Date: Thu, 16 Apr 2020 09:55:40 -0400 Subject: [PATCH 10/91] Removed rest of project --- aws-app-sync/pom.xml | 49 +++++++++++++++++++ .../awsappsync/AwsAppSyncApplication.java | 13 +++++ .../src/main/resources/application.properties | 1 + .../AwsAppSyncApplicationTests.java | 13 +++++ 4 files changed, 76 insertions(+) create mode 100644 aws-app-sync/pom.xml create mode 100644 aws-app-sync/src/main/java/com/baeldung/awsappsync/AwsAppSyncApplication.java create mode 100644 aws-app-sync/src/main/resources/application.properties create mode 100644 aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java diff --git a/aws-app-sync/pom.xml b/aws-app-sync/pom.xml new file mode 100644 index 0000000000..af02307e66 --- /dev/null +++ b/aws-app-sync/pom.xml @@ -0,0 +1,49 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + + com.baeldung + aws-app-sync + 0.0.1-SNAPSHOT + aws-app-sync + Demo project for Spring Boot using AWS App Sync + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/aws-app-sync/src/main/java/com/baeldung/awsappsync/AwsAppSyncApplication.java b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AwsAppSyncApplication.java new file mode 100644 index 0000000000..ae012c91a5 --- /dev/null +++ b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AwsAppSyncApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.awsappsync; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AwsAppSyncApplication { + + public static void main(String[] args) { + SpringApplication.run(AwsAppSyncApplication.class, args); + } + +} diff --git a/aws-app-sync/src/main/resources/application.properties b/aws-app-sync/src/main/resources/application.properties new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/aws-app-sync/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java new file mode 100644 index 0000000000..7b82393865 --- /dev/null +++ b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java @@ -0,0 +1,13 @@ +package com.baeldung.awsappsync; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AwsAppSyncApplicationTests { + + @Test + void contextLoads() { + } + +} From 6bf0d97d62bdfe986fde782544d47ebba9cb9705 Mon Sep 17 00:00:00 2001 From: Kyle Doyle Date: Fri, 17 Apr 2020 19:50:36 -0400 Subject: [PATCH 11/91] Bael-3893 AWS AppSync with Spring Boot --- aws-app-sync/pom.xml | 15 +++- .../src/main/resources/application.properties | 1 - .../AwsAppSyncApplicationTests.java | 90 ++++++++++++++++++- 3 files changed, 102 insertions(+), 4 deletions(-) delete mode 100644 aws-app-sync/src/main/resources/application.properties diff --git a/aws-app-sync/pom.xml b/aws-app-sync/pom.xml index af02307e66..d30cfc96a4 100644 --- a/aws-app-sync/pom.xml +++ b/aws-app-sync/pom.xml @@ -8,17 +8,26 @@ 2.2.6.RELEASE + com.baeldung aws-app-sync 0.0.1-SNAPSHOT aws-app-sync - Demo project for Spring Boot using AWS App Sync + + Spring Boot using AWS App Sync 1.8 + + + com.amazonaws + aws-java-sdk-appsync + 1.11.762 + + org.springframework.boot spring-boot-starter-web @@ -35,6 +44,10 @@ + + org.springframework.boot + spring-boot-starter-webflux + diff --git a/aws-app-sync/src/main/resources/application.properties b/aws-app-sync/src/main/resources/application.properties deleted file mode 100644 index 8b13789179..0000000000 --- a/aws-app-sync/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ - diff --git a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java index 7b82393865..15bcc6e9c9 100644 --- a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java +++ b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java @@ -1,13 +1,99 @@ package com.baeldung.awsappsync; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; @SpringBootTest class AwsAppSyncApplicationTests { - @Test - void contextLoads() { + static String apiUrl = "https://m4i3b6icrrb7livfbypfspiifi.appsync-api.us-east-2.amazonaws.com"; + static String apiKey = "da2-es2s6oj4mzhbxk5yu26ss2ruj4"; + static String API_KEY_HEADER = "x-api-key"; + + static WebClient.RequestBodySpec requestBodySpec; + + @BeforeAll + static void setUp() { + requestBodySpec = WebClient + .builder() + .baseUrl(apiUrl) + .defaultHeader(API_KEY_HEADER, apiKey) + .build() + .method(HttpMethod.POST) + .uri("/graphql"); } + @Test + void testGraphQuery() { + + Map requestBody = new HashMap<>(); + requestBody.put("query", "query ListEvents {\n" + + " listEvents {\n" + + " items {\n" + + " id\n" + + " name\n" + + " where\n" + + " when\n" + + " description\n" + + " }\n" + + " }\n" + + "}"); + requestBody.put("variables", ""); + requestBody.put("operationName", "ListEvents"); + + WebClient.ResponseSpec response = requestBodySpec + .body(BodyInserters.fromValue(requestBody)) + .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) + .acceptCharset(StandardCharsets.UTF_8) + .retrieve(); + + String bodyString = response.bodyToMono(String.class).block(); + + assertTrue(bodyString != null && bodyString.contains("My First Event")); + } + + @Test + void testGraphAdd() { + + String queryString = "mutation add {\n" + + " createEvent(\n" + + " name:\"My added GraphQL event\"\n" + + " where:\"Day 2\"\n" + + " when:\"Saturday night\"\n" + + " description:\"Studying GraphQL\"\n" + + " ){\n" + + " id\n" + + " name\n" + + " where\n" + + " when\n" + + " description\n" + + " }\n" + + "}"; + + + Map requestBody = new HashMap<>(); + requestBody.put("query", queryString); + requestBody.put("variables", ""); + requestBody.put("operationName", "add"); + + WebClient.ResponseSpec response = requestBodySpec + .body(BodyInserters.fromValue(requestBody)) + .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) + .acceptCharset(StandardCharsets.UTF_8) + .retrieve(); + + String bodyString = response.bodyToMono(String.class).block(); + assertTrue(bodyString != null && bodyString.contains("Day 2")); + } } From 9a1e98598f8c8015dff5dc2edc86446d28f606b6 Mon Sep 17 00:00:00 2001 From: Kyle Doyle Date: Fri, 17 Apr 2020 19:56:42 -0400 Subject: [PATCH 12/91] Bael-3893 AWS AppSync with Spring Boot --- .../awsappsync/AwsAppSyncApplicationTests.java | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java index 15bcc6e9c9..005d533cbf 100644 --- a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java +++ b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java @@ -35,7 +35,7 @@ class AwsAppSyncApplicationTests { } @Test - void testGraphQuery() { + void givenGraphQuery_whenListEvents_thenReturnAllEvents() { Map requestBody = new HashMap<>(); requestBody.put("query", "query ListEvents {\n" + @@ -60,11 +60,14 @@ class AwsAppSyncApplicationTests { String bodyString = response.bodyToMono(String.class).block(); - assertTrue(bodyString != null && bodyString.contains("My First Event")); + assertNotNull(bodyString); + assertTrue(bodyString.contains("My First Event")); + assertTrue(bodyString.contains("where")); + assertTrue(bodyString.contains("when")); } @Test - void testGraphAdd() { + void givenGraphAdd_whenMutation_thenReturnIdNameDesc() { String queryString = "mutation add {\n" + " createEvent(\n" + @@ -75,8 +78,6 @@ class AwsAppSyncApplicationTests { " ){\n" + " id\n" + " name\n" + - " where\n" + - " when\n" + " description\n" + " }\n" + "}"; @@ -94,6 +95,10 @@ class AwsAppSyncApplicationTests { .retrieve(); String bodyString = response.bodyToMono(String.class).block(); - assertTrue(bodyString != null && bodyString.contains("Day 2")); + + assertNotNull(bodyString); + assertTrue(bodyString.contains("My added GraphQL event")); + assertFalse(bodyString.contains("where")); + assertFalse(bodyString.contains("when")); } } From 3746a5328554b56ff614d5abf328f104e4b6c727 Mon Sep 17 00:00:00 2001 From: Kyle Doyle Date: Fri, 17 Apr 2020 20:16:59 -0400 Subject: [PATCH 13/91] Bael 3893 - Added to modules --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 71e5d21b02..22d73f3a9e 100644 --- a/pom.xml +++ b/pom.xml @@ -1015,6 +1015,7 @@ asm atomix aws + aws-app-sync aws-lambda axon azure From 3233f80c5b0df473890982e561c41cea53e06a28 Mon Sep 17 00:00:00 2001 From: sergio41 Date: Sun, 19 Apr 2020 22:37:21 +0200 Subject: [PATCH 14/91] [BAEL-3944] Code Upload --- .../com/baeldung/regex/RegexUnitTest.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/RegexUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/RegexUnitTest.java index b3c3a91a09..909894ec55 100644 --- a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/RegexUnitTest.java +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/RegexUnitTest.java @@ -481,6 +481,50 @@ public class RegexUnitTest { } + @Test + public void whenMatchesTenDigitsNumber_thenCorrect() { + Pattern pattern = Pattern.compile("^\\d{10}$"); + Matcher matcher = pattern.matcher("1234567890"); + assertTrue(matcher.matches()); + } + + @Test + public void whenMatchesTenDigitsNumberWhitespacesHyphen_thenCorrect() { + Pattern pattern = Pattern.compile("^(\\d{3}[- ]?){2}\\d{4}$"); + Matcher matcher = pattern.matcher("123 456 7890"); + assertTrue(matcher.matches()); + } + + @Test + public void whenMatchesTenDigitsNumberParenthesis_thenCorrect() { + Pattern pattern = Pattern.compile("^\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$"); + Matcher matcher = pattern.matcher("(123)-456-7890"); + assertTrue(matcher.matches()); + } + + @Test + public void whenMatchesTenDigitsNumberPrefix_thenCorrect() { + Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$"); + Matcher matcher = pattern.matcher("+111 (123)-456-7890"); + assertTrue(matcher.matches()); + } + + @Test + public void whenMatchesPhoneNumber_thenCorrect() { + String patterns = "^(\\+\\d{1,3}( )?)?\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$" + + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$" + + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$"; + + String[] validPhoneNumbers = {"1234567890","123 456 7890", "(123)-456-7890", "+111 (123)-456-7890", + "123 456 789", "+111 123 456 789", "123 45 67 89", "+111 123 45 67 89"}; + + Pattern pattern = Pattern.compile(patterns); + for(String phoneNumber : validPhoneNumbers) { + Matcher matcher = pattern.matcher(phoneNumber); + assertTrue(matcher.matches()); + } + } + public synchronized static int runTest(String regex, String text) { pattern = Pattern.compile(regex); matcher = pattern.matcher(text); From b37ee5f26d08e8e24d2eae2b1aa101f6c9b62b8c Mon Sep 17 00:00:00 2001 From: Cavero Barca Date: Tue, 21 Apr 2020 15:29:47 +0200 Subject: [PATCH 15/91] Add WebFilter Factories examples configured through yaml and Java DSL --- spring-cloud/spring-cloud-gateway/pom.xml | 12 ++- .../WebFilterGatewayApplication.java | 15 +++ .../config/ModifyBodyRouteConfig.java | 49 ++++++++++ .../main/resources/application-webfilters.yml | 93 +++++++++++++++++++ 4 files changed, 165 insertions(+), 4 deletions(-) create mode 100644 spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java create mode 100644 spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/ModifyBodyRouteConfig.java create mode 100644 spring-cloud/spring-cloud-gateway/src/main/resources/application-webfilters.yml diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml index 0f62c031cf..ada32ae85f 100644 --- a/spring-cloud/spring-cloud-gateway/pom.xml +++ b/spring-cloud/spring-cloud-gateway/pom.xml @@ -49,6 +49,12 @@ spring-cloud-starter-gateway + + + org.springframework.cloud + spring-cloud-starter-circuitbreaker-reactor-resilience4j + + org.hibernate hibernate-validator-cdi @@ -84,10 +90,8 @@ - Greenwich.SR3 - - - 2.1.9.RELEASE + Hoxton.SR3 + 2.2.6.RELEASE 6.0.2.Final diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java new file mode 100644 index 0000000000..3b45e9013f --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java @@ -0,0 +1,15 @@ +package com.baeldung.springcloudgateway.webfilters; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; + +@SpringBootApplication +public class WebFilterGatewayApplication { + + public static void main(String[] args) { + new SpringApplicationBuilder(WebFilterGatewayApplication.class) + .profiles("webfilters") + .run(args); + } + +} \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/ModifyBodyRouteConfig.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/ModifyBodyRouteConfig.java new file mode 100644 index 0000000000..ccc789f287 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/ModifyBodyRouteConfig.java @@ -0,0 +1,49 @@ +package com.baeldung.springcloudgateway.webfilters.config; + +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.MediaType; + +import reactor.core.publisher.Mono; + +@Configuration +public class ModifyBodyRouteConfig { + + @Bean + public RouteLocator routes(RouteLocatorBuilder builder) { + return builder.routes() + .route("modify_request_body", r -> r.path("/post") + .filters(f -> f.modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE, + (exchange, s) -> Mono.just(new Hello(s.toUpperCase())))).uri("https://httpbin.org")) + .build(); + } + + @Bean + public RouteLocator responseRoutes(RouteLocatorBuilder builder) { + return builder.routes() + .route("modify_response_body", r -> r.path("/put/**") + .filters(f -> f.modifyResponseBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE, + (exchange, s) -> Mono.just(new Hello("New Body")))).uri("https://httpbin.org")) + .build(); + } + + static class Hello { + String message; + + public Hello() { } + + public Hello(String message) { + this.message = message; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + } +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application-webfilters.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application-webfilters.yml new file mode 100644 index 0000000000..9b3ec64f96 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application-webfilters.yml @@ -0,0 +1,93 @@ +spring: + cloud: + gateway: + routes: + - id: request_header_route + uri: https://httpbin.org + predicates: + - Path=/get/** + filters: + - AddRequestHeader=My-Header-Good,Good + - AddRequestHeader=My-Header-Remove,Remove + - AddRequestParameter=var, good + - AddRequestParameter=var2, remove + - MapRequestHeader=My-Header-Good, My-Header-Bad + - MapRequestHeader=My-Header-Set, My-Header-Bad + - SetRequestHeader=My-Header-Set, Set + - RemoveRequestHeader=My-Header-Remove + - RemoveRequestParameter=var2 + - PreserveHostHeader + + - id: response_header_route + uri: https://httpbin.org + predicates: + - Path=/header/post/** + filters: + - AddResponseHeader=My-Header-Good,Good + - AddResponseHeader=My-Header-Set,Good + - AddResponseHeader=My-Header-Rewrite, password=12345678 + - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin + - AddResponseHeader=My-Header-Remove,Remove + - SetResponseHeader=My-Header-Set, Set + - RemoveResponseHeader=My-Header-Remove + - RewriteResponseHeader=My-Header-Rewrite, password=[^&]+, password=*** + - RewriteLocationResponseHeader=AS_IN_REQUEST, Location, , + - StripPrefix=1 + + - id: path_route + uri: https://httpbin.org + predicates: + - Path=/new/post/** + filters: + - RewritePath=/new(?/?.*), $\{segment} + - SetPath=/post + + - id: redirect_route + uri: https://httpbin.org + predicates: + - Path=/fake/post/** + filters: + - RedirectTo=302, https://httpbin.org + + - id: status_route + uri: https://httpbin.org + predicates: + - Path=/delete/** + filters: + - SetStatus=401 + + - id: size_route + uri: https://httpbin.org + predicates: + - Path=/anything + filters: + - name: RequestSize + args: + maxSize: 5000000 + + - id: retry_test + uri: https://httpbin.org + predicates: + - Path=/status/502 + filters: + - name: Retry + args: + retries: 3 + statuses: BAD_GATEWAY + methods: GET,POST + backoff: + firstBackoff: 10ms + maxBackoff: 50ms + factor: 2 + basedOnPreviousValue: false + + - id: circuitbreaker_route + uri: https://httpbin.org + predicates: + - Path=/status/504 + filters: + - name: CircuitBreaker + args: + name: myCircuitBreaker + fallbackUri: forward:/anything + - RewritePath=/status/504, /anything \ No newline at end of file From b25323afb2891c5cdb19ac26161cb5b67558b2b6 Mon Sep 17 00:00:00 2001 From: Cavero Barca Date: Tue, 21 Apr 2020 15:33:39 +0200 Subject: [PATCH 16/91] Add testing to the WebFilter Factories Spring Boot project --- .../WebFilterFactoriesLiveTest.java | 139 ++++++++++++++++++ 1 file changed, 139 insertions(+) create mode 100644 spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/WebFilterFactoriesLiveTest.java diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/WebFilterFactoriesLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/WebFilterFactoriesLiveTest.java new file mode 100644 index 0000000000..3efd60fb27 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/WebFilterFactoriesLiveTest.java @@ -0,0 +1,139 @@ +package com.baeldung.springcloudgateway.webfilters; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import org.assertj.core.api.Condition; +import org.json.JSONException; +import org.json.JSONObject; +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.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.reactive.server.WebTestClient; +import org.springframework.test.web.reactive.server.WebTestClient.ResponseSpec; + +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("webfilters") +public class WebFilterFactoriesLiveTest { + + @LocalServerPort + String port; + + @Autowired + private WebTestClient client; + + @Autowired + private TestRestTemplate restTemplate; + + @BeforeEach + public void configureClient() { + client = WebTestClient.bindToServer() + .baseUrl("http://localhost:" + port) + .build(); + } + + @Test + public void whenCallGetThroughGateway_thenAllHTTPRequestHeadersParametersAreSet() throws JSONException { + String url = "http://localhost:" + port + "/get"; + ResponseEntity response = restTemplate.getForEntity(url, String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + JSONObject json = new JSONObject(response.getBody()); + JSONObject headers = json.getJSONObject("headers"); + assertThat(headers.getString("My-Header-Good")).isEqualTo("Good"); + assertThat(headers.getString("My-Header-Bad")).isEqualTo("Good"); + assertThat(headers.getString("My-Header-Set")).isEqualTo("Set"); + assertTrue(headers.isNull("My-Header-Remove")); + JSONObject vars = json.getJSONObject("args"); + assertThat(vars.getString("var")).isEqualTo("good"); + } + + @Test + public void whenCallHeaderPostThroughGateway_thenAllHTTPResponseHeadersAreSet() { + ResponseSpec response = client.post() + .uri("/header/post") + .exchange(); + + response.expectStatus() + .isOk() + .expectHeader() + .valueEquals("My-Header-Rewrite", "password=***") + .expectHeader() + .valueEquals("My-Header-Set", "Set") + .expectHeader() + .valueEquals("My-Header-Good", "Good") + .expectHeader() + .doesNotExist("My-Header-Remove"); + } + + @Test + public void whenCallPostThroughGateway_thenBodyIsRetrieved() throws JSONException { + String url = "http://localhost:" + port + "/post"; + + HttpEntity entity = new HttpEntity<>("content", new HttpHeaders()); + + ResponseEntity response = restTemplate.exchange(url, + HttpMethod.POST, entity, String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + JSONObject json = new JSONObject(response.getBody()); + JSONObject data = json.getJSONObject("json"); + assertThat(data.getString("message")).isEqualTo("CONTENT"); + } + + + @Test + public void whenCallPutThroughGateway_thenBodyIsRetrieved() throws JSONException { + String url = "http://localhost:" + port + "/put"; + + HttpEntity entity = new HttpEntity<>("CONTENT", new HttpHeaders()); + + ResponseEntity response = restTemplate.exchange(url, + HttpMethod.PUT, entity, String.class); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + JSONObject json = new JSONObject(response.getBody()); + assertThat(json.getString("message")).isEqualTo("New Body"); + } + + @Test + public void whenCallDeleteThroughGateway_thenIsUnauthorizedCodeIsSet() { + ResponseSpec response = client.delete() + .uri("/delete") + .exchange(); + + response.expectStatus() + .isUnauthorized(); + } + + @Test + public void whenCallFakePostThroughGateway_thenIsUnauthorizedCodeIsSet() { + ResponseSpec response = client.post() + .uri("/fake/post") + .exchange(); + + response.expectStatus() + .is3xxRedirection(); + } + + @Test + public void whenCallStatus504ThroughGateway_thenCircuitBreakerIsExecuted() throws JSONException { + String url = "http://localhost:" + port + "/status/504"; + ResponseEntity response = restTemplate.getForEntity(url, String.class); + + JSONObject json = new JSONObject(response.getBody()); + assertThat(json.getString("url")).contains("anything"); + } +} From 8b6c667ce058c09870c0784627fdf831a2dfe912 Mon Sep 17 00:00:00 2001 From: Kyle Doyle Date: Wed, 22 Apr 2020 21:10:52 -0400 Subject: [PATCH 17/91] Bael-3893 AWS AppSync with Spring Boot --- aws-app-sync/pom.xml | 6 -- .../awsappsync/AppSyncClientHelper.java | 32 ++++++++++ .../AwsAppSyncApplicationTests.java | 63 ++----------------- 3 files changed, 38 insertions(+), 63 deletions(-) create mode 100644 aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java diff --git a/aws-app-sync/pom.xml b/aws-app-sync/pom.xml index d30cfc96a4..ef2085ff35 100644 --- a/aws-app-sync/pom.xml +++ b/aws-app-sync/pom.xml @@ -22,12 +22,6 @@ - - com.amazonaws - aws-java-sdk-appsync - 1.11.762 - - org.springframework.boot spring-boot-starter-web diff --git a/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java new file mode 100644 index 0000000000..fcbc0aa275 --- /dev/null +++ b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java @@ -0,0 +1,32 @@ +package com.baeldung.awsappsync; + +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; + +import java.nio.charset.StandardCharsets; +import java.util.Map; + +public class AppSyncClientHelper { + + static String apiUrl = "https://m4i3b6icrrb7livfbypfspiifi.appsync-api.us-east-2.amazonaws.com"; + static String apiKey = "da2-es2s6oj4mzhbxk5yu26ss2ruj4"; + static String API_KEY_HEADER = "x-api-key"; + + public static WebClient.ResponseSpec getResponseBodySpec(Map requestBody) { + return WebClient + .builder() + .baseUrl(apiUrl) + .defaultHeader(API_KEY_HEADER, apiKey) + .defaultHeader("Content-Type", "application/json") + .build() + .method(HttpMethod.POST) + .uri("/graphql") + .body(BodyInserters.fromValue(requestBody)) + .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) + .acceptCharset(StandardCharsets.UTF_8) + .retrieve(); + } + +} diff --git a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java index 005d533cbf..cd14bcd5b2 100644 --- a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java +++ b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java @@ -1,14 +1,9 @@ package com.baeldung.awsappsync; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.http.HttpMethod; -import org.springframework.http.MediaType; -import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.WebClient; -import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; @@ -17,48 +12,16 @@ import static org.junit.jupiter.api.Assertions.*; @SpringBootTest class AwsAppSyncApplicationTests { - static String apiUrl = "https://m4i3b6icrrb7livfbypfspiifi.appsync-api.us-east-2.amazonaws.com"; - static String apiKey = "da2-es2s6oj4mzhbxk5yu26ss2ruj4"; - static String API_KEY_HEADER = "x-api-key"; - - static WebClient.RequestBodySpec requestBodySpec; - - @BeforeAll - static void setUp() { - requestBodySpec = WebClient - .builder() - .baseUrl(apiUrl) - .defaultHeader(API_KEY_HEADER, apiKey) - .build() - .method(HttpMethod.POST) - .uri("/graphql"); - } - @Test void givenGraphQuery_whenListEvents_thenReturnAllEvents() { Map requestBody = new HashMap<>(); - requestBody.put("query", "query ListEvents {\n" + - " listEvents {\n" + - " items {\n" + - " id\n" + - " name\n" + - " where\n" + - " when\n" + - " description\n" + - " }\n" + - " }\n" + - "}"); + requestBody.put("query", "query ListEvents { listEvents { items { id name where when description } } }"); requestBody.put("variables", ""); requestBody.put("operationName", "ListEvents"); - WebClient.ResponseSpec response = requestBodySpec - .body(BodyInserters.fromValue(requestBody)) - .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) - .acceptCharset(StandardCharsets.UTF_8) - .retrieve(); - - String bodyString = response.bodyToMono(String.class).block(); + String bodyString = AppSyncClientHelper.getResponseBodySpec(requestBody) + .bodyToMono(String.class).block(); assertNotNull(bodyString); assertTrue(bodyString.contains("My First Event")); @@ -69,18 +32,8 @@ class AwsAppSyncApplicationTests { @Test void givenGraphAdd_whenMutation_thenReturnIdNameDesc() { - String queryString = "mutation add {\n" + - " createEvent(\n" + - " name:\"My added GraphQL event\"\n" + - " where:\"Day 2\"\n" + - " when:\"Saturday night\"\n" + - " description:\"Studying GraphQL\"\n" + - " ){\n" + - " id\n" + - " name\n" + - " description\n" + - " }\n" + - "}"; + String queryString = "mutation add { createEvent( name:\"My added GraphQL event\" where:\"Day 2\"" + + " when:\"Saturday night\" description:\"Studying GraphQL\" ){ id name description } }"; Map requestBody = new HashMap<>(); @@ -88,11 +41,7 @@ class AwsAppSyncApplicationTests { requestBody.put("variables", ""); requestBody.put("operationName", "add"); - WebClient.ResponseSpec response = requestBodySpec - .body(BodyInserters.fromValue(requestBody)) - .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) - .acceptCharset(StandardCharsets.UTF_8) - .retrieve(); + WebClient.ResponseSpec response = AppSyncClientHelper.getResponseBodySpec(requestBody); String bodyString = response.bodyToMono(String.class).block(); From 5bb2977eb063a73c81dd7fc99cc2c6ecefdc1c32 Mon Sep 17 00:00:00 2001 From: sergio41 Date: Fri, 24 Apr 2020 13:03:41 +0200 Subject: [PATCH 18/91] [BAEL-3944] Move to a separate test class and fix other issues --- .../regex/PhoneNumbersRegexUnitTest.java | 55 +++++++++++++++++++ .../com/baeldung/regex/RegexUnitTest.java | 49 ----------------- 2 files changed, 55 insertions(+), 49 deletions(-) create mode 100644 core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/PhoneNumbersRegexUnitTest.java diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/PhoneNumbersRegexUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/PhoneNumbersRegexUnitTest.java new file mode 100644 index 0000000000..edfa7a2c5e --- /dev/null +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/PhoneNumbersRegexUnitTest.java @@ -0,0 +1,55 @@ +package com.baeldung.regex; + +import static org.junit.Assert.*; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Test; + +public class PhoneNumbersRegexUnitTest { + + @Test + public void whenMatchesTenDigitsNumber_thenCorrect() { + Pattern pattern = Pattern.compile("^\\d{10}$"); + Matcher matcher = pattern.matcher("1234567890"); + assertTrue(matcher.matches()); + } + + @Test + public void whenMatchesTenDigitsNumberWhitespacesHyphen_thenCorrect() { + Pattern pattern = Pattern.compile("^(\\d{3}[- ]?){2}\\d{4}$"); + Matcher matcher = pattern.matcher("123 456 7890"); + assertTrue(matcher.matches()); + } + + @Test + public void whenMatchesTenDigitsNumberParenthesis_thenCorrect() { + Pattern pattern = Pattern.compile("^\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$"); + Matcher matcher = pattern.matcher("(123)-456-7890"); + assertTrue(matcher.matches()); + } + + @Test + public void whenMatchesTenDigitsNumberPrefix_thenCorrect() { + Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$"); + Matcher matcher = pattern.matcher("+111 (123)-456-7890"); + assertTrue(matcher.matches()); + } + + @Test + public void whenMatchesPhoneNumber_thenCorrect() { + String patterns = "^(\\+\\d{1,3}( )?)?\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$" + + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$" + + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$"; + + String[] validPhoneNumbers = {"1234567890","123 456 7890", "(123)-456-7890", "+111 (123)-456-7890", + "123 456 789", "+111 123 456 789", "123 45 67 89", "+111 123 45 67 89"}; + + Pattern pattern = Pattern.compile(patterns); + for(String phoneNumber : validPhoneNumbers) { + Matcher matcher = pattern.matcher(phoneNumber); + assertTrue(matcher.matches()); + } + } +} diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/RegexUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/RegexUnitTest.java index 909894ec55..77052b79ac 100644 --- a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/RegexUnitTest.java +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/RegexUnitTest.java @@ -26,7 +26,6 @@ public class RegexUnitTest { while (matcher.find()) matches++; assertEquals(matches, 2); - } @Test @@ -452,7 +451,6 @@ public class RegexUnitTest { Matcher matcher = pattern.matcher("dogs are friendly"); assertTrue(matcher.lookingAt()); assertFalse(matcher.matches()); - } @Test @@ -460,7 +458,6 @@ public class RegexUnitTest { Pattern pattern = Pattern.compile("dog"); Matcher matcher = pattern.matcher("dog"); assertTrue(matcher.matches()); - } @Test @@ -469,7 +466,6 @@ public class RegexUnitTest { Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly"); String newStr = matcher.replaceFirst("cat"); assertEquals("cats are domestic animals, dogs are friendly", newStr); - } @Test @@ -478,51 +474,6 @@ public class RegexUnitTest { Matcher matcher = pattern.matcher("dogs are domestic animals, dogs are friendly"); String newStr = matcher.replaceAll("cat"); assertEquals("cats are domestic animals, cats are friendly", newStr); - - } - - @Test - public void whenMatchesTenDigitsNumber_thenCorrect() { - Pattern pattern = Pattern.compile("^\\d{10}$"); - Matcher matcher = pattern.matcher("1234567890"); - assertTrue(matcher.matches()); - } - - @Test - public void whenMatchesTenDigitsNumberWhitespacesHyphen_thenCorrect() { - Pattern pattern = Pattern.compile("^(\\d{3}[- ]?){2}\\d{4}$"); - Matcher matcher = pattern.matcher("123 456 7890"); - assertTrue(matcher.matches()); - } - - @Test - public void whenMatchesTenDigitsNumberParenthesis_thenCorrect() { - Pattern pattern = Pattern.compile("^\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$"); - Matcher matcher = pattern.matcher("(123)-456-7890"); - assertTrue(matcher.matches()); - } - - @Test - public void whenMatchesTenDigitsNumberPrefix_thenCorrect() { - Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$"); - Matcher matcher = pattern.matcher("+111 (123)-456-7890"); - assertTrue(matcher.matches()); - } - - @Test - public void whenMatchesPhoneNumber_thenCorrect() { - String patterns = "^(\\+\\d{1,3}( )?)?\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$" + - "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$" + - "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$"; - - String[] validPhoneNumbers = {"1234567890","123 456 7890", "(123)-456-7890", "+111 (123)-456-7890", - "123 456 789", "+111 123 456 789", "123 45 67 89", "+111 123 45 67 89"}; - - Pattern pattern = Pattern.compile(patterns); - for(String phoneNumber : validPhoneNumbers) { - Matcher matcher = pattern.matcher(phoneNumber); - assertTrue(matcher.matches()); - } } public synchronized static int runTest(String regex, String text) { From 953b8d4640900045433599e8148d92990b8835a0 Mon Sep 17 00:00:00 2001 From: sergio41 Date: Fri, 24 Apr 2020 13:07:05 +0200 Subject: [PATCH 19/91] [BAEL-3944] Real like phone numbers --- .../baeldung/regex/PhoneNumbersRegexUnitTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/PhoneNumbersRegexUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/PhoneNumbersRegexUnitTest.java index edfa7a2c5e..620b7a9bae 100644 --- a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/PhoneNumbersRegexUnitTest.java +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/PhoneNumbersRegexUnitTest.java @@ -12,28 +12,28 @@ public class PhoneNumbersRegexUnitTest { @Test public void whenMatchesTenDigitsNumber_thenCorrect() { Pattern pattern = Pattern.compile("^\\d{10}$"); - Matcher matcher = pattern.matcher("1234567890"); + Matcher matcher = pattern.matcher("2055550125"); assertTrue(matcher.matches()); } @Test public void whenMatchesTenDigitsNumberWhitespacesHyphen_thenCorrect() { Pattern pattern = Pattern.compile("^(\\d{3}[- ]?){2}\\d{4}$"); - Matcher matcher = pattern.matcher("123 456 7890"); + Matcher matcher = pattern.matcher("202 555 0125"); assertTrue(matcher.matches()); } @Test public void whenMatchesTenDigitsNumberParenthesis_thenCorrect() { Pattern pattern = Pattern.compile("^\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$"); - Matcher matcher = pattern.matcher("(123)-456-7890"); + Matcher matcher = pattern.matcher("(202)-555-0125"); assertTrue(matcher.matches()); } @Test public void whenMatchesTenDigitsNumberPrefix_thenCorrect() { Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$"); - Matcher matcher = pattern.matcher("+111 (123)-456-7890"); + Matcher matcher = pattern.matcher("+111 (202)-555-0125"); assertTrue(matcher.matches()); } @@ -43,8 +43,8 @@ public class PhoneNumbersRegexUnitTest { "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$" + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$"; - String[] validPhoneNumbers = {"1234567890","123 456 7890", "(123)-456-7890", "+111 (123)-456-7890", - "123 456 789", "+111 123 456 789", "123 45 67 89", "+111 123 45 67 89"}; + String[] validPhoneNumbers = {"2055550125","202 555 0125", "(202)-555-0125", "+111 (202)-555-0125", + "636 856 789", "+111 636 856 789", "636 85 67 89", "+111 636 85 67 89"}; Pattern pattern = Pattern.compile(patterns); for(String phoneNumber : validPhoneNumbers) { From 44485bcc48a090a6fd2850047065ce8a7677276c Mon Sep 17 00:00:00 2001 From: Cavero Barca Date: Sat, 25 Apr 2020 01:49:20 +0200 Subject: [PATCH 20/91] Use a two-space indent when continuing a line --- .../WebFilterGatewayApplication.java | 4 +- .../config/ModifyBodyRouteConfig.java | 16 ++--- .../WebFilterFactoriesLiveTest.java | 69 +++++++++---------- 3 files changed, 43 insertions(+), 46 deletions(-) diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java index 3b45e9013f..852e5cadba 100644 --- a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/WebFilterGatewayApplication.java @@ -8,8 +8,8 @@ public class WebFilterGatewayApplication { public static void main(String[] args) { new SpringApplicationBuilder(WebFilterGatewayApplication.class) - .profiles("webfilters") - .run(args); + .profiles("webfilters") + .run(args); } } \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/ModifyBodyRouteConfig.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/ModifyBodyRouteConfig.java index ccc789f287..7b6188b66a 100644 --- a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/ModifyBodyRouteConfig.java +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/ModifyBodyRouteConfig.java @@ -14,19 +14,19 @@ public class ModifyBodyRouteConfig { @Bean public RouteLocator routes(RouteLocatorBuilder builder) { return builder.routes() - .route("modify_request_body", r -> r.path("/post") - .filters(f -> f.modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE, - (exchange, s) -> Mono.just(new Hello(s.toUpperCase())))).uri("https://httpbin.org")) - .build(); + .route("modify_request_body", r -> r.path("/post") + .filters(f -> f.modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE, + (exchange, s) -> Mono.just(new Hello(s.toUpperCase())))).uri("https://httpbin.org")) + .build(); } @Bean public RouteLocator responseRoutes(RouteLocatorBuilder builder) { return builder.routes() - .route("modify_response_body", r -> r.path("/put/**") - .filters(f -> f.modifyResponseBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE, - (exchange, s) -> Mono.just(new Hello("New Body")))).uri("https://httpbin.org")) - .build(); + .route("modify_response_body", r -> r.path("/put/**") + .filters(f -> f.modifyResponseBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE, + (exchange, s) -> Mono.just(new Hello("New Body")))).uri("https://httpbin.org")) + .build(); } static class Hello { diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/WebFilterFactoriesLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/WebFilterFactoriesLiveTest.java index 3efd60fb27..67e00a42fc 100644 --- a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/WebFilterFactoriesLiveTest.java +++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/WebFilterFactoriesLiveTest.java @@ -33,23 +33,23 @@ public class WebFilterFactoriesLiveTest { @Autowired private WebTestClient client; - + @Autowired private TestRestTemplate restTemplate; @BeforeEach public void configureClient() { client = WebTestClient.bindToServer() - .baseUrl("http://localhost:" + port) - .build(); + .baseUrl("http://localhost:" + port) + .build(); } @Test public void whenCallGetThroughGateway_thenAllHTTPRequestHeadersParametersAreSet() throws JSONException { - String url = "http://localhost:" + port + "/get"; + String url = "http://localhost:" + port + "/get"; ResponseEntity response = restTemplate.getForEntity(url, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - + JSONObject json = new JSONObject(response.getBody()); JSONObject headers = json.getJSONObject("headers"); assertThat(headers.getString("My-Header-Good")).isEqualTo("Good"); @@ -63,76 +63,73 @@ public class WebFilterFactoriesLiveTest { @Test public void whenCallHeaderPostThroughGateway_thenAllHTTPResponseHeadersAreSet() { ResponseSpec response = client.post() - .uri("/header/post") - .exchange(); + .uri("/header/post") + .exchange(); response.expectStatus() - .isOk() - .expectHeader() - .valueEquals("My-Header-Rewrite", "password=***") - .expectHeader() - .valueEquals("My-Header-Set", "Set") - .expectHeader() - .valueEquals("My-Header-Good", "Good") - .expectHeader() - .doesNotExist("My-Header-Remove"); + .isOk() + .expectHeader() + .valueEquals("My-Header-Rewrite", "password=***") + .expectHeader() + .valueEquals("My-Header-Set", "Set") + .expectHeader() + .valueEquals("My-Header-Good", "Good") + .expectHeader() + .doesNotExist("My-Header-Remove"); } @Test public void whenCallPostThroughGateway_thenBodyIsRetrieved() throws JSONException { - String url = "http://localhost:" + port + "/post"; + String url = "http://localhost:" + port + "/post"; HttpEntity entity = new HttpEntity<>("content", new HttpHeaders()); - - ResponseEntity response = restTemplate.exchange(url, - HttpMethod.POST, entity, String.class); + + ResponseEntity response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - + JSONObject json = new JSONObject(response.getBody()); JSONObject data = json.getJSONObject("json"); assertThat(data.getString("message")).isEqualTo("CONTENT"); } - @Test public void whenCallPutThroughGateway_thenBodyIsRetrieved() throws JSONException { - String url = "http://localhost:" + port + "/put"; + String url = "http://localhost:" + port + "/put"; HttpEntity entity = new HttpEntity<>("CONTENT", new HttpHeaders()); - - ResponseEntity response = restTemplate.exchange(url, - HttpMethod.PUT, entity, String.class); + + ResponseEntity response = restTemplate.exchange(url, HttpMethod.PUT, entity, String.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - + JSONObject json = new JSONObject(response.getBody()); assertThat(json.getString("message")).isEqualTo("New Body"); } - + @Test public void whenCallDeleteThroughGateway_thenIsUnauthorizedCodeIsSet() { ResponseSpec response = client.delete() - .uri("/delete") - .exchange(); + .uri("/delete") + .exchange(); response.expectStatus() - .isUnauthorized(); + .isUnauthorized(); } @Test public void whenCallFakePostThroughGateway_thenIsUnauthorizedCodeIsSet() { ResponseSpec response = client.post() - .uri("/fake/post") - .exchange(); + .uri("/fake/post") + .exchange(); response.expectStatus() - .is3xxRedirection(); + .is3xxRedirection(); } @Test public void whenCallStatus504ThroughGateway_thenCircuitBreakerIsExecuted() throws JSONException { - String url = "http://localhost:" + port + "/status/504"; + String url = "http://localhost:" + port + "/status/504"; ResponseEntity response = restTemplate.getForEntity(url, String.class); - + JSONObject json = new JSONObject(response.getBody()); assertThat(json.getString("url")).contains("anything"); } From a73fb8483a036103945b5934f1b40c70e7020f99 Mon Sep 17 00:00:00 2001 From: sergio41 Date: Sat, 25 Apr 2020 14:19:28 +0200 Subject: [PATCH 21/91] [BAEL-3944] Package move --- .../regex/{ => phonenumbers}/PhoneNumbersRegexUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/{ => phonenumbers}/PhoneNumbersRegexUnitTest.java (98%) diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/PhoneNumbersRegexUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java similarity index 98% rename from core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/PhoneNumbersRegexUnitTest.java rename to core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java index 620b7a9bae..f7a9d70850 100644 --- a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/PhoneNumbersRegexUnitTest.java +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java @@ -1,4 +1,4 @@ -package com.baeldung.regex; +package com.baeldung.regex.phonenumbers; import static org.junit.Assert.*; From ec8d2244a3118ca3854feac34ef60ae3391acb59 Mon Sep 17 00:00:00 2001 From: Cavero Barca Date: Mon, 27 Apr 2020 01:22:33 +0200 Subject: [PATCH 22/91] Add RedisRateLimiter to webfilter package --- spring-cloud/spring-cloud-gateway/pom.xml | 25 ++++++-- .../RequestRateLimiterResolverConfig.java | 16 +++++ .../main/resources/application-webfilters.yml | 21 ++++-- .../RedisWebFilterFactoriesLiveTest.java | 64 +++++++++++++++++++ .../src/test/resources/logback-test.xml | 8 +++ 5 files changed, 123 insertions(+), 11 deletions(-) create mode 100644 spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/RequestRateLimiterResolverConfig.java create mode 100644 spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/RedisWebFilterFactoriesLiveTest.java diff --git a/spring-cloud/spring-cloud-gateway/pom.xml b/spring-cloud/spring-cloud-gateway/pom.xml index ada32ae85f..c692eed7ec 100644 --- a/spring-cloud/spring-cloud-gateway/pom.xml +++ b/spring-cloud/spring-cloud-gateway/pom.xml @@ -1,7 +1,7 @@ + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 spring-cloud-gateway spring-cloud-gateway @@ -54,7 +54,21 @@ org.springframework.cloud spring-cloud-starter-circuitbreaker-reactor-resilience4j - + + + + org.springframework.boot + spring-boot-starter-data-redis-reactive + + + + + it.ozimov + embedded-redis + ${redis.version} + test + + org.hibernate hibernate-validator-cdi @@ -75,8 +89,8 @@ test - org.springframework.boot - spring-boot-devtools + org.springframework.boot + spring-boot-devtools @@ -93,6 +107,7 @@ Hoxton.SR3 2.2.6.RELEASE 6.0.2.Final + 0.7.2 diff --git a/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/RequestRateLimiterResolverConfig.java b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/RequestRateLimiterResolverConfig.java new file mode 100644 index 0000000000..f80a742fa6 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/main/java/com/baeldung/springcloudgateway/webfilters/config/RequestRateLimiterResolverConfig.java @@ -0,0 +1,16 @@ +package com.baeldung.springcloudgateway.webfilters.config; + +import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import reactor.core.publisher.Mono; + +@Configuration +public class RequestRateLimiterResolverConfig { + + @Bean + KeyResolver userKeyResolver() { + return exchange -> Mono.just("1"); + } +} diff --git a/spring-cloud/spring-cloud-gateway/src/main/resources/application-webfilters.yml b/spring-cloud/spring-cloud-gateway/src/main/resources/application-webfilters.yml index 9b3ec64f96..3348cbbba0 100644 --- a/spring-cloud/spring-cloud-gateway/src/main/resources/application-webfilters.yml +++ b/spring-cloud/spring-cloud-gateway/src/main/resources/application-webfilters.yml @@ -1,4 +1,12 @@ +logging: + level: + org.springframework.cloud.gateway: INFO + reactor.netty.http.client: INFO + spring: + redis: + host: localhost + port: 6379 cloud: gateway: routes: @@ -81,13 +89,14 @@ spring: factor: 2 basedOnPreviousValue: false - - id: circuitbreaker_route + - id: request_rate_limiter uri: https://httpbin.org predicates: - - Path=/status/504 + - Path=/redis/get/** filters: - - name: CircuitBreaker + - StripPrefix=1 + - name: RequestRateLimiter args: - name: myCircuitBreaker - fallbackUri: forward:/anything - - RewritePath=/status/504, /anything \ No newline at end of file + redis-rate-limiter.replenishRate: 10 + redis-rate-limiter.burstCapacity: 5 + key-resolver: "#{@userKeyResolver}" \ No newline at end of file diff --git a/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/RedisWebFilterFactoriesLiveTest.java b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/RedisWebFilterFactoriesLiveTest.java new file mode 100644 index 0000000000..a28eb68775 --- /dev/null +++ b/spring-cloud/spring-cloud-gateway/src/test/java/com/baeldung/springcloudgateway/webfilters/RedisWebFilterFactoriesLiveTest.java @@ -0,0 +1,64 @@ +package com.baeldung.springcloudgateway.webfilters; + +import org.junit.After; +import org.junit.Before; +import org.junit.jupiter.api.RepeatedTest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ActiveProfiles; + +import redis.embedded.RedisServer; + +@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) +@ActiveProfiles("webfilters") +@TestConfiguration +public class RedisWebFilterFactoriesLiveTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(RedisWebFilterFactoriesLiveTest.class); + + private RedisServer redisServer; + + public RedisWebFilterFactoriesLiveTest() { + } + + @Before + public void postConstruct() { + this.redisServer = new RedisServer(6379); + redisServer.start(); + } + + @LocalServerPort + String port; + + @Autowired + private TestRestTemplate restTemplate; + + @Autowired + TestRestTemplate template; + + @RepeatedTest(25) + public void whenCallRedisGetThroughGateway_thenOKStatusOrIsReceived() { + String url = "http://localhost:" + port + "/redis/get"; + + ResponseEntity r = restTemplate.getForEntity(url, String.class); + // assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + + LOGGER.info("Received: status->{}, reason->{}, remaining->{}", + r.getStatusCodeValue(), r.getStatusCode().getReasonPhrase(), + r.getHeaders().get("X-RateLimit-Remaining")); + } + + @After + public void preDestroy() { + redisServer.stop(); + } + +} diff --git a/spring-cloud/spring-cloud-gateway/src/test/resources/logback-test.xml b/spring-cloud/spring-cloud-gateway/src/test/resources/logback-test.xml index 6fcdb6317f..6980d119b1 100644 --- a/spring-cloud/spring-cloud-gateway/src/test/resources/logback-test.xml +++ b/spring-cloud/spring-cloud-gateway/src/test/resources/logback-test.xml @@ -3,7 +3,15 @@ + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + \ No newline at end of file From fe9405607a590555ed525cefa3ac3c0a6ccd175a Mon Sep 17 00:00:00 2001 From: Chirag Dewan Date: Wed, 29 Apr 2020 08:29:17 +0530 Subject: [PATCH 23/91] BAEL1731 Log4j2 Plugins --- .../plugins/DockerPatternConverter.java | 30 ++++ .../logging/log4j2/plugins/KafkaAppender.java | 133 ++++++++++++++++++ .../logging/log4j2/plugins/KafkaBroker.java | 38 +++++ .../logging/log4j2/plugins/KafkaLookup.java | 24 ++++ .../log4j2/src/test/resources/log4j2.xml | 9 ++ 5 files changed, 234 insertions(+) create mode 100644 logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/DockerPatternConverter.java create mode 100644 logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaAppender.java create mode 100644 logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaBroker.java create mode 100644 logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaLookup.java diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/DockerPatternConverter.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/DockerPatternConverter.java new file mode 100644 index 0000000000..c2e40cd565 --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/DockerPatternConverter.java @@ -0,0 +1,30 @@ +package com.baeldung.logging.log4j2.plugins; + +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.pattern.ConverterKeys; +import org.apache.logging.log4j.core.pattern.LogEventPatternConverter; +import org.apache.logging.log4j.core.pattern.PatternConverter; + +@Plugin(name = "DockerPatternConverter", category = PatternConverter.CATEGORY) +@ConverterKeys({"docker", "container"}) +public class DockerPatternConverter extends LogEventPatternConverter { + + private DockerPatternConverter(String[] options) { + super("Docker", "docker"); + } + + public static DockerPatternConverter newInstance(String[] options) { + return new DockerPatternConverter(options); + } + + @Override + public void format(LogEvent event, StringBuilder toAppendTo) { + toAppendTo.append(dockerContainer()); + } + + private String dockerContainer() { + //get docker container ID inside which application is running here + return "container-1"; + } +} diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaAppender.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaAppender.java new file mode 100644 index 0000000000..3e91aa5e94 --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaAppender.java @@ -0,0 +1,133 @@ +package com.baeldung.logging.log4j2.plugins; + +import org.apache.logging.log4j.core.Core; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.Layout; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginBuilderAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginBuilderFactory; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required; + +import java.io.Serializable; + +@Plugin(name = "Kafka2", category = Core.CATEGORY_NAME) +public class KafkaAppender extends AbstractAppender { + + @PluginBuilderFactory + public static Builder newBuilder() { + return new Builder(); + } + + public static class Builder implements org.apache.logging.log4j.core.util.Builder { + + @PluginBuilderAttribute("name") + @Required + private String name; + + @PluginBuilderAttribute("ip") + private String ipAddress; + + @PluginBuilderAttribute("port") + private int port; + + @PluginBuilderAttribute("topic") + private String topic; + + @PluginBuilderAttribute("partition") + private String partition; + + @PluginElement("Layout") + private Layout layout; + + @PluginElement("Filter") + private Filter filter; + + public Layout getLayout() { + return layout; + } + + public Builder setLayout(Layout layout) { + this.layout = layout; + return this; + } + + public Filter getFilter() { + return filter; + } + + public String getName() { + return name; + } + + public Builder setName(String name) { + this.name = name; + return this; + } + + public Builder setFilter(Filter filter) { + this.filter = filter; + return this; + } + + public String getIpAddress() { + return ipAddress; + } + + public Builder setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + return this; + } + + public int getPort() { + return port; + } + + public Builder setPort(int port) { + this.port = port; + return this; + } + + public String getTopic() { + return topic; + } + + public Builder setTopic(String topic) { + this.topic = topic; + return this; + } + + public String getPartition() { + return partition; + } + + public Builder setPartition(String partition) { + this.partition = partition; + return this; + } + + @Override + public KafkaAppender build() { + return new KafkaAppender(getName(), getFilter(), getLayout(), true, new KafkaBroker(ipAddress, port, topic, partition)); + } + } + + private KafkaBroker broker; + + private KafkaAppender(String name, Filter filter, Layout layout, boolean ignoreExceptions, KafkaBroker broker) { + super(name, filter, layout, ignoreExceptions); + this.broker = broker; + } + + @Override + public void append(LogEvent event) { + + connectAndSendToKafka(broker, event); + } + + private void connectAndSendToKafka(KafkaBroker broker, LogEvent event) { + //send to Kafka + } +} diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaBroker.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaBroker.java new file mode 100644 index 0000000000..0479e71c41 --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaBroker.java @@ -0,0 +1,38 @@ +package com.baeldung.logging.log4j2.plugins; + +import java.io.Serializable; + +public class KafkaBroker implements Serializable { + + private final String ipAddress; + private final int port; + + public KafkaBroker(String ipAddress, int port, String topic, String partition) { + this.ipAddress = ipAddress; + this.port = port; + this.topic = topic; + this.partition = partition; + } + + public String getTopic() { + return topic; + } + + public String getPartition() { + return partition; + } + + private final String topic; + private final String partition; + + + public String getIpAddress() { + return ipAddress; + } + + public int getPort() { + return port; + } + + +} diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaLookup.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaLookup.java new file mode 100644 index 0000000000..c2679861c4 --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/KafkaLookup.java @@ -0,0 +1,24 @@ +package com.baeldung.logging.log4j2.plugins; + +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.lookup.StrLookup; + +@Plugin(name = "kafka", category = StrLookup.CATEGORY) +public class KafkaLookup implements StrLookup { + + @Override + public String lookup(String key) { + return getFromKafka(key); + } + + @Override + public String lookup(LogEvent event, String key) { + return getFromKafka(key); + } + + private String getFromKafka(String topicName) { + //kafka search logic should go here + return "topic1-p1"; + } +} diff --git a/logging-modules/log4j2/src/test/resources/log4j2.xml b/logging-modules/log4j2/src/test/resources/log4j2.xml index ee26bcecf2..050e0aa705 100644 --- a/logging-modules/log4j2/src/test/resources/log4j2.xml +++ b/logging-modules/log4j2/src/test/resources/log4j2.xml @@ -50,6 +50,12 @@ + + + + + + + + + From 23bc2db643ff723e4c2d899c7dd0d1c008dc3454 Mon Sep 17 00:00:00 2001 From: sergio41 Date: Thu, 30 Apr 2020 18:44:05 +0200 Subject: [PATCH 24/91] [BAEL-3944] Minor changes on examples and identations --- .../PhoneNumbersRegexUnitTest.java | 35 ++++++++++--------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java index f7a9d70850..ec0380c450 100644 --- a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java @@ -15,37 +15,38 @@ public class PhoneNumbersRegexUnitTest { Matcher matcher = pattern.matcher("2055550125"); assertTrue(matcher.matches()); } - + @Test - public void whenMatchesTenDigitsNumberWhitespacesHyphen_thenCorrect() { - Pattern pattern = Pattern.compile("^(\\d{3}[- ]?){2}\\d{4}$"); + public void whenMatchesTenDigitsNumberWhitespacesDotHyphen_thenCorrect() { + Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$"); Matcher matcher = pattern.matcher("202 555 0125"); assertTrue(matcher.matches()); } - + @Test public void whenMatchesTenDigitsNumberParenthesis_thenCorrect() { - Pattern pattern = Pattern.compile("^\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$"); - Matcher matcher = pattern.matcher("(202)-555-0125"); + Pattern pattern = Pattern.compile("^((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); + Matcher matcher = pattern.matcher("(202) 555-0125"); assertTrue(matcher.matches()); } - + @Test public void whenMatchesTenDigitsNumberPrefix_thenCorrect() { - Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$"); - Matcher matcher = pattern.matcher("+111 (202)-555-0125"); + Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); + Matcher matcher = pattern.matcher("+111 (202) 555-0125"); assertTrue(matcher.matches()); } - + @Test public void whenMatchesPhoneNumber_thenCorrect() { - String patterns = "^(\\+\\d{1,3}( )?)?\\(?\\d{3}\\)?[- ]?\\d{3}[- ]?\\d{4}$" + - "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$" + - "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$"; - - String[] validPhoneNumbers = {"2055550125","202 555 0125", "(202)-555-0125", "+111 (202)-555-0125", - "636 856 789", "+111 636 856 789", "636 85 67 89", "+111 636 85 67 89"}; - + String patterns + = "^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$" + + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$" + + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$"; + + String[] validPhoneNumbers + = {"2055550125","202 555 0125", "(202) 555-0125", "+111 (202) 555-0125", "636 856 789", "+111 636 856 789", "636 85 67 89", "+111 636 85 67 89"}; + Pattern pattern = Pattern.compile(patterns); for(String phoneNumber : validPhoneNumbers) { Matcher matcher = pattern.matcher(phoneNumber); From 5a73101deb657414252d3ddfa91cab365504c90d Mon Sep 17 00:00:00 2001 From: sergio41 Date: Thu, 30 Apr 2020 19:09:11 +0200 Subject: [PATCH 25/91] [BAEL-3944] Identation --- .../baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java index ec0380c450..afabf47baa 100644 --- a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java @@ -45,7 +45,7 @@ public class PhoneNumbersRegexUnitTest { + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$"; String[] validPhoneNumbers - = {"2055550125","202 555 0125", "(202) 555-0125", "+111 (202) 555-0125", "636 856 789", "+111 636 856 789", "636 85 67 89", "+111 636 85 67 89"}; + = {"2055550125","202 555 0125", "(202) 555-0125", "+111 (202) 555-0125", "636 856 789", "+111 636 856 789", "636 85 67 89", "+111 636 85 67 89"}; Pattern pattern = Pattern.compile(patterns); for(String phoneNumber : validPhoneNumbers) { From c10208b4d926ad4ee6795082cecba8c3228415bc Mon Sep 17 00:00:00 2001 From: Kyle Doyle Date: Fri, 1 May 2020 19:48:38 -0400 Subject: [PATCH 26/91] Bael 3893 - Code review updates --- .../awsappsync/AppSyncClientHelper.java | 2 +- .../awsappsync/AwsAppSyncApplication.java | 6 +- .../AwsAppSyncApplicationTests.java | 77 ++++++++++++------- pom.xml | 2 +- 4 files changed, 53 insertions(+), 34 deletions(-) diff --git a/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java index fcbc0aa275..b310e60748 100644 --- a/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java +++ b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AppSyncClientHelper.java @@ -11,7 +11,7 @@ import java.util.Map; public class AppSyncClientHelper { static String apiUrl = "https://m4i3b6icrrb7livfbypfspiifi.appsync-api.us-east-2.amazonaws.com"; - static String apiKey = "da2-es2s6oj4mzhbxk5yu26ss2ruj4"; + static String apiKey = "da2-bm4rpatkkrc5jfyhvvq7itjeke"; static String API_KEY_HEADER = "x-api-key"; public static WebClient.ResponseSpec getResponseBodySpec(Map requestBody) { diff --git a/aws-app-sync/src/main/java/com/baeldung/awsappsync/AwsAppSyncApplication.java b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AwsAppSyncApplication.java index ae012c91a5..19fffd2994 100644 --- a/aws-app-sync/src/main/java/com/baeldung/awsappsync/AwsAppSyncApplication.java +++ b/aws-app-sync/src/main/java/com/baeldung/awsappsync/AwsAppSyncApplication.java @@ -6,8 +6,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AwsAppSyncApplication { - public static void main(String[] args) { - SpringApplication.run(AwsAppSyncApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(AwsAppSyncApplication.class, args); + } } diff --git a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java index cd14bcd5b2..6e94651789 100644 --- a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java +++ b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java @@ -12,42 +12,61 @@ import static org.junit.jupiter.api.Assertions.*; @SpringBootTest class AwsAppSyncApplicationTests { - @Test - void givenGraphQuery_whenListEvents_thenReturnAllEvents() { + @Test + void givenGraphQuery_whenListEvents_thenReturnAllEvents() { - Map requestBody = new HashMap<>(); - requestBody.put("query", "query ListEvents { listEvents { items { id name where when description } } }"); - requestBody.put("variables", ""); - requestBody.put("operationName", "ListEvents"); + Map requestBody = new HashMap<>(); + requestBody.put("query", "query ListEvents {" + + " listEvents {" + + " items {" + + " id" + + " name" + + " where" + + " when" + + " description" + + " }" + + " }" + + "}"); + requestBody.put("variables", ""); + requestBody.put("operationName", "ListEvents"); - String bodyString = AppSyncClientHelper.getResponseBodySpec(requestBody) - .bodyToMono(String.class).block(); + String bodyString = AppSyncClientHelper.getResponseBodySpec(requestBody) + .bodyToMono(String.class).block(); - assertNotNull(bodyString); - assertTrue(bodyString.contains("My First Event")); - assertTrue(bodyString.contains("where")); - assertTrue(bodyString.contains("when")); - } + assertNotNull(bodyString); + assertTrue(bodyString.contains("My First Event")); + assertTrue(bodyString.contains("where")); + assertTrue(bodyString.contains("when")); + } - @Test - void givenGraphAdd_whenMutation_thenReturnIdNameDesc() { + @Test + void givenGraphAdd_whenMutation_thenReturnIdNameDesc() { - String queryString = "mutation add { createEvent( name:\"My added GraphQL event\" where:\"Day 2\"" + - " when:\"Saturday night\" description:\"Studying GraphQL\" ){ id name description } }"; + String queryString = "mutation add {" + + " createEvent(" + + " name:\"My added GraphQL event\"" + + " where:\"Day 2\"" + + " when:\"Saturday night\"" + + " description:\"Studying GraphQL\"" + + " ){" + + " id" + + " name" + + " description" + + " }" + + "}"; + Map requestBody = new HashMap<>(); + requestBody.put("query", queryString); + requestBody.put("variables", ""); + requestBody.put("operationName", "add"); - Map requestBody = new HashMap<>(); - requestBody.put("query", queryString); - requestBody.put("variables", ""); - requestBody.put("operationName", "add"); + WebClient.ResponseSpec response = AppSyncClientHelper.getResponseBodySpec(requestBody); - WebClient.ResponseSpec response = AppSyncClientHelper.getResponseBodySpec(requestBody); + String bodyString = response.bodyToMono(String.class).block(); - String bodyString = response.bodyToMono(String.class).block(); - - assertNotNull(bodyString); - assertTrue(bodyString.contains("My added GraphQL event")); - assertFalse(bodyString.contains("where")); - assertFalse(bodyString.contains("when")); - } + assertNotNull(bodyString); + assertTrue(bodyString.contains("My added GraphQL event")); + assertFalse(bodyString.contains("where")); + assertFalse(bodyString.contains("when")); + } } diff --git a/pom.xml b/pom.xml index 22d73f3a9e..8f2cc8e902 100644 --- a/pom.xml +++ b/pom.xml @@ -1015,7 +1015,7 @@ asm atomix aws - aws-app-sync + aws-app-sync aws-lambda axon azure From e41cc37b61f7052c55bb297f1ee0ec4ea4291600 Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sun, 3 May 2020 16:38:26 +0530 Subject: [PATCH 27/91] updated readme file --- spring-core-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-core-2/README.md b/spring-core-2/README.md index 947b816db8..6068e8c3c2 100644 --- a/spring-core-2/README.md +++ b/spring-core-2/README.md @@ -14,4 +14,5 @@ This module contains articles about core Spring functionality - [Spring Events](https://www.baeldung.com/spring-events) - [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) +- [Running Setup Data in Startup] (https://www.baeldung.com/running-setup-logic-on-startup-in-spring) - More articles: [[<-- prev]](/spring-core)[[next -->]](/spring-core-3) From a1cfe519cafd993135d54bd14af21d912d5f22b1 Mon Sep 17 00:00:00 2001 From: Anshul BANSAL Date: Sun, 3 May 2020 14:38:08 +0300 Subject: [PATCH 28/91] BAEL-3995 - Spring Security with Okta --- spring-security-modules/pom.xml | 1 + .../spring-security-okta/pom.xml | 62 +++++++++++++++++++ .../java/com/baeldung/okta/Application.java | 13 ++++ .../okta/controller/AdminController.java | 43 +++++++++++++ .../okta/controller/HomeController.java | 16 +++++ .../src/main/resources/application.properties | 8 +++ 6 files changed, 143 insertions(+) create mode 100644 spring-security-modules/spring-security-okta/pom.xml create mode 100644 spring-security-modules/spring-security-okta/src/main/java/com/baeldung/okta/Application.java create mode 100644 spring-security-modules/spring-security-okta/src/main/java/com/baeldung/okta/controller/AdminController.java create mode 100644 spring-security-modules/spring-security-okta/src/main/java/com/baeldung/okta/controller/HomeController.java create mode 100644 spring-security-modules/spring-security-okta/src/main/resources/application.properties diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index 49a0db03ed..59dd75cbda 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -30,6 +30,7 @@ spring-security-mvc-login spring-security-mvc-persisted-remember-me spring-security-mvc-socket + spring-security-okta spring-security-oidc spring-security-react spring-security-rest diff --git a/spring-security-modules/spring-security-okta/pom.xml b/spring-security-modules/spring-security-okta/pom.xml new file mode 100644 index 0000000000..c5ff9013b5 --- /dev/null +++ b/spring-security-modules/spring-security-okta/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + spring-security-okta + 1.0-SNAPSHOT + spring-security-okta + war + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-web + + + com.okta.spring + okta-spring-boot-starter + ${okta.spring.version} + + + com.okta.spring + okta-spring-sdk + ${okta.spring.version} + + + + + spring-security-okta + + + src/main/resources + + + + + org.springframework.boot + spring-boot-maven-plugin + + true + + + + + repackage + + + + + + + + + 1.4.0 + + diff --git a/spring-security-modules/spring-security-okta/src/main/java/com/baeldung/okta/Application.java b/spring-security-modules/spring-security-okta/src/main/java/com/baeldung/okta/Application.java new file mode 100644 index 0000000000..0c5cc94f10 --- /dev/null +++ b/spring-security-modules/spring-security-okta/src/main/java/com/baeldung/okta/Application.java @@ -0,0 +1,13 @@ +package com.baeldung.okta; + +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-okta/src/main/java/com/baeldung/okta/controller/AdminController.java b/spring-security-modules/spring-security-okta/src/main/java/com/baeldung/okta/controller/AdminController.java new file mode 100644 index 0000000000..c7786c4006 --- /dev/null +++ b/spring-security-modules/spring-security-okta/src/main/java/com/baeldung/okta/controller/AdminController.java @@ -0,0 +1,43 @@ +package com.baeldung.okta.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import com.okta.sdk.client.Client; +import com.okta.sdk.resource.user.User; +import com.okta.sdk.resource.user.UserBuilder; +import com.okta.sdk.resource.user.UserList; + +@RestController +public class AdminController { + + @Autowired + public Client client; + + @GetMapping("/users") + public UserList getUsers() { + return client.listUsers(); + } + + @GetMapping("/user") + public UserList searchUserByEmail(@RequestParam String query) { + return client.listUsers(query, null, null, null, null); + } + + @GetMapping("/createUser") + public User createUser() { + char[] tempPassword = {'P','a','$','$','w','0','r','d'}; + User user = UserBuilder.instance() + .setEmail("norman.lewis@email.com") + .setFirstName("Norman") + .setLastName("Lewis") + .setPassword(tempPassword) + .setActive(true) + .buildAndCreate(client); + return user; + } + +} + diff --git a/spring-security-modules/spring-security-okta/src/main/java/com/baeldung/okta/controller/HomeController.java b/spring-security-modules/spring-security-okta/src/main/java/com/baeldung/okta/controller/HomeController.java new file mode 100644 index 0000000000..b8f3ec4e10 --- /dev/null +++ b/spring-security-modules/spring-security-okta/src/main/java/com/baeldung/okta/controller/HomeController.java @@ -0,0 +1,16 @@ +package com.baeldung.okta.controller; + +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.oauth2.core.oidc.user.OidcUser; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class HomeController { + + @GetMapping("/") + public String home(@AuthenticationPrincipal OidcUser user) { + return "Welcome, "+ user.getFullName() +"!"; + } + +} diff --git a/spring-security-modules/spring-security-okta/src/main/resources/application.properties b/spring-security-modules/spring-security-okta/src/main/resources/application.properties new file mode 100644 index 0000000000..4a584e3c29 --- /dev/null +++ b/spring-security-modules/spring-security-okta/src/main/resources/application.properties @@ -0,0 +1,8 @@ +okta.oauth2.issuer= //Auth server issuer URL +okta.oauth2.client-id= //Client ID of our Okta application +okta.oauth2.client-secret= //Client secret of our Okta application +okta.oauth2.redirect-uri=/authorization-code/callback + +#Okta Spring SDK configs +okta.client.orgUrl= //orgURL +okta.client.token= //token generated \ No newline at end of file From 05a4f60e38babd42b62b825157247195bd5778da Mon Sep 17 00:00:00 2001 From: Cristian Rosu Date: Sun, 3 May 2020 17:28:27 +0300 Subject: [PATCH 29/91] BAEL-3826: creating PDFs using Thymeleaf as template engine --- pdf/pom.xml | 10 ++++ .../com/baeldung/pdf/PDFThymeleafExample.java | 48 +++++++++++++++++++ .../main/resources/thymeleaf_template.html | 7 +++ 3 files changed, 65 insertions(+) create mode 100644 pdf/src/main/java/com/baeldung/pdf/PDFThymeleafExample.java create mode 100644 pdf/src/main/resources/thymeleaf_template.html diff --git a/pdf/pom.xml b/pdf/pom.xml index d148aa1670..463c88948d 100644 --- a/pdf/pom.xml +++ b/pdf/pom.xml @@ -60,6 +60,16 @@ poi-ooxml ${poi-ooxml.version} + + org.thymeleaf + thymeleaf + 3.0.11.RELEASE + + + org.xhtmlrenderer + flying-saucer-pdf + 9.1.20 + diff --git a/pdf/src/main/java/com/baeldung/pdf/PDFThymeleafExample.java b/pdf/src/main/java/com/baeldung/pdf/PDFThymeleafExample.java new file mode 100644 index 0000000000..2e1df1d320 --- /dev/null +++ b/pdf/src/main/java/com/baeldung/pdf/PDFThymeleafExample.java @@ -0,0 +1,48 @@ +package com.baeldung.pdf; + +import com.lowagie.text.DocumentException; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.context.Context; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import org.xhtmlrenderer.pdf.ITextRenderer; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +public class PDFThymeleafExample { + + public static void main(String[] args) throws IOException, DocumentException { + PDFThymeleafExample thymeleaf2Pdf = new PDFThymeleafExample(); + String html = thymeleaf2Pdf.parseThymeleafTemplate(); + thymeleaf2Pdf.generatePdfFromHtml(html); + } + + public void generatePdfFromHtml(String html) throws IOException, DocumentException { + String outputFolder = System.getProperty("user.home") + File.separator + "thymeleaf.pdf"; + OutputStream outputStream = new FileOutputStream(outputFolder); + + ITextRenderer renderer = new ITextRenderer(); + renderer.setDocumentFromString(html); + renderer.layout(); + renderer.createPDF(outputStream); + + outputStream.close(); + } + + private String parseThymeleafTemplate() { + ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode(TemplateMode.HTML); + + TemplateEngine templateEngine = new TemplateEngine(); + templateEngine.setTemplateResolver(templateResolver); + + Context context = new Context(); + context.setVariable("to", "Baeldung.com"); + + return templateEngine.process("thymeleaf_template", context); + } +} diff --git a/pdf/src/main/resources/thymeleaf_template.html b/pdf/src/main/resources/thymeleaf_template.html new file mode 100644 index 0000000000..3e856367cc --- /dev/null +++ b/pdf/src/main/resources/thymeleaf_template.html @@ -0,0 +1,7 @@ + + +

+ +

+ + \ No newline at end of file From dbb4a85c1071d6d95dbbf6ee939945b5ddccbf15 Mon Sep 17 00:00:00 2001 From: sergio41 Date: Sun, 3 May 2020 16:44:14 +0200 Subject: [PATCH 30/91] [BAEL-3944] Negative test cases --- .../PhoneNumbersRegexUnitTest.java | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java index afabf47baa..11bf1618b6 100644 --- a/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java +++ b/core-java-modules/core-java-regex/src/test/java/com/baeldung/regex/phonenumbers/PhoneNumbersRegexUnitTest.java @@ -15,6 +15,13 @@ public class PhoneNumbersRegexUnitTest { Matcher matcher = pattern.matcher("2055550125"); assertTrue(matcher.matches()); } + + @Test + public void whenMOreThanTenDigits_thenNotCorrect() { + Pattern pattern = Pattern.compile("^\\d{10}$"); + Matcher matcher = pattern.matcher("20555501251"); + assertFalse(matcher.matches()); + } @Test public void whenMatchesTenDigitsNumberWhitespacesDotHyphen_thenCorrect() { @@ -22,6 +29,27 @@ public class PhoneNumbersRegexUnitTest { Matcher matcher = pattern.matcher("202 555 0125"); assertTrue(matcher.matches()); } + + @Test + public void whenIncludesBracket_thenNotCorrect() { + Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$"); + Matcher matcher = pattern.matcher("202]555 0125"); + assertFalse(matcher.matches()); + } + + @Test + public void whenNotStartsWithBatchesOfThreeDigits_thenNotCorrect() { + Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$"); + Matcher matcher = pattern.matcher("2021 555 0125"); + assertFalse(matcher.matches()); + } + + @Test + public void whenLastPartWithNoFourDigits_thenNotCorrect() { + Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$"); + Matcher matcher = pattern.matcher("202 555 012"); + assertFalse(matcher.matches()); + } @Test public void whenMatchesTenDigitsNumberParenthesis_thenCorrect() { @@ -30,6 +58,20 @@ public class PhoneNumbersRegexUnitTest { assertTrue(matcher.matches()); } + @Test + public void whenJustOpeningParenthesis_thenNotCorrect() { + Pattern pattern = Pattern.compile("^((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); + Matcher matcher = pattern.matcher("(202 555-0125"); + assertFalse(matcher.matches()); + } + + @Test + public void whenJustClosingParenthesis_thenNotCorrect() { + Pattern pattern = Pattern.compile("^((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); + Matcher matcher = pattern.matcher("202) 555-0125"); + assertFalse(matcher.matches()); + } + @Test public void whenMatchesTenDigitsNumberPrefix_thenCorrect() { Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); @@ -37,6 +79,20 @@ public class PhoneNumbersRegexUnitTest { assertTrue(matcher.matches()); } + @Test + public void whenIncorrectPrefix_thenNotCorrect() { + Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); + Matcher matcher = pattern.matcher("-111 (202) 555-0125"); + assertFalse(matcher.matches()); + } + + @Test + public void whenTooLongPrefix_thenNotCorrect() { + Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$"); + Matcher matcher = pattern.matcher("+1111 (202) 555-0125"); + assertFalse(matcher.matches()); + } + @Test public void whenMatchesPhoneNumber_thenCorrect() { String patterns @@ -53,4 +109,21 @@ public class PhoneNumbersRegexUnitTest { assertTrue(matcher.matches()); } } + + @Test + public void whenNotMatchesPhoneNumber_thenNotCorrect() { + String patterns + = "^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$" + + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?){2}\\d{3}$" + + "|^(\\+\\d{1,3}( )?)?(\\d{3}[ ]?)(\\d{2}[ ]?){2}\\d{2}$"; + + String[] invalidPhoneNumbers + = {"20555501251","202]555 0125", "2021 555 012", "(202 555-0125", "202) 555-0125", "-111 (202) 555-0125", "+1111 (202) 555-0125", "636 85 789", "636 85 67 893"}; + + Pattern pattern = Pattern.compile(patterns); + for(String phoneNumber : invalidPhoneNumbers) { + Matcher matcher = pattern.matcher(phoneNumber); + assertFalse(matcher.matches()); + } + } } From f8cae12a3830b303442bcd808439a9f057027def Mon Sep 17 00:00:00 2001 From: Kyle Doyle Date: Sun, 3 May 2020 13:53:19 -0400 Subject: [PATCH 31/91] Bael-3893 - Updated indents with 4 spaces --- aws-app-sync/pom.xml | 90 ++++++++++++++++++++++---------------------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/aws-app-sync/pom.xml b/aws-app-sync/pom.xml index ef2085ff35..1f915978ab 100644 --- a/aws-app-sync/pom.xml +++ b/aws-app-sync/pom.xml @@ -1,56 +1,56 @@ - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.2.6.RELEASE - - + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.2.6.RELEASE + + - com.baeldung - aws-app-sync - 0.0.1-SNAPSHOT - aws-app-sync + com.baeldung + aws-app-sync + 0.0.1-SNAPSHOT + aws-app-sync - Spring Boot using AWS App Sync + Spring Boot using AWS App Sync - - 1.8 - + + 1.8 + - + - - org.springframework.boot - spring-boot-starter-web - + + org.springframework.boot + spring-boot-starter-web + - - org.springframework.boot - spring-boot-starter-test - test - - - org.junit.vintage - junit-vintage-engine - - - - - org.springframework.boot - spring-boot-starter-webflux - - + + org.springframework.boot + spring-boot-starter-test + test + + + org.junit.vintage + junit-vintage-engine + + + + + org.springframework.boot + spring-boot-starter-webflux + + - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + + + org.springframework.boot + spring-boot-maven-plugin + + + From ba42ca2dbbd07c5e89abeda3aef065f50bb74a82 Mon Sep 17 00:00:00 2001 From: Maciej Glowka Date: Sun, 3 May 2020 22:05:04 +0200 Subject: [PATCH 32/91] BAEL-3829: example of dynamic bean autowiring in Spring --- .../BeanFactoryDynamicAutowireService.java | 22 ++++++++++++++ .../autowire/DynamicAutowireConfig.java | 9 ++++++ .../InterfaceDynamicAutowireService.java | 26 ++++++++++++++++ .../dynamic/autowire/RegionService.java | 7 +++++ .../dynamic/autowire/USARegionService.java | 16 ++++++++++ .../dynamic/autowire/UkRegionService.java | 16 ++++++++++ .../DynamicAutowireIntegrationTest.java | 30 +++++++++++++++++++ 7 files changed, 126 insertions(+) create mode 100644 spring-core-4/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java create mode 100644 spring-core-4/src/main/java/com/baeldung/dynamic/autowire/DynamicAutowireConfig.java create mode 100644 spring-core-4/src/main/java/com/baeldung/dynamic/autowire/InterfaceDynamicAutowireService.java create mode 100644 spring-core-4/src/main/java/com/baeldung/dynamic/autowire/RegionService.java create mode 100644 spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USARegionService.java create mode 100644 spring-core-4/src/main/java/com/baeldung/dynamic/autowire/UkRegionService.java create mode 100644 spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java new file mode 100644 index 0000000000..5f8f2e548e --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java @@ -0,0 +1,22 @@ +package com.baeldung.dynamic.autowire; + +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class BeanFactoryDynamicAutowireService { + private final BeanFactory beanFactory; + + @Autowired + public BeanFactoryDynamicAutowireService(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + + public boolean isServerActive(String countryCode, int serverId) { + RegionService service = beanFactory.getBean(countryCode, RegionService.class); + + return service.isServerActive(serverId); + } + +} diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/DynamicAutowireConfig.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/DynamicAutowireConfig.java new file mode 100644 index 0000000000..256bd9b495 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/DynamicAutowireConfig.java @@ -0,0 +1,9 @@ +package com.baeldung.dynamic.autowire; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@ComponentScan("com.baeldung.dynamic.autowire") +public class DynamicAutowireConfig { +} diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/InterfaceDynamicAutowireService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/InterfaceDynamicAutowireService.java new file mode 100644 index 0000000000..ad655f5c42 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/InterfaceDynamicAutowireService.java @@ -0,0 +1,26 @@ +package com.baeldung.dynamic.autowire; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +@Service +public class InterfaceDynamicAutowireService { + private final Map servicesByCountryCode; + + @Autowired + public InterfaceDynamicAutowireService(List regionServices) { + servicesByCountryCode = regionServices.stream() + .collect(Collectors.toMap(RegionService::getCountryCode, Function.identity())); + } + + public boolean isServerActive(String countryCode, int serverId) { + RegionService service = servicesByCountryCode.get(countryCode); + + return service.isServerActive(serverId); + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/RegionService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/RegionService.java new file mode 100644 index 0000000000..f9f92d045a --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/RegionService.java @@ -0,0 +1,7 @@ +package com.baeldung.dynamic.autowire; + +public interface RegionService { + boolean isServerActive(int serverId); + + String getCountryCode(); +} diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USARegionService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USARegionService.java new file mode 100644 index 0000000000..cfad0146e5 --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USARegionService.java @@ -0,0 +1,16 @@ +package com.baeldung.dynamic.autowire; + +import org.springframework.stereotype.Service; + +@Service("usa") +public class USARegionService implements RegionService { + @Override + public boolean isServerActive(int serverId) { + return true; + } + + @Override + public String getCountryCode() { + return "usa"; + } +} diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/UkRegionService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/UkRegionService.java new file mode 100644 index 0000000000..1fbe8ed96e --- /dev/null +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/UkRegionService.java @@ -0,0 +1,16 @@ +package com.baeldung.dynamic.autowire; + +import org.springframework.stereotype.Service; + +@Service("uk") +public class UkRegionService implements RegionService { + @Override + public boolean isServerActive(int serverId) { + return false; + } + + @Override + public String getCountryCode() { + return "uk"; + } +} diff --git a/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java new file mode 100644 index 0000000000..5afab69c53 --- /dev/null +++ b/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java @@ -0,0 +1,30 @@ +package com.baeldung.dynamic.autowire; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = DynamicAutowireConfig.class) +public class DynamicAutowireIntegrationTest { + + @Autowired + private BeanFactoryDynamicAutowireService beanFactoryDynamicAutowireService; + + @Autowired + private InterfaceDynamicAutowireService interfaceDynamicAutowireService; + + @Test + public void testConstructWorkerByJava() { + assertThat(beanFactoryDynamicAutowireService.isServerActive("uk", 101), is(false)); + assertThat(interfaceDynamicAutowireService.isServerActive("uk", 101), is(false)); + + assertThat(beanFactoryDynamicAutowireService.isServerActive("usa", 101), is(true)); + assertThat(interfaceDynamicAutowireService.isServerActive("usa", 101), is(true)); + } +} From 7ec77df0960181bdf35e8770d332ac7602b43e8a Mon Sep 17 00:00:00 2001 From: Chirag Dewan Date: Mon, 4 May 2020 18:11:12 +0530 Subject: [PATCH 33/91] BAEL1731 Adding listappender --- .../logging/log4j2/plugins/ListAppender.java | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/ListAppender.java diff --git a/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/ListAppender.java b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/ListAppender.java new file mode 100644 index 0000000000..e3819028db --- /dev/null +++ b/logging-modules/log4j2/src/main/java/com/baeldung/logging/log4j2/plugins/ListAppender.java @@ -0,0 +1,48 @@ +/** + * + */ +package com.baeldung.logging.log4j2.plugins; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.Core; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static java.util.Collections.synchronizedList; + +@Plugin(name = "ListAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE) +public class ListAppender extends AbstractAppender { + + private List logList; + + protected ListAppender(String name, Filter filter) { + super(name, filter, null); + logList = synchronizedList(new ArrayList<>()); + } + + @PluginFactory + public static ListAppender createAppender(@PluginAttribute("name") String name, @PluginElement("Filter") final Filter filter) { + return new ListAppender(name, filter); + } + + @Override + public void append(LogEvent event) { + if (event.getLevel() + .isLessSpecificThan(Level.WARN)) { + error("Unable to log less than WARN level."); + return; + } + logList.add(event); + } + +} From 7f4368556772836b2dd53b3360c8a735b742290b Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 08:35:36 +0800 Subject: [PATCH 34/91] Update README.md --- libraries-3/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/libraries-3/README.md b/libraries-3/README.md index ec433960ef..62bd3b9f66 100644 --- a/libraries-3/README.md +++ b/libraries-3/README.md @@ -16,4 +16,3 @@ Remember, for advanced libraries like [Jackson](/jackson) and [JUnit](/testing-m - [Introduction to Takes](https://www.baeldung.com/java-takes) - [Using NullAway to Avoid NullPointerExceptions](https://www.baeldung.com/java-nullaway) - [Introduction to Alibaba Arthas](https://www.baeldung.com/java-alibaba-arthas-intro) -- [Quick Guide to Spring Cloud Circuit Breaker](https://www.baeldung.com/spring-cloud-circuit-breaker) From dd4b25e855a1a94127f73420b92f1ee285cb3123 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 08:43:18 +0800 Subject: [PATCH 35/91] Update README.md --- spring-mvc-basics-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-mvc-basics-2/README.md b/spring-mvc-basics-2/README.md index e52459bd6e..673b7b1fef 100644 --- a/spring-mvc-basics-2/README.md +++ b/spring-mvc-basics-2/README.md @@ -9,7 +9,7 @@ This module contains articles about Spring MVC - [Servlet Redirect vs Forward](https://www.baeldung.com/servlet-redirect-forward) - [Apache Tiles Integration with Spring MVC](https://www.baeldung.com/spring-mvc-apache-tiles) - [Guide to Spring Email](https://www.baeldung.com/spring-email) -- [Using ThymeLeaf and FreeMarker Emails Templates with Spring](https://www.baeldung.com/thymeleaf-freemarker-email) +- [Using ThymeLeaf and FreeMarker Emails Templates with Spring](https://www.baeldung.com/spring-email-templates) - [Request Method Not Supported (405) in Spring](https://www.baeldung.com/spring-request-method-not-supported-405) - [Spring @RequestParam Annotation](https://www.baeldung.com/spring-request-param) - More articles: [[more -->]](/spring-mvc-basics-3) From 1f95843c36f170d285b432d61091d7989b89cbdd Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 08:47:17 +0800 Subject: [PATCH 36/91] Delete README.md --- bazel/bazelapp/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 bazel/bazelapp/README.md diff --git a/bazel/bazelapp/README.md b/bazel/bazelapp/README.md deleted file mode 100644 index 528f797c21..0000000000 --- a/bazel/bazelapp/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Building Java Applications with Bazel](https://www.baeldung.com/bazel-build-tool) From e164ae4c72a806049f4054947b28c3df1194a0e0 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 08:53:16 +0800 Subject: [PATCH 37/91] Delete README.md --- oauth2-framework-impl/oauth2-authorization-server/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 oauth2-framework-impl/oauth2-authorization-server/README.md diff --git a/oauth2-framework-impl/oauth2-authorization-server/README.md b/oauth2-framework-impl/oauth2-authorization-server/README.md deleted file mode 100644 index 4bcb9790b1..0000000000 --- a/oauth2-framework-impl/oauth2-authorization-server/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Implementing The OAuth 2.0 Authorization Framework Using Jakarta EE](https://www.baeldung.com/java-ee-oauth2-implementation) From 33fa3b7275fe96aaee04a14f7f8a9dfcdb1aca59 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 08:57:04 +0800 Subject: [PATCH 38/91] Delete README.md --- oauth2-framework-impl/oauth2-resource-server/README.md | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 oauth2-framework-impl/oauth2-resource-server/README.md diff --git a/oauth2-framework-impl/oauth2-resource-server/README.md b/oauth2-framework-impl/oauth2-resource-server/README.md deleted file mode 100644 index 4bcb9790b1..0000000000 --- a/oauth2-framework-impl/oauth2-resource-server/README.md +++ /dev/null @@ -1,3 +0,0 @@ -### Relevant Articles: - -- [Implementing The OAuth 2.0 Authorization Framework Using Jakarta EE](https://www.baeldung.com/java-ee-oauth2-implementation) From caca2dbea73fa638ff7fd24d2798c0296bf07e99 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 09:00:24 +0800 Subject: [PATCH 39/91] Update README.md --- spring-swagger-codegen/spring-swagger-codegen-app/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-swagger-codegen/spring-swagger-codegen-app/README.md b/spring-swagger-codegen/spring-swagger-codegen-app/README.md index 1cb9e35d99..8740b17ba3 100644 --- a/spring-swagger-codegen/spring-swagger-codegen-app/README.md +++ b/spring-swagger-codegen/spring-swagger-codegen-app/README.md @@ -1,3 +1,3 @@ ## Spring Swagger Codegen App -This module contains the code for [Generate Spring Boot REST Client with Swagger](http://www.baeldung.com/spring-boot-rest-client-swagger-codegen). +This module contains the code for Generate Spring Boot REST Client with Swagger. From 0167480f880aae12f1af7bfd5a6b7ce81a7eb6e4 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 09:21:38 +0800 Subject: [PATCH 40/91] Update README.md --- core-java-modules/core-java-concurrency-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-java-modules/core-java-concurrency-2/README.md b/core-java-modules/core-java-concurrency-2/README.md index ab7eebc26a..23471a237e 100644 --- a/core-java-modules/core-java-concurrency-2/README.md +++ b/core-java-modules/core-java-concurrency-2/README.md @@ -4,5 +4,5 @@ ### Relevant Articles: - [Using a Mutex Object in Java](https://www.baeldung.com/java-mutex) -- [Testing Multi-Threaded Code in Java] (https://www.baeldung.com/java-testing-multithreaded) +- [Testing Multi-Threaded Code in Java](https://www.baeldung.com/java-testing-multithreaded) From d95a78b1924fe104b8de116bfc8c4e306ec52199 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 15:26:18 +0800 Subject: [PATCH 41/91] Update README.md --- spring-core-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-core-2/README.md b/spring-core-2/README.md index 947b816db8..10d3080b45 100644 --- a/spring-core-2/README.md +++ b/spring-core-2/README.md @@ -14,4 +14,5 @@ This module contains articles about core Spring functionality - [Spring Events](https://www.baeldung.com/spring-events) - [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) +- [Running Setup Data on Startup in Spring](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) - More articles: [[<-- prev]](/spring-core)[[next -->]](/spring-core-3) From efa810462107cdbc98de292f81eb4c7c1c72fccd Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 16:42:15 +0800 Subject: [PATCH 42/91] Update README.md --- spring-thymeleaf-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-thymeleaf-2/README.md b/spring-thymeleaf-2/README.md index d5c5ead43d..d2d10f81da 100644 --- a/spring-thymeleaf-2/README.md +++ b/spring-thymeleaf-2/README.md @@ -13,4 +13,5 @@ This module contains articles about Spring with Thymeleaf - [Working with Boolean in Thymeleaf](https://www.baeldung.com/thymeleaf-boolean) - [Working With Custom HTML Attributes in Thymeleaf](https://www.baeldung.com/thymeleaf-custom-html-attributes) - [How to Create an Executable JAR with Maven](https://www.baeldung.com/executable-jar-with-maven) +- [https://www.baeldung.com/spring-mvc-thymeleaf-data](https://www.baeldung.com/spring-mvc-thymeleaf-data) - [[<-- prev]](/spring-thymeleaf) From 66cf67cc7c6ac5b21efbcf47fd50ef2f466c598a Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 16:45:16 +0800 Subject: [PATCH 43/91] Update README.md --- spring-cloud/spring-cloud-circuit-breaker/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/spring-cloud/spring-cloud-circuit-breaker/README.md b/spring-cloud/spring-cloud-circuit-breaker/README.md index 040eb0ccee..894be93408 100644 --- a/spring-cloud/spring-cloud-circuit-breaker/README.md +++ b/spring-cloud/spring-cloud-circuit-breaker/README.md @@ -3,3 +3,5 @@ This module contains articles about Spring Cloud Circuit Breaker ### Relevant Articles: + +- [Quick Guide to Spring Cloud Circuit Breaker](https://www.baeldung.com/spring-cloud-circuit-breaker) From 38bc3707712404e25431a2c1d1b8ba2222eb3984 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 16:47:03 +0800 Subject: [PATCH 44/91] Update README.md --- persistence-modules/hibernate-jpa/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/hibernate-jpa/README.md b/persistence-modules/hibernate-jpa/README.md index fb48f975bc..514fcedb8a 100644 --- a/persistence-modules/hibernate-jpa/README.md +++ b/persistence-modules/hibernate-jpa/README.md @@ -14,3 +14,4 @@ This module contains articles specific to use of Hibernate as a JPA implementati - [TransactionRequiredException Error](https://www.baeldung.com/jpa-transaction-required-exception) - [JPA/Hibernate Persistence Context](https://www.baeldung.com/jpa-hibernate-persistence-context) - [Quick Guide to EntityManager#getReference()](https://www.baeldung.com/jpa-entity-manager-get-reference) +- [Hibernate Error “No Persistence Provider for EntityManager”](https://www.baeldung.com/hibernate-no-persistence-provider) From 66832ae37ec0c57512b8466c5feed6867a0b81be Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 16:51:28 +0800 Subject: [PATCH 45/91] Update README.md --- core-java-modules/core-java-streams-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-streams-3/README.md b/core-java-modules/core-java-streams-3/README.md index 05c4b99900..65713aa04f 100644 --- a/core-java-modules/core-java-streams-3/README.md +++ b/core-java-modules/core-java-streams-3/README.md @@ -10,4 +10,5 @@ This module contains articles about the Stream API in Java. - [Primitive Type Streams in Java 8](https://www.baeldung.com/java-8-primitive-streams) - [Debugging Java 8 Streams with IntelliJ](https://www.baeldung.com/intellij-debugging-java-streams) - [Add BigDecimals using the Stream API](https://www.baeldung.com/java-stream-add-bigdecimals) +- [Should We Close a Java Stream?](https://www.baeldung.com/java-stream-close) - More articles: [[<-- prev>]](/../core-java-streams-2) From 44c7cecd657092a6fb68c5944d2b2236d1f7f450 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 16:53:27 +0800 Subject: [PATCH 46/91] Update README.md --- core-java-modules/core-java-collections-maps-3/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-collections-maps-3/README.md b/core-java-modules/core-java-collections-maps-3/README.md index 64a3b75d83..7386f7e9b7 100644 --- a/core-java-modules/core-java-collections-maps-3/README.md +++ b/core-java-modules/core-java-collections-maps-3/README.md @@ -5,4 +5,5 @@ This module contains articles about Map data structures in Java. ### Relevant Articles: - [Java TreeMap vs HashMap](https://www.baeldung.com/java-treemap-vs-hashmap) - [Comparing Two HashMaps in Java](https://www.baeldung.com/java-compare-hashmaps) +- [The Map.computeIfAbsent() Method](https://www.baeldung.com/java-map-computeifabsent) - More articles: [[<-- prev]](/core-java-modules/core-java-collections-maps-2) From 48525264a085b93b8810ac175c5539720a8abd7b Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 16:57:15 +0800 Subject: [PATCH 47/91] Update README.md --- core-java-modules/core-java-networking-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/core-java-modules/core-java-networking-2/README.md b/core-java-modules/core-java-networking-2/README.md index 120b111ff5..662d97252e 100644 --- a/core-java-modules/core-java-networking-2/README.md +++ b/core-java-modules/core-java-networking-2/README.md @@ -11,4 +11,5 @@ This module contains articles about networking in Java - [Sending Emails with Java](https://www.baeldung.com/java-email) - [Authentication with HttpUrlConnection](https://www.baeldung.com/java-http-url-connection) - [Download a File from an URL in Java](https://www.baeldung.com/java-download-file) +- [Handling java.net.ConnectException](https://www.baeldung.com/java-net-connectexception) - [[<-- Prev]](/core-java-modules/core-java-networking) From 01dc9eec8d506bbd6e8dceaf6d3c93a8731c605c Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:03:15 +0800 Subject: [PATCH 48/91] Create README.md --- spring-boot-modules/spring-boot/src/test/resources/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 spring-boot-modules/spring-boot/src/test/resources/README.md diff --git a/spring-boot-modules/spring-boot/src/test/resources/README.md b/spring-boot-modules/spring-boot/src/test/resources/README.md new file mode 100644 index 0000000000..51c95afd9d --- /dev/null +++ b/spring-boot-modules/spring-boot/src/test/resources/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [How to Test GraphQL Using Postman](https://www.baeldung.com/graphql-postman) From 60364c19e5f642785bcba10cee9f322f66cb697b Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:05:25 +0800 Subject: [PATCH 49/91] Update README.md --- libraries-testing/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries-testing/README.md b/libraries-testing/README.md index 7098c10d28..ffdefe4b19 100644 --- a/libraries-testing/README.md +++ b/libraries-testing/README.md @@ -11,4 +11,4 @@ This module contains articles about test libraries. - [Introduction to Awaitlity](https://www.baeldung.com/awaitlity-testing) - [Introduction to Hoverfly in Java](https://www.baeldung.com/hoverfly) - [Testing with Hamcrest](https://www.baeldung.com/java-junit-hamcrest-guide) -- [Introduction To DBUnit](https://www.baeldung.com/dbunit) +- [Introduction To DBUnit](https://www.baeldung.com/java-dbunit) From e232346eb937bab9bf2d74a727e90d833f1d5982 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:08:45 +0800 Subject: [PATCH 50/91] Update README.md --- testing-modules/junit5-annotations/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/junit5-annotations/README.md b/testing-modules/junit5-annotations/README.md index 02d4cd652a..bd51bb3d2d 100644 --- a/testing-modules/junit5-annotations/README.md +++ b/testing-modules/junit5-annotations/README.md @@ -7,3 +7,4 @@ This module contains articles about JUnit 5 Annotations - [JUnit 5 Conditional Test Execution with Annotations](https://www.baeldung.com/junit-5-conditional-test-execution) - [JUnit5 Programmatic Extension Registration with @RegisterExtension](https://www.baeldung.com/junit-5-registerextension-annotation) - [Guide to JUnit 5 Parameterized Tests](https://www.baeldung.com/parameterized-tests-junit-5) +- [Writing Templates for Test Cases Using JUnit 5](https://www.baeldung.com/junit5-test-templates) From 4ef6e5efbd0236c1b031a8f53f197b7bcac412b3 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:10:54 +0800 Subject: [PATCH 51/91] Update README.md --- reactor-core/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/reactor-core/README.md b/reactor-core/README.md index e3cca35f86..0214aa26fd 100644 --- a/reactor-core/README.md +++ b/reactor-core/README.md @@ -7,3 +7,4 @@ This module contains articles about Reactor Core. - [Intro To Reactor Core](https://www.baeldung.com/reactor-core) - [Combining Publishers in Project Reactor](https://www.baeldung.com/reactor-combine-streams) - [Programmatically Creating Sequences with Project Reactor](https://www.baeldung.com/flux-sequences-reactor) +- [How to Extract a Mono’s Content in Java](https://www.baeldung.com/java-string-from-mono) From c034df09fc1118f67b403c11bc8dbdf9f3b554c5 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:16:27 +0800 Subject: [PATCH 52/91] Update README.md --- core-groovy/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core-groovy/README.md b/core-groovy/README.md index 25a0aece3a..f852b3ccf2 100644 --- a/core-groovy/README.md +++ b/core-groovy/README.md @@ -12,4 +12,5 @@ This module contains articles about core Groovy concepts - [Closures in Groovy](https://www.baeldung.com/groovy-closures) - [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date) - [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io) -- [[More -->]](/core-groovy-2) \ No newline at end of file +- [Convert String to Integer in Groovy](https://www.baeldung.com/groovy-convert-string-to-integer) +- [[More -->]](/core-groovy-2) From 424fecc7d9c44d0953405f7e5a1df882e6be00d4 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:23:23 +0800 Subject: [PATCH 53/91] Update README.md --- testing-modules/mockito-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/testing-modules/mockito-2/README.md b/testing-modules/mockito-2/README.md index 6c9ddee01d..329228186f 100644 --- a/testing-modules/mockito-2/README.md +++ b/testing-modules/mockito-2/README.md @@ -5,3 +5,4 @@ - [Mockito Strict Stubbing and The UnnecessaryStubbingException](https://www.baeldung.com/mockito-unnecessary-stubbing-exception) - [Mockito and Fluent APIs](https://www.baeldung.com/mockito-fluent-apis) - [Mocking the ObjectMapper readValue() Method](https://www.baeldung.com/mockito-mock-jackson-read-value) +- [Introduction to Mockito’s AdditionalAnswers](https://www.baeldung.com/mockito-additionalanswers) From 629ba77f5676616d0c8aad7eeb8fc6121c1e5c94 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:27:51 +0800 Subject: [PATCH 54/91] Update README.md --- persistence-modules/java-mongodb/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/java-mongodb/README.md b/persistence-modules/java-mongodb/README.md index 5c3c448b03..b79cea6781 100644 --- a/persistence-modules/java-mongodb/README.md +++ b/persistence-modules/java-mongodb/README.md @@ -11,3 +11,4 @@ This module contains articles about MongoDB in Java. - [Introduction to Morphia – Java ODM for MongoDB](https://www.baeldung.com/mongodb-morphia) - [MongoDB Aggregations Using Java](https://www.baeldung.com/java-mongodb-aggregations) - [MongoDB BSON to JSON](https://www.baeldung.com/bson-to-json) +- [BSON to JSON Document Conversion in Java](https://www.baeldung.com/java-convert-bson-to-json) From e0c1a17a68e69c737153ea97951ce3729927b471 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:31:23 +0800 Subject: [PATCH 55/91] Create README.md --- terraform/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 terraform/README.md diff --git a/terraform/README.md b/terraform/README.md new file mode 100644 index 0000000000..19abd2ff20 --- /dev/null +++ b/terraform/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Introduction to Terraform](https://www.baeldung.com/ops/terraform-intro) From 1793a19bfc8dde7c1fcc14e44a68566072104512 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:36:42 +0800 Subject: [PATCH 56/91] Update README.md --- persistence-modules/spring-data-jpa-4/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-data-jpa-4/README.md b/persistence-modules/spring-data-jpa-4/README.md index 3884435f75..085dfcb366 100644 --- a/persistence-modules/spring-data-jpa-4/README.md +++ b/persistence-modules/spring-data-jpa-4/README.md @@ -6,6 +6,7 @@ - [JPA Entity Lifecycle Events](https://www.baeldung.com/jpa-entity-lifecycle-events) - [Working with Lazy Element Collections in JPA](https://www.baeldung.com/java-jpa-lazy-collections) - [Calling Stored Procedures from Spring Data JPA Repositories](https://www.baeldung.com/spring-data-jpa-stored-procedures) +- [Custom Naming Convention with Spring Data JPA](https://www.baeldung.com/spring-data-jpa-custom-naming) ### Eclipse Config After importing the project into Eclipse, you may see the following error: From 7d3aa9f3e594acb660606993b060963ab06430b0 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:43:34 +0800 Subject: [PATCH 57/91] Create README.md --- java-collections-maps-3/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 java-collections-maps-3/README.md diff --git a/java-collections-maps-3/README.md b/java-collections-maps-3/README.md new file mode 100644 index 0000000000..4da8547824 --- /dev/null +++ b/java-collections-maps-3/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [Java Map With Case-Insensitive Keys](https://www.baeldung.com/java-map-with-case-insensitive-keys) From 6335a8eaa526fa5040e10f639e951e4acea64fbf Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:47:21 +0800 Subject: [PATCH 58/91] Create README.md --- netty/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 netty/README.md diff --git a/netty/README.md b/netty/README.md new file mode 100644 index 0000000000..30c63cd5a8 --- /dev/null +++ b/netty/README.md @@ -0,0 +1,3 @@ +### Relevant Articles: + +- [HTTP/2 in Netty](https://www.baeldung.com/netty-http2) From 9d62a60deb4e6dec5909da86fbe41b56b75059c1 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:50:35 +0800 Subject: [PATCH 59/91] Update README.md --- persistence-modules/spring-boot-persistence-2/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/persistence-modules/spring-boot-persistence-2/README.md b/persistence-modules/spring-boot-persistence-2/README.md index 5d171fb2ca..3ea93db4fe 100644 --- a/persistence-modules/spring-boot-persistence-2/README.md +++ b/persistence-modules/spring-boot-persistence-2/README.md @@ -1,3 +1,4 @@ ### Relevant Articles: - [Using JDBI with Spring Boot](https://www.baeldung.com/spring-boot-jdbi) +- [Oracle Connection Pooling With Spring](https://www.baeldung.com/spring-oracle-connection-pooling) From 22b4859f6269868251ee42854d6a909059bcfdf1 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Tue, 5 May 2020 17:54:09 +0800 Subject: [PATCH 60/91] Update README.md --- atomikos/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/atomikos/README.md b/atomikos/README.md index 19f2e871d4..2c44e388fe 100644 --- a/atomikos/README.md +++ b/atomikos/README.md @@ -4,4 +4,4 @@ This module contains articles about Atomikos ### Relevant Articles: -- [Guide Transactions Using Atomikos]() +- [A Guide to Atomikos](https://www.baeldung.com/java-atomikos) From 13f2b10c8b7bff8dd99fa5831434ce97247815a6 Mon Sep 17 00:00:00 2001 From: Maciej Glowka Date: Wed, 6 May 2020 00:35:07 +0200 Subject: [PATCH 61/91] BAEL-3829: added more distinct bean names, changed country codes to ISO codes --- .../autowire/BeanFactoryDynamicAutowireService.java | 9 +++++++-- ...va => CustomMapFromListDynamicAutowireService.java} | 10 +++++----- .../{UkRegionService.java => GBRegionService.java} | 8 ++++---- .../com/baeldung/dynamic/autowire/RegionService.java | 2 +- .../{USARegionService.java => USRegionService.java} | 8 ++++---- .../autowire/DynamicAutowireIntegrationTest.java | 10 +++++----- 6 files changed, 26 insertions(+), 21 deletions(-) rename spring-core-4/src/main/java/com/baeldung/dynamic/autowire/{InterfaceDynamicAutowireService.java => CustomMapFromListDynamicAutowireService.java} (55%) rename spring-core-4/src/main/java/com/baeldung/dynamic/autowire/{UkRegionService.java => GBRegionService.java} (58%) rename spring-core-4/src/main/java/com/baeldung/dynamic/autowire/{USARegionService.java => USRegionService.java} (58%) diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java index 5f8f2e548e..4ad4420489 100644 --- a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/BeanFactoryDynamicAutowireService.java @@ -6,6 +6,7 @@ import org.springframework.stereotype.Service; @Service public class BeanFactoryDynamicAutowireService { + private static final String SERVICE_NAME_SUFFIX = "regionService"; private final BeanFactory beanFactory; @Autowired @@ -13,10 +14,14 @@ public class BeanFactoryDynamicAutowireService { this.beanFactory = beanFactory; } - public boolean isServerActive(String countryCode, int serverId) { - RegionService service = beanFactory.getBean(countryCode, RegionService.class); + public boolean isServerActive(String isoCountryCode, int serverId) { + RegionService service = beanFactory.getBean(getRegionServiceBeanName(isoCountryCode), RegionService.class); return service.isServerActive(serverId); } + private String getRegionServiceBeanName(String isoCountryCode) { + return isoCountryCode + SERVICE_NAME_SUFFIX; + } + } diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/InterfaceDynamicAutowireService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/CustomMapFromListDynamicAutowireService.java similarity index 55% rename from spring-core-4/src/main/java/com/baeldung/dynamic/autowire/InterfaceDynamicAutowireService.java rename to spring-core-4/src/main/java/com/baeldung/dynamic/autowire/CustomMapFromListDynamicAutowireService.java index ad655f5c42..e04c345d51 100644 --- a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/InterfaceDynamicAutowireService.java +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/CustomMapFromListDynamicAutowireService.java @@ -9,17 +9,17 @@ import java.util.function.Function; import java.util.stream.Collectors; @Service -public class InterfaceDynamicAutowireService { +public class CustomMapFromListDynamicAutowireService { private final Map servicesByCountryCode; @Autowired - public InterfaceDynamicAutowireService(List regionServices) { + public CustomMapFromListDynamicAutowireService(List regionServices) { servicesByCountryCode = regionServices.stream() - .collect(Collectors.toMap(RegionService::getCountryCode, Function.identity())); + .collect(Collectors.toMap(RegionService::getISOCountryCode, Function.identity())); } - public boolean isServerActive(String countryCode, int serverId) { - RegionService service = servicesByCountryCode.get(countryCode); + public boolean isServerActive(String isoCountryCode, int serverId) { + RegionService service = servicesByCountryCode.get(isoCountryCode); return service.isServerActive(serverId); } diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/UkRegionService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/GBRegionService.java similarity index 58% rename from spring-core-4/src/main/java/com/baeldung/dynamic/autowire/UkRegionService.java rename to spring-core-4/src/main/java/com/baeldung/dynamic/autowire/GBRegionService.java index 1fbe8ed96e..8c6a1372d4 100644 --- a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/UkRegionService.java +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/GBRegionService.java @@ -2,15 +2,15 @@ package com.baeldung.dynamic.autowire; import org.springframework.stereotype.Service; -@Service("uk") -public class UkRegionService implements RegionService { +@Service("GBregionService") +public class GBRegionService implements RegionService { @Override public boolean isServerActive(int serverId) { return false; } @Override - public String getCountryCode() { - return "uk"; + public String getISOCountryCode() { + return "GB"; } } diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/RegionService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/RegionService.java index f9f92d045a..a2caf38ab3 100644 --- a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/RegionService.java +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/RegionService.java @@ -3,5 +3,5 @@ package com.baeldung.dynamic.autowire; public interface RegionService { boolean isServerActive(int serverId); - String getCountryCode(); + String getISOCountryCode(); } diff --git a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USARegionService.java b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USRegionService.java similarity index 58% rename from spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USARegionService.java rename to spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USRegionService.java index cfad0146e5..a2d5f47553 100644 --- a/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USARegionService.java +++ b/spring-core-4/src/main/java/com/baeldung/dynamic/autowire/USRegionService.java @@ -2,15 +2,15 @@ package com.baeldung.dynamic.autowire; import org.springframework.stereotype.Service; -@Service("usa") -public class USARegionService implements RegionService { +@Service("USregionService") +public class USRegionService implements RegionService { @Override public boolean isServerActive(int serverId) { return true; } @Override - public String getCountryCode() { - return "usa"; + public String getISOCountryCode() { + return "US"; } } diff --git a/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java index 5afab69c53..3eb6268e97 100644 --- a/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java +++ b/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java @@ -17,14 +17,14 @@ public class DynamicAutowireIntegrationTest { private BeanFactoryDynamicAutowireService beanFactoryDynamicAutowireService; @Autowired - private InterfaceDynamicAutowireService interfaceDynamicAutowireService; + private CustomMapFromListDynamicAutowireService customMapFromListDynamicAutowireService; @Test public void testConstructWorkerByJava() { - assertThat(beanFactoryDynamicAutowireService.isServerActive("uk", 101), is(false)); - assertThat(interfaceDynamicAutowireService.isServerActive("uk", 101), is(false)); + assertThat(beanFactoryDynamicAutowireService.isServerActive("GB", 101), is(false)); + assertThat(customMapFromListDynamicAutowireService.isServerActive("GB", 101), is(false)); - assertThat(beanFactoryDynamicAutowireService.isServerActive("usa", 101), is(true)); - assertThat(interfaceDynamicAutowireService.isServerActive("usa", 101), is(true)); + assertThat(beanFactoryDynamicAutowireService.isServerActive("US", 101), is(true)); + assertThat(customMapFromListDynamicAutowireService.isServerActive("US", 101), is(true)); } } From b4315b82d889944899672ddde5675c31599fdc33 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 6 May 2020 15:12:08 +0800 Subject: [PATCH 62/91] Update README.md --- spring-thymeleaf-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-thymeleaf-2/README.md b/spring-thymeleaf-2/README.md index d2d10f81da..a8c067a443 100644 --- a/spring-thymeleaf-2/README.md +++ b/spring-thymeleaf-2/README.md @@ -13,5 +13,5 @@ This module contains articles about Spring with Thymeleaf - [Working with Boolean in Thymeleaf](https://www.baeldung.com/thymeleaf-boolean) - [Working With Custom HTML Attributes in Thymeleaf](https://www.baeldung.com/thymeleaf-custom-html-attributes) - [How to Create an Executable JAR with Maven](https://www.baeldung.com/executable-jar-with-maven) -- [https://www.baeldung.com/spring-mvc-thymeleaf-data](https://www.baeldung.com/spring-mvc-thymeleaf-data) +- [Spring MVC Data and Thymeleaf](https://www.baeldung.com/spring-mvc-thymeleaf-data) - [[<-- prev]](/spring-thymeleaf) From c9ebd8e33e6da1859c06e02e53db7dd615bef7e1 Mon Sep 17 00:00:00 2001 From: johnA1331 <53036378+johnA1331@users.noreply.github.com> Date: Wed, 6 May 2020 15:17:10 +0800 Subject: [PATCH 63/91] Update README.md --- atomikos/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/atomikos/README.md b/atomikos/README.md index 2c44e388fe..f9129233ec 100644 --- a/atomikos/README.md +++ b/atomikos/README.md @@ -1,5 +1,4 @@ ## Atomikos - This module contains articles about Atomikos ### Relevant Articles: From 0e33f2d06cd9f71bdfa810e1ecd6bf2c754b4cab Mon Sep 17 00:00:00 2001 From: Maciej Glowka Date: Thu, 7 May 2020 23:25:43 +0200 Subject: [PATCH 64/91] BAEL-3829: fixed test method names --- .../dynamic/autowire/DynamicAutowireIntegrationTest.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java b/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java index 3eb6268e97..56582ecb66 100644 --- a/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java +++ b/spring-core-4/src/test/java/com/baeldung/dynamic/autowire/DynamicAutowireIntegrationTest.java @@ -20,10 +20,13 @@ public class DynamicAutowireIntegrationTest { private CustomMapFromListDynamicAutowireService customMapFromListDynamicAutowireService; @Test - public void testConstructWorkerByJava() { + public void givenDynamicallyAutowiredBean_whenCheckingServerInGB_thenServerIsNotActive() { assertThat(beanFactoryDynamicAutowireService.isServerActive("GB", 101), is(false)); assertThat(customMapFromListDynamicAutowireService.isServerActive("GB", 101), is(false)); + } + @Test + public void givenDynamicallyAutowiredBean_whenCheckingServerInUS_thenServerIsActive() { assertThat(beanFactoryDynamicAutowireService.isServerActive("US", 101), is(true)); assertThat(customMapFromListDynamicAutowireService.isServerActive("US", 101), is(true)); } From a93fc0541e9f463f394659fb9a1a05ec1f13e689 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Fri, 8 May 2020 19:06:20 +0530 Subject: [PATCH 65/91] JAVA-954: Migrate spring-social-login to parent-boot-2 --- spring-social-login/pom.xml | 20 +++++++++--- .../java/com/baeldung/config/Application.java | 2 +- .../com/baeldung/config/SecurityConfig.java | 32 ++++++++++++++----- 3 files changed, 41 insertions(+), 13 deletions(-) diff --git a/spring-social-login/pom.xml b/spring-social-login/pom.xml index 9fa839f1c2..628f439cc0 100644 --- a/spring-social-login/pom.xml +++ b/spring-social-login/pom.xml @@ -8,9 +8,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -42,15 +42,16 @@ org.thymeleaf.extras - thymeleaf-extras-springsecurity4 + thymeleaf-extras-springsecurity5 org.springframework.social spring-social-facebook + ${spring.social.facebook.version} - + org.springframework.boot spring-boot-starter-data-jpa @@ -60,6 +61,12 @@ com.h2database h2 + + + net.bytebuddy + byte-buddy-dep + ${bytebuddy.version} + @@ -93,5 +100,10 @@
+ + + 1.10.9 + 2.0.3.RELEASE + \ No newline at end of file diff --git a/spring-social-login/src/main/java/com/baeldung/config/Application.java b/spring-social-login/src/main/java/com/baeldung/config/Application.java index 5d083d2d47..c65df6dbfe 100644 --- a/spring-social-login/src/main/java/com/baeldung/config/Application.java +++ b/spring-social-login/src/main/java/com/baeldung/config/Application.java @@ -3,7 +3,7 @@ package com.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.boot.web.support.SpringBootServletInitializer; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @SpringBootApplication diff --git a/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java b/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java index 3d3081fef9..152c7b229a 100644 --- a/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java +++ b/spring-social-login/src/main/java/com/baeldung/config/SecurityConfig.java @@ -1,8 +1,7 @@ package com.baeldung.config; -import com.baeldung.security.FacebookSignInAdapter; -import com.baeldung.security.FacebookConnectionSignup; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -14,22 +13,27 @@ import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.social.connect.ConnectionFactoryLocator; import org.springframework.social.connect.UsersConnectionRepository; import org.springframework.social.connect.mem.InMemoryUsersConnectionRepository; +import org.springframework.social.connect.support.ConnectionFactoryRegistry; import org.springframework.social.connect.web.ProviderSignInController; +import org.springframework.social.facebook.connect.FacebookConnectionFactory; + +import com.baeldung.security.FacebookConnectionSignup; +import com.baeldung.security.FacebookSignInAdapter; @Configuration @EnableWebSecurity @ComponentScan(basePackages = { "com.baeldung.security" }) public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Value("${spring.social.facebook.appSecret}") + String appSecret; + + @Value("${spring.social.facebook.appId}") + String appId; @Autowired private UserDetailsService userDetailsService; - @Autowired - private ConnectionFactoryLocator connectionFactoryLocator; - - @Autowired - private UsersConnectionRepository usersConnectionRepository; - @Autowired private FacebookConnectionSignup facebookConnectionSignup; @@ -55,7 +59,19 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean // @Primary public ProviderSignInController providerSignInController() { + ConnectionFactoryLocator connectionFactoryLocator = connectionFactoryLocator(); + UsersConnectionRepository usersConnectionRepository = getUsersConnectionRepository(connectionFactoryLocator); ((InMemoryUsersConnectionRepository) usersConnectionRepository).setConnectionSignUp(facebookConnectionSignup); return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new FacebookSignInAdapter()); } + + private ConnectionFactoryLocator connectionFactoryLocator() { + ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry(); + registry.addConnectionFactory(new FacebookConnectionFactory(appId, appSecret)); + return registry; + } + + private UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) { + return new InMemoryUsersConnectionRepository(connectionFactoryLocator); + } } \ No newline at end of file From 7e8d36d0840862273aca040356f5c04846b6b20d Mon Sep 17 00:00:00 2001 From: Cristian Rosu Date: Fri, 8 May 2020 20:17:17 +0300 Subject: [PATCH 66/91] BAEL-3826: test Thymeleaf PDF generation using ByteArrayOutputStream --- .../baeldung/pdf/PDFThymeleafUnitTest.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java diff --git a/pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java b/pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java new file mode 100644 index 0000000000..7d927072aa --- /dev/null +++ b/pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.pdf; + +import com.lowagie.text.DocumentException; +import org.junit.Test; +import org.thymeleaf.TemplateEngine; +import org.thymeleaf.context.Context; +import org.thymeleaf.templatemode.TemplateMode; +import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +import org.xhtmlrenderer.pdf.ITextRenderer; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import static org.junit.Assert.assertTrue; + +public class PDFThymeleafUnitTest { + + @Test + public void givenThymeleafTemplate_whenParsedAndRenderedToPDF_thenItShouldNotBeEmpty() throws DocumentException, IOException { + String html = parseThymeleafTemplate(); + ByteArrayOutputStream outputStream = generatePdfOutputStreamFromHtml(html); + assertTrue(outputStream.size() > 0); + } + + private ByteArrayOutputStream generatePdfOutputStreamFromHtml(String html) throws IOException, DocumentException { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + ITextRenderer renderer = new ITextRenderer(); + renderer.setDocumentFromString(html); + renderer.layout(); + renderer.createPDF(outputStream); + + outputStream.close(); + return outputStream; + } + + private String parseThymeleafTemplate() { + ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); + templateResolver.setSuffix(".html"); + templateResolver.setTemplateMode(TemplateMode.HTML); + + TemplateEngine templateEngine = new TemplateEngine(); + templateEngine.setTemplateResolver(templateResolver); + + Context context = new Context(); + context.setVariable("to", "Baeldung.com"); + + return templateEngine.process("thymeleaf_template", context); + } +} From f83c73a830814faee3411215dbaf5f82b8fcf278 Mon Sep 17 00:00:00 2001 From: Cristian Rosu Date: Fri, 8 May 2020 20:18:22 +0300 Subject: [PATCH 67/91] BAEL-3826: appropriate spacing --- pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java b/pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java index 7d927072aa..e253dce06c 100644 --- a/pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java +++ b/pdf/src/test/java/com/baeldung/pdf/PDFThymeleafUnitTest.java @@ -18,7 +18,9 @@ public class PDFThymeleafUnitTest { @Test public void givenThymeleafTemplate_whenParsedAndRenderedToPDF_thenItShouldNotBeEmpty() throws DocumentException, IOException { String html = parseThymeleafTemplate(); + ByteArrayOutputStream outputStream = generatePdfOutputStreamFromHtml(html); + assertTrue(outputStream.size() > 0); } From e1a6292ea60a390fdb983f961a8ac11ecd805bad Mon Sep 17 00:00:00 2001 From: "amit.pandey" Date: Sat, 9 May 2020 14:43:40 +0530 Subject: [PATCH 68/91] updated readme file --- spring-core-2/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-core-2/README.md b/spring-core-2/README.md index 6068e8c3c2..d9110f629d 100644 --- a/spring-core-2/README.md +++ b/spring-core-2/README.md @@ -14,5 +14,5 @@ This module contains articles about core Spring functionality - [Spring Events](https://www.baeldung.com/spring-events) - [Spring Null-Safety Annotations](https://www.baeldung.com/spring-null-safety-annotations) - [Using @Autowired in Abstract Classes](https://www.baeldung.com/spring-autowired-abstract-class) -- [Running Setup Data in Startup] (https://www.baeldung.com/running-setup-logic-on-startup-in-spring) +- [Running Setup Data in Startup](https://www.baeldung.com/running-setup-logic-on-startup-in-spring) - More articles: [[<-- prev]](/spring-core)[[next -->]](/spring-core-3) From 57a38967638dd32afa8871ba1508c107043cd530 Mon Sep 17 00:00:00 2001 From: Maiklins Date: Sat, 9 May 2020 14:00:25 +0200 Subject: [PATCH 69/91] Bael-3857 introduction to lock free data structures (#9238) * BAEL-3857 Introduction to Lock-Free Data Structures * BAEL-3857 Declare variables as final / volatile * BAEL-3857 Declare node value as final Co-authored-by: mikr --- .../baeldung/lockfree/NonBlockingQueue.java | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/lockfree/NonBlockingQueue.java diff --git a/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/lockfree/NonBlockingQueue.java b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/lockfree/NonBlockingQueue.java new file mode 100644 index 0000000000..9140dc287d --- /dev/null +++ b/core-java-modules/core-java-concurrency-advanced-3/src/main/java/com/baeldung/lockfree/NonBlockingQueue.java @@ -0,0 +1,81 @@ +package com.baeldung.lockfree; + +import java.util.NoSuchElementException; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +public class NonBlockingQueue { + + private final AtomicReference> head, tail; + private final AtomicInteger size; + + public NonBlockingQueue() { + head = new AtomicReference<>(null); + tail = new AtomicReference<>(null); + size = new AtomicInteger(); + size.set(0); + } + + public void add(T element) { + if (element == null) { + throw new NullPointerException(); + } + + Node node = new Node<>(element); + Node currentTail; + do { + currentTail = tail.get(); + node.setPrevious(currentTail); + } while(!tail.compareAndSet(currentTail, node)); + + if(node.previous != null) { + node.previous.next = node; + } + + head.compareAndSet(null, node); //if we are inserting the first element + size.incrementAndGet(); + } + + public T get() { + if(head.get() == null) { + throw new NoSuchElementException(); + } + + Node currentHead; + Node nextNode; + do { + currentHead = head.get(); + nextNode = currentHead.getNext(); + } while(!head.compareAndSet(currentHead, nextNode)); + + size.decrementAndGet(); + return currentHead.getValue(); + } + + public int size() { + return this.size.get(); + } + + private class Node { + private final T value; + private volatile Node next; + private volatile Node previous; + + public Node(T value) { + this.value = value; + this.next = null; + } + + public T getValue() { + return value; + } + + public Node getNext() { + return next; + } + + public void setPrevious(Node previous) { + this.previous = previous; + } + } +} From 8d41b96d0775c0cdb78fc0feaf40dbe78676e1b2 Mon Sep 17 00:00:00 2001 From: Anshul Bansal Date: Sat, 9 May 2020 15:30:54 +0300 Subject: [PATCH 70/91] corrected alphabetical order of modules --- spring-security-modules/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index 59dd75cbda..7ce33dd3e3 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -30,8 +30,8 @@ spring-security-mvc-login spring-security-mvc-persisted-remember-me spring-security-mvc-socket - spring-security-okta spring-security-oidc + spring-security-okta spring-security-react spring-security-rest spring-security-rest-basic-auth From af387990c86b52957874329517a3e8daebf90dc9 Mon Sep 17 00:00:00 2001 From: Cicio Flaviu Date: Sun, 10 May 2020 08:43:51 +0300 Subject: [PATCH 71/91] BAEL-3849 Implemented example code for comparing Transactional. (#9261) --- .../TransactionalCompareApplication.java | 12 ++++ .../spring/transactional/entity/Car.java | 60 +++++++++++++++++++ .../repository/CarRepository.java | 7 +++ .../transactional/service/CarService.java | 25 ++++++++ .../transactional/service/RentalService.java | 22 +++++++ 5 files changed, 126 insertions(+) create mode 100644 persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java create mode 100644 persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java create mode 100644 persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java create mode 100644 persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java create mode 100644 persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java new file mode 100644 index 0000000000..7fee55be8a --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/TransactionalCompareApplication.java @@ -0,0 +1,12 @@ +package com.baeldung.spring.transactional; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +class TransactionalCompareApplication { + + public static void main(String[] args) { + SpringApplication.run(TransactionalCompareApplication.class, args); + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java new file mode 100644 index 0000000000..1219111ffa --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/entity/Car.java @@ -0,0 +1,60 @@ +package com.baeldung.spring.transactional.entity; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Car { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String make; + + private String model; + + public Car() { + } + + public Car(Long id, String make, String model) { + this.id = id; + this.make = make; + this.model = model; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getMake() { + return make; + } + + public void setMake(String make) { + this.make = make; + } + + public String getModel() { + return model; + } + + public void setModel(String model) { + this.model = model; + } + + @Override + public String toString() { + return "Car{" + + "id=" + id + + ", make='" + make + '\'' + + ", model='" + model + '\'' + + '}'; + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java new file mode 100644 index 0000000000..f8ecc8f550 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/repository/CarRepository.java @@ -0,0 +1,7 @@ +package com.baeldung.spring.transactional.repository; + +import com.baeldung.spring.transactional.entity.Car; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface CarRepository extends JpaRepository { +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java new file mode 100644 index 0000000000..0821ddb02b --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/CarService.java @@ -0,0 +1,25 @@ +package com.baeldung.spring.transactional.service; + +import com.baeldung.spring.transactional.entity.Car; +import com.baeldung.spring.transactional.repository.CarRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Isolation; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityExistsException; + +@Service +@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.SUPPORTS, readOnly = false, timeout = 30) +public class CarService { + + @Autowired + private CarRepository carRepository; + + @Transactional(rollbackFor = IllegalArgumentException.class, noRollbackFor = EntityExistsException.class, + rollbackForClassName = "IllegalArgumentException", noRollbackForClassName = "EntityExistsException") + public Car save(Car car) { + return carRepository.save(car); + } +} diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java new file mode 100644 index 0000000000..0aa0815a98 --- /dev/null +++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/transactional/service/RentalService.java @@ -0,0 +1,22 @@ +package com.baeldung.spring.transactional.service; + +import com.baeldung.spring.transactional.entity.Car; +import com.baeldung.spring.transactional.repository.CarRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.persistence.EntityExistsException; +import javax.transaction.Transactional; + +@Service +@Transactional(Transactional.TxType.SUPPORTS) +public class RentalService { + + @Autowired + private CarRepository carRepository; + + @Transactional(rollbackOn = IllegalArgumentException.class, dontRollbackOn = EntityExistsException.class) + public Car rent(Car car) { + return carRepository.save(car); + } +} From 8e5456b24bced301812c4129a9bed6eee7a574f9 Mon Sep 17 00:00:00 2001 From: Mona Mohamadinia Date: Sun, 10 May 2020 13:34:01 +0430 Subject: [PATCH 72/91] Added The Sample Codes for Lateinit Initialization (#9253) --- .../com/baeldung/late/LateInitUnitTest.kt | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/late/LateInitUnitTest.kt diff --git a/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/late/LateInitUnitTest.kt b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/late/LateInitUnitTest.kt new file mode 100644 index 0000000000..c99e438742 --- /dev/null +++ b/core-kotlin-modules/core-kotlin-lang-2/src/test/kotlin/com/baeldung/late/LateInitUnitTest.kt @@ -0,0 +1,22 @@ +package com.baeldung.late + +import org.junit.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class LateInitUnitTest { + + private lateinit var answer: String + + @Test(expected = UninitializedPropertyAccessException::class) + fun givenLateInit_WhenNotInitialized_ShouldThrowAnException() { + answer.length + } + + @Test + fun givenLateInit_TheIsInitialized_ReturnsTheInitializationStatus() { + assertFalse { this::answer.isInitialized } + answer = "42" + assertTrue { this::answer.isInitialized } + } +} From 5c90dbc963995c23ca155cbf87100224804627cb Mon Sep 17 00:00:00 2001 From: Somnath Musib <7885767+musibs@users.noreply.github.com> Date: Mon, 11 May 2020 00:14:53 +1000 Subject: [PATCH 73/91] BAEL-3852 - A Guide to Foreign Memory Access API in Java 14 (#9040) * Code sample for Java Hexagonal architecture * BAEL-3838 Capturing a Java Thread Dump * BAEL-3852 Foreign memory api in Java * BAEL-3852 - Review changes of A Guide to Foreign Memory Access API in Java 14 * BAEL-3852 - Additional review changes for A Guide to Foreign Memory Access API in Java 14 * Review changes for alignment and class removal * Removed incorrectly added old files from the PR * Indentation changes Co-authored-by: Somnath Musib --- .../foreign/api/ForeignMemoryUnitTest.java | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java diff --git a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java new file mode 100644 index 0000000000..b2264f30e6 --- /dev/null +++ b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/foreign/api/ForeignMemoryUnitTest.java @@ -0,0 +1,84 @@ +package com.baeldung.java14.foreign.api; + +import jdk.incubator.foreign.*; +import org.junit.Test; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +import java.lang.invoke.VarHandle; +import java.nio.ByteOrder; + +public class ForeignMemoryUnitTest { + + @Test + public void whenAValueIsSet_thenAccessTheValue() { + long value = 10; + MemoryAddress memoryAddress = + MemorySegment.allocateNative(8).baseAddress(); + VarHandle varHandle = MemoryHandles.varHandle(long.class, + ByteOrder.nativeOrder()); + varHandle.set(memoryAddress, value); + assertThat(varHandle.get(memoryAddress), is(value)); + } + + @Test + public void whenMultipleValuesAreSet_thenAccessAll() { + VarHandle varHandle = MemoryHandles.varHandle(int.class, + ByteOrder.nativeOrder()); + + try(MemorySegment memorySegment = + MemorySegment.allocateNative(100)) { + MemoryAddress base = memorySegment.baseAddress(); + for(int i=0; i<25; i++) { + varHandle.set(base.addOffset((i*4)), i); + } + for(int i=0; i<25; i++) { + assertThat(varHandle.get(base.addOffset((i*4))), is(i)); + } + } + } + + @Test + public void whenSetValuesWithMemoryLayout_thenTheyCanBeRetrieved() { + SequenceLayout sequenceLayout = + MemoryLayout.ofSequence(25, + MemoryLayout.ofValueBits(64, ByteOrder.nativeOrder())); + VarHandle varHandle = + sequenceLayout.varHandle(long.class, + MemoryLayout.PathElement.sequenceElement()); + + try(MemorySegment memorySegment = + MemorySegment.allocateNative(sequenceLayout)) { + MemoryAddress base = memorySegment.baseAddress(); + for(long i=0; i Date: Mon, 11 May 2020 08:28:13 -0400 Subject: [PATCH 74/91] Bael-3893 - Fixed string concatenation operator --- .../AwsAppSyncApplicationTests.java | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java index 6e94651789..22d99959b3 100644 --- a/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java +++ b/aws-app-sync/src/test/java/com/baeldung/awsappsync/AwsAppSyncApplicationTests.java @@ -16,17 +16,17 @@ class AwsAppSyncApplicationTests { void givenGraphQuery_whenListEvents_thenReturnAllEvents() { Map requestBody = new HashMap<>(); - requestBody.put("query", "query ListEvents {" + - " listEvents {" + - " items {" + - " id" + - " name" + - " where" + - " when" + - " description" + - " }" + - " }" + - "}"); + requestBody.put("query", "query ListEvents {" + + " listEvents {" + + " items {" + + " id" + + " name" + + " where" + + " when" + + " description" + + " }" + + " }" + + "}"); requestBody.put("variables", ""); requestBody.put("operationName", "ListEvents"); @@ -42,18 +42,18 @@ class AwsAppSyncApplicationTests { @Test void givenGraphAdd_whenMutation_thenReturnIdNameDesc() { - String queryString = "mutation add {" + - " createEvent(" + - " name:\"My added GraphQL event\"" + - " where:\"Day 2\"" + - " when:\"Saturday night\"" + - " description:\"Studying GraphQL\"" + - " ){" + - " id" + - " name" + - " description" + - " }" + - "}"; + String queryString = "mutation add {" + + " createEvent(" + + " name:\"My added GraphQL event\"" + + " where:\"Day 2\"" + + " when:\"Saturday night\"" + + " description:\"Studying GraphQL\"" + + " ){" + + " id" + + " name" + + " description" + + " }" + + "}"; Map requestBody = new HashMap<>(); requestBody.put("query", queryString); From 699e94fdb64af3fc6ad6afb32f71f90fe0fbe9f1 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 11 May 2020 18:54:07 +0530 Subject: [PATCH 75/91] JAVA-952: Migrate spring-session to parent-boot-2 --- spring-session/pom.xml | 4 ++-- spring-session/spring-session-redis/pom.xml | 11 ++++++++--- .../baeldung/spring/session/SecurityConfig.java | 14 +++++++++++--- .../session/SessionControllerIntegrationTest.java | 2 +- 4 files changed, 22 insertions(+), 9 deletions(-) diff --git a/spring-session/pom.xml b/spring-session/pom.xml index 42a414afdc..8388efb6c3 100644 --- a/spring-session/pom.xml +++ b/spring-session/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 diff --git a/spring-session/spring-session-redis/pom.xml b/spring-session/spring-session-redis/pom.xml index 37402634b0..8d225e06ed 100644 --- a/spring-session/spring-session-redis/pom.xml +++ b/spring-session/spring-session-redis/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-boot-1 + ../../parent-boot-2 @@ -25,7 +25,7 @@ org.springframework.session - spring-session + spring-session-data-redis org.springframework.boot @@ -36,6 +36,11 @@ embedded-redis ${embedded-redis.version} + + redis.clients + jedis + jar + diff --git a/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java b/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java index 1da6d9422d..678c98e7eb 100644 --- a/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java +++ b/spring-session/spring-session-redis/src/main/java/com/baeldung/spring/session/SecurityConfig.java @@ -1,23 +1,31 @@ package com.baeldung.spring.session; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { - + @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication().withUser("admin").password("password").roles("ADMIN"); + auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("password")).roles("ADMIN"); } - + @Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic().and().authorizeRequests().antMatchers("/").hasRole("ADMIN").anyRequest().authenticated(); } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } } diff --git a/spring-session/spring-session-redis/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java b/spring-session/spring-session-redis/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java index 7ee0294315..065533c73f 100644 --- a/spring-session/spring-session-redis/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java +++ b/spring-session/spring-session-redis/src/test/java/com/baeldung/spring/session/SessionControllerIntegrationTest.java @@ -5,7 +5,7 @@ import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; From 9d2e94f5290187f3a48faa34d4363a25a49a951c Mon Sep 17 00:00:00 2001 From: Justin Albano Date: Mon, 11 May 2020 11:47:04 -0400 Subject: [PATCH 76/91] BAEL-3951: Added JDK 14 record example and associated tests. (#9270) --- .../com/baeldung/java14/record/Person.java | 22 +++ .../baeldung/java14/record/PersonTest.java | 150 ++++++++++++++++++ 2 files changed, 172 insertions(+) create mode 100644 core-java-modules/core-java-14/src/main/java/com/baeldung/java14/record/Person.java create mode 100644 core-java-modules/core-java-14/src/test/java/com/baeldung/java14/record/PersonTest.java diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/record/Person.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/record/Person.java new file mode 100644 index 0000000000..33243c4ecf --- /dev/null +++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/record/Person.java @@ -0,0 +1,22 @@ +package com.baeldung.java14.record; + +import java.util.Objects; + +public record Person (String name, String address) { + + public static String UNKWOWN_ADDRESS = "Unknown"; + public static String UNNAMED = "Unnamed"; + + public Person { + Objects.requireNonNull(name); + Objects.requireNonNull(address); + } + + public Person(String name) { + this(name, UNKWOWN_ADDRESS); + } + + public static Person unnamed(String address) { + return new Person(UNNAMED, address); + } +} diff --git a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/record/PersonTest.java b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/record/PersonTest.java new file mode 100644 index 0000000000..4a7d4ede5f --- /dev/null +++ b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/record/PersonTest.java @@ -0,0 +1,150 @@ +package com.baeldung.java14.record; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class PersonTest { + + @Test + public void givenSameNameAndAddress_whenEquals_thenPersonsEqual() { + + String name = "John Doe"; + String address = "100 Linda Ln."; + + Person person1 = new Person(name, address); + Person person2 = new Person(name, address); + + assertTrue(person1.equals(person2)); + } + + @Test + public void givenDifferentObject_whenEquals_thenNotEqual() { + + Person person = new Person("John Doe", "100 Linda Ln."); + + assertFalse(person.equals(new Object())); + } + + @Test + public void givenDifferentName_whenEquals_thenPersonsNotEqual() { + + String address = "100 Linda Ln."; + + Person person1 = new Person("Jane Doe", address); + Person person2 = new Person("John Doe", address); + + assertFalse(person1.equals(person2)); + } + + @Test + public void givenDifferentAddress_whenEquals_thenPersonsNotEqual() { + + String name = "John Doe"; + + Person person1 = new Person(name, "100 Linda Ln."); + Person person2 = new Person(name, "200 London Ave."); + + assertFalse(person1.equals(person2)); + } + + @Test + public void givenSameNameAndAddress_whenHashCode_thenPersonsEqual() { + + String name = "John Doe"; + String address = "100 Linda Ln."; + + Person person1 = new Person(name, address); + Person person2 = new Person(name, address); + + assertEquals(person1.hashCode(), person2.hashCode()); + } + + @Test + public void givenDifferentObject_whenHashCode_thenNotEqual() { + + Person person = new Person("John Doe", "100 Linda Ln."); + + assertNotEquals(person.hashCode(), new Object().hashCode()); + } + + @Test + public void givenDifferentName_whenHashCode_thenPersonsNotEqual() { + + String address = "100 Linda Ln."; + + Person person1 = new Person("Jane Doe", address); + Person person2 = new Person("John Doe", address); + + assertNotEquals(person1.hashCode(), person2.hashCode()); + } + + @Test + public void givenDifferentAddress_whenHashCode_thenPersonsNotEqual() { + + String name = "John Doe"; + + Person person1 = new Person(name, "100 Linda Ln."); + Person person2 = new Person(name, "200 London Ave."); + + assertNotEquals(person1.hashCode(), person2.hashCode()); + } + + @Test + public void givenValidNameAndAddress_whenGetNameAndAddress_thenExpectedValuesReturned() { + + String name = "John Doe"; + String address = "100 Linda Ln."; + + Person person = new Person(name, address); + + assertEquals(name, person.name()); + assertEquals(address, person.address()); + } + + @Test + public void givenValidNameAndAddress_whenToString_thenCorrectStringReturned() { + + String name = "John Doe"; + String address = "100 Linda Ln."; + + Person person = new Person(name, address); + + assertEquals("Person[name=" + name + ", address=" + address + "]", person.toString()); + } + + @Test(expected = NullPointerException.class) + public void givenNullName_whenConstruct_thenErrorThrown() { + new Person(null, "100 Linda Ln."); + } + + @Test(expected = NullPointerException.class) + public void givenNullAddress_whenConstruct_thenErrorThrown() { + new Person("John Doe", null); + } + + @Test + public void givenUnknownAddress_whenConstructing_thenAddressPopulated() { + + String name = "John Doe"; + + Person person = new Person(name); + + assertEquals(name, person.name()); + assertEquals(Person.UNKWOWN_ADDRESS, person.address()); + } + + @Test + public void givenUnnamed_whenConstructingThroughFactory_thenNamePopulated() { + + String address = "100 Linda Ln."; + + Person person = Person.unnamed(address); + + assertEquals(Person.UNNAMED, person.name()); + assertEquals(address, person.address()); + } +} From 22f622521ff1c0565438f5ef0cb61d400c9cb0ba Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Tue, 12 May 2020 12:34:28 +0530 Subject: [PATCH 77/91] JAVA-945: Migrate spring-rest-hal-browser to parent-boot-2 --- spring-rest-hal-browser/pom.xml | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/spring-rest-hal-browser/pom.xml b/spring-rest-hal-browser/pom.xml index adef8bf2b0..32a0b52875 100644 --- a/spring-rest-hal-browser/pom.xml +++ b/spring-rest-hal-browser/pom.xml @@ -9,9 +9,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -19,25 +19,26 @@ org.springframework.boot spring-boot-starter-web - ${spring-boot.version} org.springframework.boot spring-boot-starter-data-jpa - ${spring-boot.version} org.springframework.data spring-data-rest-hal-browser - ${spring-data.version} com.h2database h2 - ${h2.version} + + + net.bytebuddy + byte-buddy-dep + ${bytebuddy.version} @@ -55,9 +56,7 @@ - 2.0.3.RELEASE - 3.0.8.RELEASE - 1.4.197 + 1.10.10 1.8 1.8 From 20843c7f224fe68e772b0518532c881fff483483 Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Fri, 24 Apr 2020 01:56:25 +0200 Subject: [PATCH 78/91] BAEL-3863 Introduction to Finagle --- finagle/README.md | 7 +++++ finagle/pom.xml | 30 +++++++++++++++++++ .../java/com/baeldung/finagle/Client.java | 24 +++++++++++++++ .../com/baeldung/finagle/GreetingService.java | 18 +++++++++++ .../java/com/baeldung/finagle/LogFilter.java | 17 +++++++++++ .../java/com/baeldung/finagle/Server.java | 15 ++++++++++ finagle/src/main/resources/logback.xml | 13 ++++++++ .../src/main/resources/twitter4j.properties | 4 +++ 8 files changed, 128 insertions(+) create mode 100644 finagle/README.md create mode 100644 finagle/pom.xml create mode 100644 finagle/src/main/java/com/baeldung/finagle/Client.java create mode 100644 finagle/src/main/java/com/baeldung/finagle/GreetingService.java create mode 100644 finagle/src/main/java/com/baeldung/finagle/LogFilter.java create mode 100644 finagle/src/main/java/com/baeldung/finagle/Server.java create mode 100644 finagle/src/main/resources/logback.xml create mode 100644 finagle/src/main/resources/twitter4j.properties diff --git a/finagle/README.md b/finagle/README.md new file mode 100644 index 0000000000..d16afdc10d --- /dev/null +++ b/finagle/README.md @@ -0,0 +1,7 @@ +## Finagle + +This module contains articles about Finagle and associated libraries. + +### Relevant articles + +- [Introduction to Finagle](https://www.baeldung.com/introduction-to-finagle) diff --git a/finagle/pom.xml b/finagle/pom.xml new file mode 100644 index 0000000000..f1dc932c13 --- /dev/null +++ b/finagle/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + Finagle + Finagle + jar + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + com.twitter + finagle-core_2.13 + 20.4.0 + + + com.twitter + finagle-http_2.13 + 20.4.0 + + + + + + diff --git a/finagle/src/main/java/com/baeldung/finagle/Client.java b/finagle/src/main/java/com/baeldung/finagle/Client.java new file mode 100644 index 0000000000..a881f1c37c --- /dev/null +++ b/finagle/src/main/java/com/baeldung/finagle/Client.java @@ -0,0 +1,24 @@ +package com.baeldung.finagle; + +import com.twitter.finagle.Http; +import com.twitter.finagle.Service; +import com.twitter.finagle.http.Method; +import com.twitter.finagle.http.Request; +import com.twitter.finagle.http.Response; +import com.twitter.util.Await; +import com.twitter.util.Future; +import scala.runtime.BoxedUnit; + +public class Client { + public static void main(String[] args) throws Exception { + Service service = new LogFilter().andThen(Http.newService(":8080")); + Request request = Request.apply(Method.Get(), "/?name=John"); + request.host("localhost"); + Future response = service.apply(request); + Await.result(response + .onSuccess(r -> { + System.out.println(r.getContentString()); + return BoxedUnit.UNIT; + })); + } +} diff --git a/finagle/src/main/java/com/baeldung/finagle/GreetingService.java b/finagle/src/main/java/com/baeldung/finagle/GreetingService.java new file mode 100644 index 0000000000..c795724192 --- /dev/null +++ b/finagle/src/main/java/com/baeldung/finagle/GreetingService.java @@ -0,0 +1,18 @@ +package com.baeldung.finagle; + +import com.twitter.finagle.Service; +import com.twitter.finagle.http.Request; +import com.twitter.finagle.http.Response; +import com.twitter.finagle.http.Status; +import com.twitter.io.Buf; +import com.twitter.io.Reader; +import com.twitter.util.Future; + +public class GreetingService extends Service { + @Override + public Future apply(Request request) { + String greeting = "Hello " + request.getParam("name"); + Reader reader = Reader.fromBuf(new Buf.ByteArray(greeting.getBytes(), 0, greeting.length())); + return Future.value(Response.apply(request.version(), Status.Ok(), reader)); + } +} diff --git a/finagle/src/main/java/com/baeldung/finagle/LogFilter.java b/finagle/src/main/java/com/baeldung/finagle/LogFilter.java new file mode 100644 index 0000000000..d381456cfe --- /dev/null +++ b/finagle/src/main/java/com/baeldung/finagle/LogFilter.java @@ -0,0 +1,17 @@ +package com.baeldung.finagle; + +import com.twitter.finagle.Service; +import com.twitter.finagle.SimpleFilter; +import com.twitter.finagle.http.Request; +import com.twitter.finagle.http.Response; +import com.twitter.util.Future; + +public class LogFilter extends SimpleFilter { + @Override + public Future apply(Request request, Service service) { + System.out.println("Request host:" + request.host().getOrElse(() -> "")); + System.out.println("Request params:"); + request.getParams().forEach(entry -> System.out.println("\t" + entry.getKey() + " : " + entry.getValue())); + return service.apply(request); + } +} diff --git a/finagle/src/main/java/com/baeldung/finagle/Server.java b/finagle/src/main/java/com/baeldung/finagle/Server.java new file mode 100644 index 0000000000..8a9c9be192 --- /dev/null +++ b/finagle/src/main/java/com/baeldung/finagle/Server.java @@ -0,0 +1,15 @@ +package com.baeldung.finagle; + +import com.twitter.finagle.Http; +import com.twitter.finagle.ListeningServer; +import com.twitter.finagle.Service; +import com.twitter.util.Await; +import com.twitter.util.TimeoutException; + +public class Server { + public static void main(String[] args) throws TimeoutException, InterruptedException { + Service service = new LogFilter().andThen(new GreetingService()); + ListeningServer server = Http.serve(":8080", service); + Await.ready(server); + } +} diff --git a/finagle/src/main/resources/logback.xml b/finagle/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/finagle/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/finagle/src/main/resources/twitter4j.properties b/finagle/src/main/resources/twitter4j.properties new file mode 100644 index 0000000000..ee11dc62a1 --- /dev/null +++ b/finagle/src/main/resources/twitter4j.properties @@ -0,0 +1,4 @@ +oauth.consumerKey=//TODO +oauth.consumerSecret=//TODO +oauth.accessToken=//TODO +oauth.accessTokenSecret=//TODO From 33edef47e18c16e03ce056af609dc984d6f4a566 Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Fri, 24 Apr 2020 02:05:49 +0200 Subject: [PATCH 79/91] BAEL-3863 add Finagle module to root pom.xml --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index 34703c6f73..813a42c93d 100644 --- a/pom.xml +++ b/pom.xml @@ -418,6 +418,7 @@ ethereum feign + finagle flyway-cdi-extension geotools From ff684f13b6d4d27f063d0e912ca9e6b0151acb0e Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Fri, 24 Apr 2020 20:52:23 +0200 Subject: [PATCH 80/91] BAEL-3863 moved Finagle package to libraries-rpc, added test --- {finagle => libraries-rpc}/README.md | 0 {finagle => libraries-rpc}/pom.xml | 4 +- .../com/baeldung/rpc}/finagle/Client.java | 2 +- .../rpc}/finagle/GreetingService.java | 2 +- .../com/baeldung/rpc}/finagle/LogFilter.java | 2 +- .../com/baeldung/rpc}/finagle/Server.java | 2 +- .../src/main/resources/logback.xml | 0 .../src/main/resources/twitter4j.properties | 0 .../rpc/finagle/ClientServerTest.java | 40 +++++++++++++++++++ pom.xml | 2 +- 10 files changed, 47 insertions(+), 7 deletions(-) rename {finagle => libraries-rpc}/README.md (100%) rename {finagle => libraries-rpc}/pom.xml (92%) rename {finagle/src/main/java/com/baeldung => libraries-rpc/src/main/java/com/baeldung/rpc}/finagle/Client.java (96%) rename {finagle/src/main/java/com/baeldung => libraries-rpc/src/main/java/com/baeldung/rpc}/finagle/GreetingService.java (95%) rename {finagle/src/main/java/com/baeldung => libraries-rpc/src/main/java/com/baeldung/rpc}/finagle/LogFilter.java (95%) rename {finagle/src/main/java/com/baeldung => libraries-rpc/src/main/java/com/baeldung/rpc}/finagle/Server.java (93%) rename {finagle => libraries-rpc}/src/main/resources/logback.xml (100%) rename {finagle => libraries-rpc}/src/main/resources/twitter4j.properties (100%) create mode 100644 libraries-rpc/src/test/java/com/baeldung/rpc/finagle/ClientServerTest.java diff --git a/finagle/README.md b/libraries-rpc/README.md similarity index 100% rename from finagle/README.md rename to libraries-rpc/README.md diff --git a/finagle/pom.xml b/libraries-rpc/pom.xml similarity index 92% rename from finagle/pom.xml rename to libraries-rpc/pom.xml index f1dc932c13..145693cac1 100644 --- a/finagle/pom.xml +++ b/libraries-rpc/pom.xml @@ -2,8 +2,8 @@ 4.0.0 - Finagle - Finagle + libraries-rpc + libraries-rpc jar diff --git a/finagle/src/main/java/com/baeldung/finagle/Client.java b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Client.java similarity index 96% rename from finagle/src/main/java/com/baeldung/finagle/Client.java rename to libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Client.java index a881f1c37c..989c79f302 100644 --- a/finagle/src/main/java/com/baeldung/finagle/Client.java +++ b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Client.java @@ -1,4 +1,4 @@ -package com.baeldung.finagle; +package com.baeldung.rpc.finagle; import com.twitter.finagle.Http; import com.twitter.finagle.Service; diff --git a/finagle/src/main/java/com/baeldung/finagle/GreetingService.java b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/GreetingService.java similarity index 95% rename from finagle/src/main/java/com/baeldung/finagle/GreetingService.java rename to libraries-rpc/src/main/java/com/baeldung/rpc/finagle/GreetingService.java index c795724192..7f3d741f94 100644 --- a/finagle/src/main/java/com/baeldung/finagle/GreetingService.java +++ b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/GreetingService.java @@ -1,4 +1,4 @@ -package com.baeldung.finagle; +package com.baeldung.rpc.finagle; import com.twitter.finagle.Service; import com.twitter.finagle.http.Request; diff --git a/finagle/src/main/java/com/baeldung/finagle/LogFilter.java b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/LogFilter.java similarity index 95% rename from finagle/src/main/java/com/baeldung/finagle/LogFilter.java rename to libraries-rpc/src/main/java/com/baeldung/rpc/finagle/LogFilter.java index d381456cfe..3ef57ed18f 100644 --- a/finagle/src/main/java/com/baeldung/finagle/LogFilter.java +++ b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/LogFilter.java @@ -1,4 +1,4 @@ -package com.baeldung.finagle; +package com.baeldung.rpc.finagle; import com.twitter.finagle.Service; import com.twitter.finagle.SimpleFilter; diff --git a/finagle/src/main/java/com/baeldung/finagle/Server.java b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Server.java similarity index 93% rename from finagle/src/main/java/com/baeldung/finagle/Server.java rename to libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Server.java index 8a9c9be192..5bc8d93eaf 100644 --- a/finagle/src/main/java/com/baeldung/finagle/Server.java +++ b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Server.java @@ -1,4 +1,4 @@ -package com.baeldung.finagle; +package com.baeldung.rpc.finagle; import com.twitter.finagle.Http; import com.twitter.finagle.ListeningServer; diff --git a/finagle/src/main/resources/logback.xml b/libraries-rpc/src/main/resources/logback.xml similarity index 100% rename from finagle/src/main/resources/logback.xml rename to libraries-rpc/src/main/resources/logback.xml diff --git a/finagle/src/main/resources/twitter4j.properties b/libraries-rpc/src/main/resources/twitter4j.properties similarity index 100% rename from finagle/src/main/resources/twitter4j.properties rename to libraries-rpc/src/main/resources/twitter4j.properties diff --git a/libraries-rpc/src/test/java/com/baeldung/rpc/finagle/ClientServerTest.java b/libraries-rpc/src/test/java/com/baeldung/rpc/finagle/ClientServerTest.java new file mode 100644 index 0000000000..b3faa1968c --- /dev/null +++ b/libraries-rpc/src/test/java/com/baeldung/rpc/finagle/ClientServerTest.java @@ -0,0 +1,40 @@ +package com.baeldung.rpc.finagle; + +import com.twitter.finagle.Http; +import com.twitter.finagle.Service; +import com.twitter.finagle.http.Method; +import com.twitter.finagle.http.Request; +import com.twitter.finagle.http.Response; +import com.twitter.util.Await; +import com.twitter.util.Future; +import org.junit.Test; +import scala.runtime.BoxedUnit; + +import static org.junit.Assert.assertEquals; + +public class ClientServerTest { + @Test + public void clientShouldReceiveResponseFromServer() throws Exception { + // given + Service serverService = new LogFilter().andThen(new GreetingService()); + Http.serve(":8080", serverService); + + Service clientService = new LogFilter().andThen(Http.newService(":8080")); + + // when + Request request = Request.apply(Method.Get(), "/?name=John"); + request.host("localhost"); + Future response = clientService.apply(request); + + // then + Await.result(response + .onSuccess(r -> { + assertEquals("Hello John", r.getContentString()); + return BoxedUnit.UNIT; + }) + .onFailure(r -> { + throw new RuntimeException(r); + }) + ); + } +} diff --git a/pom.xml b/pom.xml index 813a42c93d..c16775bfc9 100644 --- a/pom.xml +++ b/pom.xml @@ -418,7 +418,6 @@ ethereum feign - finagle flyway-cdi-extension geotools @@ -509,6 +508,7 @@ libraries-http-2 libraries-io libraries-primitive + libraries-rpc libraries-security libraries-server libraries-testing From 3e0c3a0d0a621a3dcf909314fffb5a25b3a17a93 Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Fri, 24 Apr 2020 20:54:23 +0200 Subject: [PATCH 81/91] BAEL-3863 removed README.md --- libraries-rpc/README.md | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 libraries-rpc/README.md diff --git a/libraries-rpc/README.md b/libraries-rpc/README.md deleted file mode 100644 index d16afdc10d..0000000000 --- a/libraries-rpc/README.md +++ /dev/null @@ -1,7 +0,0 @@ -## Finagle - -This module contains articles about Finagle and associated libraries. - -### Relevant articles - -- [Introduction to Finagle](https://www.baeldung.com/introduction-to-finagle) From ca7d40de8fdca6741021f8273613a8ee53f7c907 Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Fri, 24 Apr 2020 20:59:20 +0200 Subject: [PATCH 82/91] BAEL-3863 removed redundant examples --- .../java/com/baeldung/rpc/finagle/Client.java | 24 ------------------- .../java/com/baeldung/rpc/finagle/Server.java | 15 ------------ 2 files changed, 39 deletions(-) delete mode 100644 libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Client.java delete mode 100644 libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Server.java diff --git a/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Client.java b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Client.java deleted file mode 100644 index 989c79f302..0000000000 --- a/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Client.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.baeldung.rpc.finagle; - -import com.twitter.finagle.Http; -import com.twitter.finagle.Service; -import com.twitter.finagle.http.Method; -import com.twitter.finagle.http.Request; -import com.twitter.finagle.http.Response; -import com.twitter.util.Await; -import com.twitter.util.Future; -import scala.runtime.BoxedUnit; - -public class Client { - public static void main(String[] args) throws Exception { - Service service = new LogFilter().andThen(Http.newService(":8080")); - Request request = Request.apply(Method.Get(), "/?name=John"); - request.host("localhost"); - Future response = service.apply(request); - Await.result(response - .onSuccess(r -> { - System.out.println(r.getContentString()); - return BoxedUnit.UNIT; - })); - } -} diff --git a/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Server.java b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Server.java deleted file mode 100644 index 5bc8d93eaf..0000000000 --- a/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/Server.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.baeldung.rpc.finagle; - -import com.twitter.finagle.Http; -import com.twitter.finagle.ListeningServer; -import com.twitter.finagle.Service; -import com.twitter.util.Await; -import com.twitter.util.TimeoutException; - -public class Server { - public static void main(String[] args) throws TimeoutException, InterruptedException { - Service service = new LogFilter().andThen(new GreetingService()); - ListeningServer server = Http.serve(":8080", service); - Await.ready(server); - } -} From cf6cbe92b9e229c28a354d683d6a3cb6a2d8eb3a Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Sat, 25 Apr 2020 18:07:27 +0200 Subject: [PATCH 83/91] BAEL-3863 Renamed tests to follow convention --- .../{ClientServerTest.java => FinagleIntegrationTest.java} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename libraries-rpc/src/test/java/com/baeldung/rpc/finagle/{ClientServerTest.java => FinagleIntegrationTest.java} (88%) diff --git a/libraries-rpc/src/test/java/com/baeldung/rpc/finagle/ClientServerTest.java b/libraries-rpc/src/test/java/com/baeldung/rpc/finagle/FinagleIntegrationTest.java similarity index 88% rename from libraries-rpc/src/test/java/com/baeldung/rpc/finagle/ClientServerTest.java rename to libraries-rpc/src/test/java/com/baeldung/rpc/finagle/FinagleIntegrationTest.java index b3faa1968c..8dcdb19e7e 100644 --- a/libraries-rpc/src/test/java/com/baeldung/rpc/finagle/ClientServerTest.java +++ b/libraries-rpc/src/test/java/com/baeldung/rpc/finagle/FinagleIntegrationTest.java @@ -12,9 +12,9 @@ import scala.runtime.BoxedUnit; import static org.junit.Assert.assertEquals; -public class ClientServerTest { +public class FinagleIntegrationTest { @Test - public void clientShouldReceiveResponseFromServer() throws Exception { + public void givenServerAndClient_whenRequestSent_thenClientShouldReceiveResponseFromServer() throws Exception { // given Service serverService = new LogFilter().andThen(new GreetingService()); Http.serve(":8080", serverService); From 6deafc178d25d2b6247074bf02249349591dba4c Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Sun, 26 Apr 2020 16:15:17 +0200 Subject: [PATCH 84/91] BAEL-3863 replace stdouts with logger --- .../main/java/com/baeldung/rpc/finagle/LogFilter.java | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/LogFilter.java b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/LogFilter.java index 3ef57ed18f..7fc5440016 100644 --- a/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/LogFilter.java +++ b/libraries-rpc/src/main/java/com/baeldung/rpc/finagle/LogFilter.java @@ -5,13 +5,18 @@ import com.twitter.finagle.SimpleFilter; import com.twitter.finagle.http.Request; import com.twitter.finagle.http.Response; import com.twitter.util.Future; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class LogFilter extends SimpleFilter { + + private static final Logger logger = LoggerFactory.getLogger(LogFilter.class); + @Override public Future apply(Request request, Service service) { - System.out.println("Request host:" + request.host().getOrElse(() -> "")); - System.out.println("Request params:"); - request.getParams().forEach(entry -> System.out.println("\t" + entry.getKey() + " : " + entry.getValue())); + logger.info("Request host:" + request.host().getOrElse(() -> "")); + logger.info("Request params:"); + request.getParams().forEach(entry -> logger.info("\t" + entry.getKey() + " : " + entry.getValue())); return service.apply(request); } } From 7da38b99cb4d8f4d02ef4eac8efc4143433671d6 Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Sun, 26 Apr 2020 16:25:51 +0200 Subject: [PATCH 85/91] BAEL-3863 add versions properties --- libraries-rpc/pom.xml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/libraries-rpc/pom.xml b/libraries-rpc/pom.xml index 145693cac1..8741a41062 100644 --- a/libraries-rpc/pom.xml +++ b/libraries-rpc/pom.xml @@ -16,15 +16,20 @@ com.twitter finagle-core_2.13 - 20.4.0 + ${finagle.core.version} com.twitter finagle-http_2.13 - 20.4.0 + ${finagle.http.version} + + 20.4.0 + 20.4.0 + + From 6709017cc02040e210265e91a9792fdc405d6aef Mon Sep 17 00:00:00 2001 From: mdabrowski-eu Date: Sat, 9 May 2020 18:01:17 +0200 Subject: [PATCH 86/91] BAEL-3863 removed redundant twitter4j.properties file --- libraries-rpc/src/main/resources/twitter4j.properties | 4 ---- 1 file changed, 4 deletions(-) delete mode 100644 libraries-rpc/src/main/resources/twitter4j.properties diff --git a/libraries-rpc/src/main/resources/twitter4j.properties b/libraries-rpc/src/main/resources/twitter4j.properties deleted file mode 100644 index ee11dc62a1..0000000000 --- a/libraries-rpc/src/main/resources/twitter4j.properties +++ /dev/null @@ -1,4 +0,0 @@ -oauth.consumerKey=//TODO -oauth.consumerSecret=//TODO -oauth.accessToken=//TODO -oauth.accessTokenSecret=//TODO From 00f5e0012cfa89c0a38c5ff123dd88af76aecfc3 Mon Sep 17 00:00:00 2001 From: Jonathan Cook Date: Wed, 13 May 2020 03:46:33 +0200 Subject: [PATCH 87/91] BAEL-3925 - How to call Python from Java? (#9277) * BAEL-3491 - Check for null before calling parse in the Double.parseDouble * BAEL-3491 - Check for null before calling parse in the Double.parseDouble - Return to indentation with spaces. * BAEL-3854 - Pattern Matching for instanceof in Java 14 * BAEL-3854 - Pattern Matching for instanceof in Java 14 - add unit test * BAEL-3868 - Fix the integrations tests in mocks * BAEL-3925 - How to call Python from Java Co-authored-by: Jonathan Cook --- java-python-interop/README.md | 5 + java-python-interop/pom.xml | 55 ++++++++ .../interop/ScriptEngineManagerUtils.java | 34 +++++ .../src/main/resources/logback.xml | 13 ++ .../interop/JavaPythonInteropUnitTest.java | 131 ++++++++++++++++++ .../src/test/resources/hello.py | 1 + pom.xml | 3 +- 7 files changed, 241 insertions(+), 1 deletion(-) create mode 100644 java-python-interop/README.md create mode 100644 java-python-interop/pom.xml create mode 100644 java-python-interop/src/main/java/com/baeldung/python/interop/ScriptEngineManagerUtils.java create mode 100644 java-python-interop/src/main/resources/logback.xml create mode 100644 java-python-interop/src/test/java/com/baeldung/python/interop/JavaPythonInteropUnitTest.java create mode 100644 java-python-interop/src/test/resources/hello.py diff --git a/java-python-interop/README.md b/java-python-interop/README.md new file mode 100644 index 0000000000..dc9573ecde --- /dev/null +++ b/java-python-interop/README.md @@ -0,0 +1,5 @@ +## Java Python Interop + +This module contains articles about Java and Python interoperability. + +### Relevant Articles: diff --git a/java-python-interop/pom.xml b/java-python-interop/pom.xml new file mode 100644 index 0000000000..6ee5a0be3b --- /dev/null +++ b/java-python-interop/pom.xml @@ -0,0 +1,55 @@ + + + 4.0.0 + java-python-interop + 0.0.1-SNAPSHOT + java-python-interop + + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + + + + + org.python + jython-slim + ${jython.version} + + + org.apache.commons + commons-exec + ${commons-exec.version} + + + org.assertj + assertj-core + ${assertj.version} + test + + + + + java-python-interop + + + src/main/resources + true + + + src/test/resources + true + + + + + + 2.7.2 + 1.3 + 3.6.1 + + + \ No newline at end of file diff --git a/java-python-interop/src/main/java/com/baeldung/python/interop/ScriptEngineManagerUtils.java b/java-python-interop/src/main/java/com/baeldung/python/interop/ScriptEngineManagerUtils.java new file mode 100644 index 0000000000..981f174c33 --- /dev/null +++ b/java-python-interop/src/main/java/com/baeldung/python/interop/ScriptEngineManagerUtils.java @@ -0,0 +1,34 @@ +package com.baeldung.python.interop; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.script.ScriptEngineFactory; +import javax.script.ScriptEngineManager; + +public class ScriptEngineManagerUtils { + + private static final Logger LOGGER = LoggerFactory.getLogger(ScriptEngineManagerUtils.class); + + private ScriptEngineManagerUtils() { + } + + public static void listEngines() { + ScriptEngineManager manager = new ScriptEngineManager(); + List engines = manager.getEngineFactories(); + + for (ScriptEngineFactory engine : engines) { + LOGGER.info("Engine name: {}", engine.getEngineName()); + LOGGER.info("Version: {}", engine.getEngineVersion()); + LOGGER.info("Language: {}", engine.getLanguageName()); + + LOGGER.info("Short Names:"); + for (String names : engine.getNames()) { + LOGGER.info(names); + } + } + } + +} diff --git a/java-python-interop/src/main/resources/logback.xml b/java-python-interop/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/java-python-interop/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/java-python-interop/src/test/java/com/baeldung/python/interop/JavaPythonInteropUnitTest.java b/java-python-interop/src/test/java/com/baeldung/python/interop/JavaPythonInteropUnitTest.java new file mode 100644 index 0000000000..5ec3a2b61f --- /dev/null +++ b/java-python-interop/src/test/java/com/baeldung/python/interop/JavaPythonInteropUnitTest.java @@ -0,0 +1,131 @@ +package com.baeldung.python.interop; + +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.util.List; +import java.util.stream.Collectors; + +import javax.script.ScriptContext; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.SimpleScriptContext; + +import org.apache.commons.exec.CommandLine; +import org.apache.commons.exec.DefaultExecutor; +import org.apache.commons.exec.ExecuteException; +import org.apache.commons.exec.PumpStreamHandler; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.python.core.PyException; +import org.python.core.PyObject; +import org.python.util.PythonInterpreter; + +public class JavaPythonInteropUnitTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void givenPythonScript_whenPythonProcessInvoked_thenSuccess() throws Exception { + ProcessBuilder processBuilder = new ProcessBuilder("python", resolvePythonScriptPath("hello.py")); + processBuilder.redirectErrorStream(true); + + Process process = processBuilder.start(); + List results = readProcessOutput(process.getInputStream()); + + assertThat("Results should not be empty", results, is(not(empty()))); + assertThat("Results should contain output of script: ", results, hasItem(containsString("Hello Baeldung Readers!!"))); + + int exitCode = process.waitFor(); + assertEquals("No errors should be detected", 0, exitCode); + } + + @Test + public void givenPythonScriptEngineIsAvailable_whenScriptInvoked_thenOutputDisplayed() throws Exception { + StringWriter output = new StringWriter(); + ScriptContext context = new SimpleScriptContext(); + context.setWriter(output); + + ScriptEngineManager manager = new ScriptEngineManager(); + ScriptEngine engine = manager.getEngineByName("python"); + engine.eval(new FileReader(resolvePythonScriptPath("hello.py")), context); + assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", output.toString() + .trim()); + } + + @Test + public void givenPythonInterpreter_whenPrintExecuted_thenOutputDisplayed() { + try (PythonInterpreter pyInterp = new PythonInterpreter()) { + StringWriter output = new StringWriter(); + pyInterp.setOut(output); + + pyInterp.exec("print('Hello Baeldung Readers!!')"); + assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", output.toString() + .trim()); + } + } + + @Test + public void givenPythonInterpreter_whenNumbersAdded_thenOutputDisplayed() { + try (PythonInterpreter pyInterp = new PythonInterpreter()) { + pyInterp.exec("x = 10+10"); + PyObject x = pyInterp.get("x"); + assertEquals("x: ", 20, x.asInt()); + } + } + + @Test + public void givenPythonInterpreter_whenErrorOccurs_thenExceptionIsThrown() { + thrown.expect(PyException.class); + thrown.expectMessage("ImportError: No module named syds"); + + try (PythonInterpreter pyInterp = new PythonInterpreter()) { + pyInterp.exec("import syds"); + } + } + + @Test + public void givenPythonScript_whenPythonProcessExecuted_thenSuccess() throws ExecuteException, IOException { + String line = "python " + resolvePythonScriptPath("hello.py"); + CommandLine cmdLine = CommandLine.parse(line); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); + + DefaultExecutor executor = new DefaultExecutor(); + executor.setStreamHandler(streamHandler); + + int exitCode = executor.execute(cmdLine); + assertEquals("No errors should be detected", 0, exitCode); + assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", outputStream.toString() + .trim()); + } + + private List readProcessOutput(InputStream inputStream) throws IOException { + try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) { + return output.lines() + .collect(Collectors.toList()); + } + } + + private String resolvePythonScriptPath(String filename) { + File file = new File("src/test/resources/" + filename); + return file.getAbsolutePath(); + } + +} diff --git a/java-python-interop/src/test/resources/hello.py b/java-python-interop/src/test/resources/hello.py new file mode 100644 index 0000000000..13275d9257 --- /dev/null +++ b/java-python-interop/src/test/resources/hello.py @@ -0,0 +1 @@ +print("Hello Baeldung Readers!!") \ No newline at end of file diff --git a/pom.xml b/pom.xml index 34703c6f73..f750ea8869 100644 --- a/pom.xml +++ b/pom.xml @@ -461,7 +461,8 @@ java-lite java-numbers java-numbers-2 - java-numbers-3 + java-numbers-3 + java-python-interop java-rmi java-spi java-vavr-stream From 020837fa2f2feb4295a315ff285691a459ba54a9 Mon Sep 17 00:00:00 2001 From: sasam0320 <63002713+sasam0320@users.noreply.github.com> Date: Wed, 13 May 2020 11:09:41 +0200 Subject: [PATCH 88/91] BAEL 3234 - Add missing code snippets from the Spring Properties article (#9280) --- .../main/resources/configForDbProperties.xml | 19 +++++++++++++++++++ .../main/resources/configForProperties.xml | 3 ++- .../src/main/resources/database.properties | 5 +++-- ...plePropertiesXmlConfigIntegrationTest.java | 2 +- 4 files changed, 25 insertions(+), 4 deletions(-) create mode 100644 spring-boot-modules/spring-boot-properties/src/main/resources/configForDbProperties.xml diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/configForDbProperties.xml b/spring-boot-modules/spring-boot-properties/src/main/resources/configForDbProperties.xml new file mode 100644 index 0000000000..00fd5f0508 --- /dev/null +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/configForDbProperties.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml b/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml index 4468bb485f..bf4452da4a 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/configForProperties.xml @@ -7,7 +7,8 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd" > - + + diff --git a/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties b/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties index 6524ce6109..eb5703ca72 100644 --- a/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties +++ b/spring-boot-modules/spring-boot-properties/src/main/resources/database.properties @@ -1,4 +1,5 @@ -database.url=jdbc:postgresql:/localhost:5432/instance + +jdbc.url=jdbc:postgresql:/localhost:5432 database.username=foo database.password=bar -jdbc.url=jdbc:postgresql:/localhost:5432 \ No newline at end of file + diff --git a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java index 6827ee1cf1..2150d4b3ec 100644 --- a/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java +++ b/spring-boot-modules/spring-boot-properties/src/test/java/com/baeldung/properties/multiple/MultiplePropertiesXmlConfigIntegrationTest.java @@ -6,7 +6,7 @@ import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import static org.assertj.core.api.Assertions.assertThat; -@SpringJUnitConfig(locations = "classpath:configForProperties.xml") +@SpringJUnitConfig(locations = {"classpath:configForProperties.xml", "classpath:configForDbProperties.xml"}) public class MultiplePropertiesXmlConfigIntegrationTest { @Value("${key.something}") private String something; From b48a87a352ac4d8fec84c257fcb182111a8f6e83 Mon Sep 17 00:00:00 2001 From: Benjamin Caure Date: Wed, 13 May 2020 17:43:22 +0200 Subject: [PATCH 89/91] Copy "BSON to JSON" tutorial entities to dedicated package (#9283) com.baeldung.bsontojson --- .../java/com/baeldung/bsontojson/Book.java | 168 ++++++++++++++++++ .../com/baeldung/bsontojson/Publisher.java | 70 ++++++++ .../bsontojson/BsonToJsonLiveTest.java | 22 +-- 3 files changed, 242 insertions(+), 18 deletions(-) create mode 100644 persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java create mode 100644 persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Publisher.java diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java new file mode 100644 index 0000000000..44e4ecb539 --- /dev/null +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java @@ -0,0 +1,168 @@ +package com.baeldung.bsontojson; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.HashSet; +import java.util.Set; + +import dev.morphia.annotations.Embedded; +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Field; +import dev.morphia.annotations.Id; +import dev.morphia.annotations.Index; +import dev.morphia.annotations.IndexOptions; +import dev.morphia.annotations.Indexes; +import dev.morphia.annotations.Property; +import dev.morphia.annotations.Reference; +import dev.morphia.annotations.Validation; + +@Entity("Books") +@Indexes({ @Index(fields = @Field("title"), options = @IndexOptions(name = "book_title")) }) +@Validation("{ price : { $gt : 0 } }") +public class Book { + @Id + private String isbn; + @Property + private String title; + private String author; + @Embedded + private Publisher publisher; + @Property("price") + private double cost; + @Reference + private Set companionBooks; + @Property + private LocalDateTime publishDate; + + public Book() { + + } + + public Book(String isbn, String title, String author, double cost, Publisher publisher) { + this.isbn = isbn; + this.title = title; + this.author = author; + this.cost = cost; + this.publisher = publisher; + this.companionBooks = new HashSet<>(); + } + + // Getters and setters ... + public String getIsbn() { + return isbn; + } + + public Book setIsbn(String isbn) { + this.isbn = isbn; + return this; + } + + public String getTitle() { + return title; + } + + public Book setTitle(String title) { + this.title = title; + return this; + } + + public String getAuthor() { + return author; + } + + public Book setAuthor(String author) { + this.author = author; + return this; + } + + public Publisher getPublisher() { + return publisher; + } + + public Book setPublisher(Publisher publisher) { + this.publisher = publisher; + return this; + } + + public double getCost() { + return cost; + } + + public Book setCost(double cost) { + this.cost = cost; + return this; + } + + public LocalDateTime getPublishDate() { + return publishDate; + } + + public Book setPublishDate(LocalDateTime publishDate) { + this.publishDate = publishDate; + return this; + } + + public Set getCompanionBooks() { + return companionBooks; + } + + public Book addCompanionBooks(Book book) { + if (companionBooks != null) + this.companionBooks.add(book); + return this; + } + + @Override + public String toString() { + return "Book [isbn=" + isbn + ", title=" + title + ", author=" + author + ", publisher=" + publisher + ", cost=" + cost + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((author == null) ? 0 : author.hashCode()); + long temp; + temp = Double.doubleToLongBits(cost); + result = prime * result + (int) (temp ^ (temp >>> 32)); + result = prime * result + ((isbn == null) ? 0 : isbn.hashCode()); + result = prime * result + ((publisher == null) ? 0 : publisher.hashCode()); + result = prime * result + ((title == null) ? 0 : title.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Book other = (Book) obj; + if (author == null) { + if (other.author != null) + return false; + } else if (!author.equals(other.author)) + return false; + if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost)) + return false; + if (isbn == null) { + if (other.isbn != null) + return false; + } else if (!isbn.equals(other.isbn)) + return false; + if (publisher == null) { + if (other.publisher != null) + return false; + } else if (!publisher.equals(other.publisher)) + return false; + if (title == null) { + if (other.title != null) + return false; + } else if (!title.equals(other.title)) + return false; + return true; + } + +} diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Publisher.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Publisher.java new file mode 100644 index 0000000000..1ab262c82b --- /dev/null +++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Publisher.java @@ -0,0 +1,70 @@ +package com.baeldung.bsontojson; + +import org.bson.types.ObjectId; + +import dev.morphia.annotations.Entity; +import dev.morphia.annotations.Id; + +@Entity +public class Publisher { + + @Id + private ObjectId id; + private String name; + + public Publisher() { + + } + + public Publisher(ObjectId id, String name) { + this.id = id; + this.name = name; + } + + public ObjectId getId() { + return id; + } + + public void setId(ObjectId id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + return "Catalog [id=" + id + ", name=" + name + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Publisher other = (Publisher) obj; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + +} diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java index 4e70394069..12053523f8 100644 --- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java @@ -2,32 +2,18 @@ package com.baeldung.bsontojson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import java.sql.Timestamp; -import java.time.Instant; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.TimeZone; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import org.bson.Document; -import org.bson.json.Converter; import org.bson.json.JsonMode; import org.bson.json.JsonWriterSettings; -import org.bson.json.StrictJsonWriter; import org.bson.types.ObjectId; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.jupiter.api.AfterEach; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.baeldung.morphia.domain.Book; -import com.baeldung.morphia.domain.Publisher; import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; @@ -42,7 +28,7 @@ public class BsonToJsonLiveTest { @BeforeClass public static void setUp() { Morphia morphia = new Morphia(); - morphia.mapPackage("com.baeldung.morphia"); + morphia.mapPackage("com.baeldung.bsontojson"); datastore = morphia.createDatastore(new MongoClient(), DB_NAME); datastore.ensureIndexes(); @@ -72,7 +58,7 @@ public class BsonToJsonLiveTest { } String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"className\": \"com.baeldung.bsontojson.Book\", " + "\"title\": \"title\", " + "\"author\": \"author\", " + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + @@ -100,7 +86,7 @@ public class BsonToJsonLiveTest { } String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"className\": \"com.baeldung.bsontojson.Book\", " + "\"title\": \"title\", " + "\"author\": \"author\", " + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + @@ -127,7 +113,7 @@ public class BsonToJsonLiveTest { } String expectedJson = "{\"_id\": \"isbn\", " + - "\"className\": \"com.baeldung.morphia.domain.Book\", " + + "\"className\": \"com.baeldung.bsontojson.Book\", " + "\"title\": \"title\", " + "\"author\": \"author\", " + "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + From f58c322ae2c2500f14033f88eda10e7c20aaa3d9 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Thu, 14 May 2020 12:13:53 +0530 Subject: [PATCH 90/91] JAVA-943: Migrate spring-mobile to parent-boot-2 --- spring-mobile/pom.xml | 19 ++++++++-- .../src/main/java/com/baeldung/AppConfig.java | 36 +++++++++++++++++++ .../baeldung/controller/IndexController.java | 5 ++- .../src/main/resources/application.properties | 4 ++- 4 files changed, 59 insertions(+), 5 deletions(-) create mode 100644 spring-mobile/src/main/java/com/baeldung/AppConfig.java diff --git a/spring-mobile/pom.xml b/spring-mobile/pom.xml index ff90ac6ecb..465458ba49 100644 --- a/spring-mobile/pom.xml +++ b/spring-mobile/pom.xml @@ -10,9 +10,9 @@ com.baeldung - parent-boot-1 + parent-boot-2 0.0.1-SNAPSHOT - ../parent-boot-1 + ../parent-boot-2 @@ -23,11 +23,24 @@ org.springframework.mobile spring-mobile-device + ${spring-mobile-device.version} org.springframework.boot spring-boot-starter-freemarker - + + + spring-milestones + Spring Milestones + https://repo.spring.io/libs-milestone + + false + + + + + 2.0.0.M3 + diff --git a/spring-mobile/src/main/java/com/baeldung/AppConfig.java b/spring-mobile/src/main/java/com/baeldung/AppConfig.java new file mode 100644 index 0000000000..efa073ae11 --- /dev/null +++ b/spring-mobile/src/main/java/com/baeldung/AppConfig.java @@ -0,0 +1,36 @@ +package com.baeldung; + +import java.util.List; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.mobile.device.DeviceHandlerMethodArgumentResolver; +import org.springframework.mobile.device.DeviceResolverHandlerInterceptor; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +@Configuration +public class AppConfig implements WebMvcConfigurer { + + @Bean + public DeviceResolverHandlerInterceptor deviceResolverHandlerInterceptor() { + return new DeviceResolverHandlerInterceptor(); + } + + @Bean + public DeviceHandlerMethodArgumentResolver deviceHandlerMethodArgumentResolver() { + return new DeviceHandlerMethodArgumentResolver(); + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(deviceResolverHandlerInterceptor()); + } + + @Override + public void addArgumentResolvers(List argumentResolvers) { + argumentResolvers.add(deviceHandlerMethodArgumentResolver()); + } + +} diff --git a/spring-mobile/src/main/java/com/baeldung/controller/IndexController.java b/spring-mobile/src/main/java/com/baeldung/controller/IndexController.java index 196fb680e7..49880f355a 100644 --- a/spring-mobile/src/main/java/com/baeldung/controller/IndexController.java +++ b/spring-mobile/src/main/java/com/baeldung/controller/IndexController.java @@ -16,13 +16,16 @@ public class IndexController { String deviceType = "browser"; String platform = "browser"; + String viewName = "index"; if (device.isNormal()) { deviceType = "browser"; } else if (device.isMobile()) { deviceType = "mobile"; + viewName = "mobile/index"; } else if (device.isTablet()) { deviceType = "tablet"; + viewName = "tablet/index"; } platform = device.getDevicePlatform().name(); @@ -33,7 +36,7 @@ public class IndexController { LOGGER.info("Client Device Type: " + deviceType + ", Platform: " + platform); - return "index"; + return viewName; } } diff --git a/spring-mobile/src/main/resources/application.properties b/spring-mobile/src/main/resources/application.properties index c0bc91f9ac..7d964f48fb 100644 --- a/spring-mobile/src/main/resources/application.properties +++ b/spring-mobile/src/main/resources/application.properties @@ -1 +1,3 @@ -spring.mobile.devicedelegatingviewresolver.enabled: true \ No newline at end of file +spring.mobile.devicedelegatingviewresolver.enabled: true +spring.freemarker.template-loader-path: classpath:/templates +spring.freemarker.suffix: .ftl \ No newline at end of file From 3c9b335ed5d48c0ae19557732ce46470350c58bf Mon Sep 17 00:00:00 2001 From: Roque Santos Date: Thu, 14 May 2020 13:56:35 -0300 Subject: [PATCH 91/91] BAEL-3942 : Correct failing build (#9289) Changed IntegrationTest to LiveTest --- .../jsonproxy/JsoupProxyLiveTest.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyLiveTest.java diff --git a/jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyLiveTest.java b/jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyLiveTest.java new file mode 100644 index 0000000000..931464c4db --- /dev/null +++ b/jsoup/src/test/java/com/baeldung/jsonproxy/JsoupProxyLiveTest.java @@ -0,0 +1,27 @@ +package com.baeldung.jsonproxy; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Proxy; + +import org.jsoup.Jsoup; +import org.junit.Test; + +public class JsoupProxyLiveTest { + + @Test + public void whenUsingHostAndPort_thenConnect() throws IOException { + Jsoup.connect("https://spring.io/blog") + .proxy("200.216.227.141", 53281) + .get(); + } + + @Test + public void whenUsingProxyClass_thenConnect() throws IOException { + Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("200.216.227.141", 53281)); + + Jsoup.connect("https://spring.io/blog") + .proxy(proxy) + .get(); + } +}