diff --git a/.gitignore b/.gitignore
index 21586748b7..50cb889e5b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,6 +19,7 @@
.idea/
*.iml
*.iws
+out/
# Mac
.DS_Store
@@ -27,6 +28,9 @@
log/
target/
+# Gradle
+.gradle/
+
spring-openid/src/main/resources/application.properties
.recommenders/
/spring-hibernate4/nbproject/
@@ -72,4 +76,5 @@ persistence-modules/hibernate5/transaction.log
apache-avro/src/main/java/com/baeldung/avro/model/
jta/transaction-logs/
software-security/sql-injection-samples/derby.log
-spring-soap/src/main/java/com/baeldung/springsoap/gen/
\ No newline at end of file
+spring-soap/src/main/java/com/baeldung/springsoap/gen/
+/report-*.json
\ No newline at end of file
diff --git a/README.md b/README.md
index 378d77196a..1030cbb09c 100644
--- a/README.md
+++ b/README.md
@@ -20,17 +20,22 @@ In additional to Spring, the following technologies are in focus: `core Java`, `
Building the project
====================
-To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
+To do the full build, do: `mvn clean install`
Building a single module
====================
-To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory
+To build a specific module run the command: `mvn clean install` in the module directory
Running a Spring Boot module
====================
-To run a Spring Boot module run the command: `mvn spring-boot:run -Dgib.enabled=false` in the module directory
+To run a Spring Boot module run the command: `mvn spring-boot:run` in the module directory
+
+#Running Tests
+
+The command `mvn clean install` will run the unit tests in a module.
+To run the integration tests, use the command `mvn clean install -Pintegration-lite-first`
diff --git a/akka-streams/pom.xml b/akka-streams/pom.xml
index a885753ce2..7719bb7351 100644
--- a/akka-streams/pom.xml
+++ b/akka-streams/pom.xml
@@ -14,18 +14,19 @@
com.typesafe.akka
- akka-stream_2.11
+ akka-stream_${scala.version}
${akkastreams.version}
com.typesafe.akka
- akka-stream-testkit_2.11
+ akka-stream-testkit_${scala.version}
${akkastreams.version}
2.5.2
+ 2.11
\ No newline at end of file
diff --git a/algorithms-miscellaneous-1/README.md b/algorithms-miscellaneous-1/README.md
index 7ed805f7c4..479c2792f6 100644
--- a/algorithms-miscellaneous-1/README.md
+++ b/algorithms-miscellaneous-1/README.md
@@ -14,6 +14,5 @@
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
-- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
-- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
+- [Generate Combinations in Java](https://www.baeldung.com/java-combinations-algorithm)
diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml
index fe670963c0..30130208f8 100644
--- a/algorithms-miscellaneous-1/pom.xml
+++ b/algorithms-miscellaneous-1/pom.xml
@@ -39,6 +39,11 @@
${org.assertj.core.version}
test
+
+ com.github.dpaukov
+ combinatoricslib3
+ 3.3.0
+
@@ -77,7 +82,7 @@
3.6.1
3.9.0
1.11
- 25.1-jre
+ 27.0.1-jre
\ No newline at end of file
diff --git a/algorithms-miscellaneous-2/README.md b/algorithms-miscellaneous-2/README.md
index d693a44f66..462644dddb 100644
--- a/algorithms-miscellaneous-2/README.md
+++ b/algorithms-miscellaneous-2/README.md
@@ -8,9 +8,6 @@
- [Create a Sudoku Solver in Java](http://www.baeldung.com/java-sudoku)
- [Displaying Money Amounts in Words](http://www.baeldung.com/java-money-into-words)
- [A Collaborative Filtering Recommendation System in Java](http://www.baeldung.com/java-collaborative-filtering-recommendations)
-- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
-- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
-- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
@@ -18,3 +15,5 @@
- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
- [Converting Between Byte Arrays and Hexadecimal Strings in Java](https://www.baeldung.com/java-byte-arrays-hex-strings)
- [Convert Latitude and Longitude to a 2D Point in Java](https://www.baeldung.com/java-convert-latitude-longitude)
+- [Reversing a Binary Tree in Java](https://www.baeldung.com/java-reversing-a-binary-tree)
+- [Find If Two Numbers Are Relatively Prime in Java](https://www.baeldung.com/java-two-relatively-prime-numbers)
diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/relativelyprime/RelativelyPrime.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/relativelyprime/RelativelyPrime.java
new file mode 100644
index 0000000000..fbea87be30
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/relativelyprime/RelativelyPrime.java
@@ -0,0 +1,45 @@
+package com.baeldung.algorithms.relativelyprime;
+
+import java.math.BigInteger;
+
+class RelativelyPrime {
+
+ static boolean iterativeRelativelyPrime(int a, int b) {
+ return iterativeGCD(a, b) == 1;
+ }
+
+ static boolean recursiveRelativelyPrime(int a, int b) {
+ return recursiveGCD(a, b) == 1;
+ }
+
+ static boolean bigIntegerRelativelyPrime(int a, int b) {
+ return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).equals(BigInteger.ONE);
+ }
+
+ private static int iterativeGCD(int a, int b) {
+ int tmp;
+ while (b != 0) {
+ if (a < b) {
+ tmp = a;
+ a = b;
+ b = tmp;
+ }
+ tmp = b;
+ b = a % b;
+ a = tmp;
+ }
+ return a;
+ }
+
+ private static int recursiveGCD(int a, int b) {
+ if (b == 0) {
+ return a;
+ }
+ if (a < b) {
+ return recursiveGCD(b, a);
+ }
+ return recursiveGCD(b, a % b);
+ }
+
+
+}
diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java
new file mode 100644
index 0000000000..a6ec2277e5
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeNode.java
@@ -0,0 +1,42 @@
+package com.baeldung.algorithms.reversingtree;
+
+public class TreeNode {
+
+ private int value;
+ private TreeNode rightChild;
+ private TreeNode leftChild;
+
+ public int getValue() {
+ return value;
+ }
+
+ public void setValue(int value) {
+ this.value = value;
+ }
+
+ public TreeNode getRightChild() {
+ return rightChild;
+ }
+
+ public void setRightChild(TreeNode rightChild) {
+ this.rightChild = rightChild;
+ }
+
+ public TreeNode getLeftChild() {
+ return leftChild;
+ }
+
+ public void setLeftChild(TreeNode leftChild) {
+ this.leftChild = leftChild;
+ }
+
+ public TreeNode(int value, TreeNode leftChild, TreeNode rightChild) {
+ this.value = value;
+ this.rightChild = rightChild;
+ this.leftChild = leftChild;
+ }
+
+ public TreeNode(int value) {
+ this.value = value;
+ }
+}
diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java
new file mode 100644
index 0000000000..162119d390
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/reversingtree/TreeReverser.java
@@ -0,0 +1,53 @@
+package com.baeldung.algorithms.reversingtree;
+
+import java.util.LinkedList;
+
+public class TreeReverser {
+
+ public void reverseRecursive(TreeNode treeNode) {
+ if (treeNode == null) {
+ return;
+ }
+
+ TreeNode temp = treeNode.getLeftChild();
+ treeNode.setLeftChild(treeNode.getRightChild());
+ treeNode.setRightChild(temp);
+
+ reverseRecursive(treeNode.getLeftChild());
+ reverseRecursive(treeNode.getRightChild());
+ }
+
+ public void reverseIterative(TreeNode treeNode) {
+ LinkedList queue = new LinkedList();
+
+ if (treeNode != null) {
+ queue.add(treeNode);
+ }
+
+ while (!queue.isEmpty()) {
+
+ TreeNode node = queue.poll();
+ if (node.getLeftChild() != null)
+ queue.add(node.getLeftChild());
+ if (node.getRightChild() != null)
+ queue.add(node.getRightChild());
+
+ TreeNode temp = node.getLeftChild();
+ node.setLeftChild(node.getRightChild());
+ node.setRightChild(temp);
+ }
+ }
+
+ public String toString(TreeNode root) {
+ if (root == null) {
+ return "";
+ }
+
+ StringBuffer buffer = new StringBuffer(String.valueOf(root.getValue())).append(" ");
+
+ buffer.append(toString(root.getLeftChild()));
+ buffer.append(toString(root.getRightChild()));
+
+ return buffer.toString();
+ }
+}
diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/relativelyprime/RelativelyPrimeUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/relativelyprime/RelativelyPrimeUnitTest.java
new file mode 100644
index 0000000000..84bb2620af
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/relativelyprime/RelativelyPrimeUnitTest.java
@@ -0,0 +1,51 @@
+package com.baeldung.algorithms.relativelyprime;
+
+import org.junit.Test;
+
+import static com.baeldung.algorithms.relativelyprime.RelativelyPrime.*;
+import static org.assertj.core.api.Assertions.assertThat;
+
+public class RelativelyPrimeUnitTest {
+
+ @Test
+ public void givenNonRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnFalse() {
+
+ boolean result = iterativeRelativelyPrime(45, 35);
+ assertThat(result).isFalse();
+ }
+
+ @Test
+ public void givenRelativelyPrimeNumbers_whenCheckingIteratively_shouldReturnTrue() {
+
+ boolean result = iterativeRelativelyPrime(500, 501);
+ assertThat(result).isTrue();
+ }
+
+ @Test
+ public void givenNonRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnFalse() {
+
+ boolean result = recursiveRelativelyPrime(45, 35);
+ assertThat(result).isFalse();
+ }
+
+ @Test
+ public void givenRelativelyPrimeNumbers_whenCheckingRecursively_shouldReturnTrue() {
+
+ boolean result = recursiveRelativelyPrime(500, 501);
+ assertThat(result).isTrue();
+ }
+
+ @Test
+ public void givenNonRelativelyPrimeNumbers_whenCheckingUsingBigIntegers_shouldReturnFalse() {
+
+ boolean result = bigIntegerRelativelyPrime(45, 35);
+ assertThat(result).isFalse();
+ }
+
+ @Test
+ public void givenRelativelyPrimeNumbers_whenCheckingBigIntegers_shouldReturnTrue() {
+
+ boolean result = bigIntegerRelativelyPrime(500, 501);
+ assertThat(result).isTrue();
+ }
+}
diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java
new file mode 100644
index 0000000000..44fac57361
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/reversingtree/TreeReverserUnitTest.java
@@ -0,0 +1,47 @@
+package com.baeldung.algorithms.reversingtree;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+public class TreeReverserUnitTest {
+
+ @Test
+ public void givenTreeWhenReversingRecursivelyThenReversed() {
+ TreeReverser reverser = new TreeReverser();
+
+ TreeNode treeNode = createBinaryTree();
+
+ reverser.reverseRecursive(treeNode);
+
+ assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
+ .trim());
+ }
+
+ @Test
+ public void givenTreeWhenReversingIterativelyThenReversed() {
+ TreeReverser reverser = new TreeReverser();
+
+ TreeNode treeNode = createBinaryTree();
+
+ reverser.reverseIterative(treeNode);
+
+ assertEquals("4 7 9 6 2 3 1", reverser.toString(treeNode)
+ .trim());
+ }
+
+ private TreeNode createBinaryTree() {
+
+ TreeNode leaf1 = new TreeNode(1);
+ TreeNode leaf2 = new TreeNode(3);
+ TreeNode leaf3 = new TreeNode(6);
+ TreeNode leaf4 = new TreeNode(9);
+
+ TreeNode nodeRight = new TreeNode(7, leaf3, leaf4);
+ TreeNode nodeLeft = new TreeNode(2, leaf1, leaf2);
+
+ TreeNode root = new TreeNode(4, nodeLeft, nodeRight);
+
+ return root;
+ }
+}
diff --git a/algorithms-miscellaneous-3/.gitignore b/algorithms-miscellaneous-3/.gitignore
new file mode 100644
index 0000000000..30b2b7442c
--- /dev/null
+++ b/algorithms-miscellaneous-3/.gitignore
@@ -0,0 +1,4 @@
+/target/
+.settings/
+.classpath
+.project
\ No newline at end of file
diff --git a/algorithms-miscellaneous-3/README.md b/algorithms-miscellaneous-3/README.md
new file mode 100644
index 0000000000..4dd4b66ff2
--- /dev/null
+++ b/algorithms-miscellaneous-3/README.md
@@ -0,0 +1,6 @@
+## Relevant articles:
+
+- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
+- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)
+- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
+- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
diff --git a/algorithms-miscellaneous-3/pom.xml b/algorithms-miscellaneous-3/pom.xml
new file mode 100644
index 0000000000..c4017144c8
--- /dev/null
+++ b/algorithms-miscellaneous-3/pom.xml
@@ -0,0 +1,39 @@
+
+ 4.0.0
+ algorithms-miscellaneous-3
+ 0.0.1-SNAPSHOT
+ algorithms-miscellaneous-3
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ org.assertj
+ assertj-core
+ ${org.assertj.core.version}
+ test
+
+
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ ${exec-maven-plugin.version}
+
+
+
+
+
+
+ 3.9.0
+
+
+
\ No newline at end of file
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestState.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestState.java
similarity index 100%
rename from algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestState.java
rename to algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestState.java
diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Graph.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Graph.java
new file mode 100644
index 0000000000..c77173b288
--- /dev/null
+++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Graph.java
@@ -0,0 +1,51 @@
+package com.baeldung.algorithms.graphcycledetection.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Graph {
+
+ private List vertices;
+
+ public Graph() {
+ this.vertices = new ArrayList<>();
+ }
+
+ public Graph(List vertices) {
+ this.vertices = vertices;
+ }
+
+ public void addVertex(Vertex vertex) {
+ this.vertices.add(vertex);
+ }
+
+ public void addEdge(Vertex from, Vertex to) {
+ from.addNeighbour(to);
+ }
+
+ public boolean hasCycle() {
+ for (Vertex vertex : vertices) {
+ if (!vertex.isVisited() && hasCycle(vertex)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean hasCycle(Vertex sourceVertex) {
+ sourceVertex.setBeingVisited(true);
+
+ for (Vertex neighbour : sourceVertex.getAdjacencyList()) {
+ if (neighbour.isBeingVisited()) {
+ // backward edge exists
+ return true;
+ } else if (!neighbour.isVisited() && hasCycle(neighbour)) {
+ return true;
+ }
+ }
+
+ sourceVertex.setBeingVisited(false);
+ sourceVertex.setVisited(true);
+ return false;
+ }
+}
diff --git a/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Vertex.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Vertex.java
new file mode 100644
index 0000000000..398cdf0d9c
--- /dev/null
+++ b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/graphcycledetection/domain/Vertex.java
@@ -0,0 +1,56 @@
+package com.baeldung.algorithms.graphcycledetection.domain;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Vertex {
+
+ private String label;
+
+ private boolean visited;
+
+ private boolean beingVisited;
+
+ private List adjacencyList;
+
+ public Vertex(String label) {
+ this.label = label;
+ this.adjacencyList = new ArrayList<>();
+ }
+
+ public String getLabel() {
+ return label;
+ }
+
+ public void setLabel(String label) {
+ this.label = label;
+ }
+
+ public boolean isVisited() {
+ return visited;
+ }
+
+ public void setVisited(boolean visited) {
+ this.visited = visited;
+ }
+
+ public boolean isBeingVisited() {
+ return beingVisited;
+ }
+
+ public void setBeingVisited(boolean beingVisited) {
+ this.beingVisited = beingVisited;
+ }
+
+ public List getAdjacencyList() {
+ return adjacencyList;
+ }
+
+ public void setAdjacencyList(List adjacencyList) {
+ this.adjacencyList = adjacencyList;
+ }
+
+ public void addNeighbour(Vertex adjacent) {
+ this.adjacencyList.add(adjacent);
+ }
+}
diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java
similarity index 100%
rename from algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java
rename to algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/romannumerals/RomanArabicConverter.java
diff --git a/algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java
similarity index 100%
rename from algorithms-miscellaneous-2/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java
rename to algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/romannumerals/RomanNumeral.java
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddle.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddle.java
similarity index 100%
rename from algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddle.java
rename to algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddle.java
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/MyNode.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/MyNode.java
similarity index 100%
rename from algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/MyNode.java
rename to algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/MyNode.java
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/RotateArray.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/RotateArray.java
similarity index 100%
rename from algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/RotateArray.java
rename to algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/RotateArray.java
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/TwoSum.java b/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/TwoSum.java
similarity index 100%
rename from algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/twopointertechnique/TwoSum.java
rename to algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/twopointertechnique/TwoSum.java
diff --git a/core-java-10/src/main/resources/logback.xml b/algorithms-miscellaneous-3/src/main/resources/logback.xml
similarity index 100%
rename from core-java-10/src/main/resources/logback.xml
rename to algorithms-miscellaneous-3/src/main/resources/logback.xml
diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java
similarity index 100%
rename from algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java
rename to algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/analysis/AnalysisRunnerLiveTest.java
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java
similarity index 100%
rename from algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java
rename to algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/enumstatemachine/LeaveRequestStateUnitTest.java
diff --git a/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java
new file mode 100644
index 0000000000..8d464d7b97
--- /dev/null
+++ b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/graphcycledetection/GraphCycleDetectionUnitTest.java
@@ -0,0 +1,56 @@
+package com.baeldung.algorithms.graphcycledetection;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+import com.baeldung.algorithms.graphcycledetection.domain.Graph;
+import com.baeldung.algorithms.graphcycledetection.domain.Vertex;
+
+public class GraphCycleDetectionUnitTest {
+
+ @Test
+ public void givenGraph_whenCycleExists_thenReturnTrue() {
+
+ Vertex vertexA = new Vertex("A");
+ Vertex vertexB = new Vertex("B");
+ Vertex vertexC = new Vertex("C");
+ Vertex vertexD = new Vertex("D");
+
+ Graph graph = new Graph();
+ graph.addVertex(vertexA);
+ graph.addVertex(vertexB);
+ graph.addVertex(vertexC);
+ graph.addVertex(vertexD);
+
+ graph.addEdge(vertexA, vertexB);
+ graph.addEdge(vertexB, vertexC);
+ graph.addEdge(vertexC, vertexA);
+ graph.addEdge(vertexD, vertexC);
+
+ assertTrue(graph.hasCycle());
+ }
+
+ @Test
+ public void givenGraph_whenNoCycleExists_thenReturnFalse() {
+
+ Vertex vertexA = new Vertex("A");
+ Vertex vertexB = new Vertex("B");
+ Vertex vertexC = new Vertex("C");
+ Vertex vertexD = new Vertex("D");
+
+ Graph graph = new Graph();
+ graph.addVertex(vertexA);
+ graph.addVertex(vertexB);
+ graph.addVertex(vertexC);
+ graph.addVertex(vertexD);
+
+ graph.addEdge(vertexA, vertexB);
+ graph.addEdge(vertexB, vertexC);
+ graph.addEdge(vertexA, vertexC);
+ graph.addEdge(vertexD, vertexC);
+
+ assertFalse(graph.hasCycle());
+ }
+}
diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java
similarity index 100%
rename from algorithms-miscellaneous-2/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java
rename to algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/romannumerals/RomanArabicConverterUnitTest.java
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java
similarity index 100%
rename from algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java
rename to algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/LinkedListFindMiddleUnitTest.java
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java
similarity index 100%
rename from algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java
rename to algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/RotateArrayUnitTest.java
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java b/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java
similarity index 100%
rename from algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java
rename to algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/twopointertechnique/TwoSumUnitTest.java
diff --git a/antlr/pom.xml b/antlr/pom.xml
index ac66891598..91b939a882 100644
--- a/antlr/pom.xml
+++ b/antlr/pom.xml
@@ -10,6 +10,14 @@
1.0.0-SNAPSHOT
+
+
+ org.antlr
+ antlr4-runtime
+ ${antlr.version}
+
+
+
@@ -44,13 +52,7 @@
-
-
- org.antlr
- antlr4-runtime
- ${antlr.version}
-
-
+
4.7.1
3.0.0
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
index c7acf22c32..be2138e172 100644
--- a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
@@ -12,9 +12,18 @@
0.0.1-SNAPSHOT
-
- 3.2.0
-
+
+
+ org.apache.cxf
+ cxf-rt-rs-client
+ ${cxf-version}
+
+
+ org.apache.cxf
+ cxf-rt-rs-sse
+ ${cxf-version}
+
+
@@ -45,17 +54,8 @@
-
-
- org.apache.cxf
- cxf-rt-rs-client
- ${cxf-version}
-
-
- org.apache.cxf
- cxf-rt-rs-sse
- ${cxf-version}
-
-
+
+ 3.2.0
+
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
index eeb5726ee1..43bbcf1ef4 100644
--- a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
@@ -13,11 +13,28 @@
0.0.1-SNAPSHOT
-
- 2.4.2
- false
- 18.0.0.2
-
+
+
+
+ javax.ws.rs
+ javax.ws.rs-api
+ 2.1
+ provided
+
+
+ javax.enterprise
+ cdi-api
+ 2.0
+ provided
+
+
+ javax.json.bind
+ javax.json.bind-api
+ 1.0
+ provided
+
+
+
${project.artifactId}
@@ -59,27 +76,10 @@
-
-
-
- javax.ws.rs
- javax.ws.rs-api
- 2.1
- provided
-
-
- javax.enterprise
- cdi-api
- 2.0
- provided
-
-
- javax.json.bind
- javax.json.bind-api
- 1.0
- provided
-
-
-
+
+ 2.4.2
+ false
+ 18.0.0.2
+
diff --git a/apache-fop/README.md b/apache-fop/README.md
index 772681ad57..1e734a5f36 100644
--- a/apache-fop/README.md
+++ b/apache-fop/README.md
@@ -3,7 +3,3 @@
## Core Java Cookbooks and Examples
### Relevant Articles:
-- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
-- [Java - Reading a Large File Efficiently](http://www.baeldung.com/java-read-lines-large-file)
-- [Java InputStream to String](http://www.baeldung.com/convert-input-stream-to-string)
-
diff --git a/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesLiveTest.java
similarity index 98%
rename from apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java
rename to apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesLiveTest.java
index b96d2c9b6a..359568db98 100644
--- a/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java
+++ b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesLiveTest.java
@@ -21,7 +21,7 @@ import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
-public class GeodeSamplesIntegrationTest {
+public class GeodeSamplesLiveTest {
ClientCache cache = null;
Region region = null;
diff --git a/apache-meecrowave/pom.xml b/apache-meecrowave/pom.xml
index fb5af69f9b..4eb1094f94 100644
--- a/apache-meecrowave/pom.xml
+++ b/apache-meecrowave/pom.xml
@@ -6,6 +6,12 @@
0.0.1
apache-meecrowave
A sample REST API application with Meecrowave
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
@@ -54,7 +60,6 @@
1.8
1.8
- 4.10
1.2.0
3.10.0
1.2.1
diff --git a/apache-meecrowave/src/test/java/com/baeldung/meecrowave/ArticleEndpointsTest.java b/apache-meecrowave/src/test/java/com/baeldung/meecrowave/ArticleEndpointsUnitTest.java
similarity index 96%
rename from apache-meecrowave/src/test/java/com/baeldung/meecrowave/ArticleEndpointsTest.java
rename to apache-meecrowave/src/test/java/com/baeldung/meecrowave/ArticleEndpointsUnitTest.java
index 0dc9773490..f9a06fd7b9 100644
--- a/apache-meecrowave/src/test/java/com/baeldung/meecrowave/ArticleEndpointsTest.java
+++ b/apache-meecrowave/src/test/java/com/baeldung/meecrowave/ArticleEndpointsUnitTest.java
@@ -17,7 +17,7 @@ import okhttp3.Request;
import okhttp3.Response;
@RunWith(MonoMeecrowave.Runner.class)
-public class ArticleEndpointsTest {
+public class ArticleEndpointsUnitTest {
@ConfigurationInject
private Meecrowave.Builder config;
diff --git a/apache-olingo/README.md b/apache-olingo/README.md
new file mode 100644
index 0000000000..bfbdc97700
--- /dev/null
+++ b/apache-olingo/README.md
@@ -0,0 +1,3 @@
+## Relevant articles:
+
+- [OData Protocol Guide](https://www.baeldung.com/odata)
diff --git a/apache-olingo/Samples.md b/apache-olingo/Samples.md
new file mode 100644
index 0000000000..def8971d64
--- /dev/null
+++ b/apache-olingo/Samples.md
@@ -0,0 +1,21 @@
+## OData test URLs
+
+This following table contains test URLs that can be used with the Olingo V2 demo project.
+
+| URL | Description |
+|------------------------------------------|-------------------------------------------------|
+| `http://localhost:8180/odata/$metadata` | fetch OData metadata document |
+| `http://localhost:8180/odata/CarMakers?$top=10&$skip=10` | Get 10 entities starting at offset 10 |
+| `http://localhost:8180/odata/CarMakers?$count` | Return total count of entities in this set |
+| `http://localhost:8180/odata/CarMakers?$filter=startswith(Name,'B')` | Return entities where the *Name* property starts with 'B' |
+| `http://localhost:8180/odata/CarModels?$filter=Year eq 2008 and CarMakerDetails/Name eq 'BWM'` | Return *CarModel* entities where the *Name* property of its maker starts with 'B' |
+| `http://localhost:8180/odata/CarModels(1L)?$expand=CarMakerDetails` | Return the *CarModel* with primary key '1', along with its maker|
+| `http://localhost:8180/odata/CarModels(1L)?$select=Name,Sku` | Return the *CarModel* with primary key '1', returing only its *Name* and *Sku* properties |
+| `http://localhost:8180/odata/CarModels?$orderBy=Name asc,Sku desc` | Return *CarModel* entities, ordered by the their *Name* and *Sku* properties |
+| `http://localhost:8180/odata/CarModels?$format=json` | Return *CarModel* entities, using a JSON representation|
+
+
+
+
+
+
diff --git a/apache-olingo/olingo2/.gitignore b/apache-olingo/olingo2/.gitignore
new file mode 100644
index 0000000000..153c9335eb
--- /dev/null
+++ b/apache-olingo/olingo2/.gitignore
@@ -0,0 +1,29 @@
+HELP.md
+/target/
+!.mvn/wrapper/maven-wrapper.jar
+
+### STS ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### IntelliJ IDEA ###
+.idea
+*.iws
+*.iml
+*.ipr
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+/build/
+
+### VS Code ###
+.vscode/
diff --git a/apache-olingo/olingo2/pom.xml b/apache-olingo/olingo2/pom.xml
new file mode 100644
index 0000000000..1efd4ea602
--- /dev/null
+++ b/apache-olingo/olingo2/pom.xml
@@ -0,0 +1,93 @@
+
+
+ 4.0.0
+
+ org.springframework.boot
+ spring-boot-starter-parent
+ 2.1.3.RELEASE
+
+
+ org.baeldung.examples.olingo2
+ olingo2-sample
+ 0.0.1-SNAPSHOT
+ olingo2-sample
+ Sample Olingo 2 Project
+
+
+ 1.8
+ 2.0.11
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-jersey
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+
+
+ com.h2database
+ h2
+ runtime
+
+
+ org.springframework.boot
+ spring-boot-configuration-processor
+ true
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+
+ org.apache.olingo
+ olingo-odata2-core
+ ${olingo2.version}
+
+
+
+ javax.ws.rs
+ javax.ws.rs-api
+
+
+
+
+ org.apache.olingo
+ olingo-odata2-jpa-processor-core
+ ${olingo2.version}
+
+
+ org.apache.olingo
+ olingo-odata2-jpa-processor-ref
+ ${olingo2.version}
+
+
+ org.eclipse.persistence
+ eclipselink
+
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java
new file mode 100644
index 0000000000..65a0428154
--- /dev/null
+++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/CarsODataJPAServiceFactory.java
@@ -0,0 +1,298 @@
+package org.baeldung.examples.olingo2;
+
+import java.util.List;
+import java.util.Map;
+
+import javax.persistence.EntityGraph;
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.persistence.FlushModeType;
+import javax.persistence.LockModeType;
+import javax.persistence.Persistence;
+import javax.persistence.Query;
+import javax.persistence.StoredProcedureQuery;
+import javax.persistence.SynchronizationType;
+import javax.persistence.TypedQuery;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaDelete;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.CriteriaUpdate;
+import javax.persistence.metamodel.Metamodel;
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.olingo.odata2.api.processor.ODataContext;
+import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext;
+import org.apache.olingo.odata2.jpa.processor.api.ODataJPAServiceFactory;
+import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException;
+import org.baeldung.examples.olingo2.JerseyConfig.EntityManagerFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.orm.jpa.EntityManagerFactoryUtils;
+import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
+import org.springframework.stereotype.Component;
+
+/**
+ * ODataJPAServiceFactory implementation for our sample domain
+ * @author Philippe
+ *
+ */
+@Component
+public class CarsODataJPAServiceFactory extends ODataJPAServiceFactory {
+
+ private static final Logger log = LoggerFactory.getLogger(CarsODataJPAServiceFactory.class);
+
+ public CarsODataJPAServiceFactory() {
+ // Enable detailed error messages (useful for debugging)
+ setDetailErrors(true);
+ }
+
+ /**
+ * This method will be called by Olingo on every request to
+ * initialize the ODataJPAContext that will be used.
+ */
+ @Override
+ public ODataJPAContext initializeODataJPAContext() throws ODataJPARuntimeException {
+
+ log.info("[I32] >>> initializeODataJPAContext()");
+ ODataJPAContext ctx = getODataJPAContext();
+ ODataContext octx = ctx.getODataContext();
+ HttpServletRequest request = (HttpServletRequest)octx.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT);
+ EntityManager em = (EntityManager)request.getAttribute(EntityManagerFilter.EM_REQUEST_ATTRIBUTE);
+
+ // Here we're passing the EM that was created by the EntityManagerFilter (see JerseyConfig)
+ ctx.setEntityManager(new EntityManagerWrapper(em));
+ ctx.setPersistenceUnitName("default");
+
+ // We're managing the EM's lifecycle, so we must inform Olingo that it should not
+ // try to manage transactions and/or persistence sessions
+ ctx.setContainerManaged(true);
+ return ctx;
+ }
+
+ static class EntityManagerWrapper implements EntityManager {
+
+ private EntityManager delegate;
+
+ public void persist(Object entity) {
+ log.info("[I68] persist: entity.class=" + entity.getClass()
+ .getSimpleName());
+ delegate.persist(entity);
+ // delegate.flush();
+ }
+
+ public T merge(T entity) {
+ log.info("[I74] merge: entity.class=" + entity.getClass()
+ .getSimpleName());
+ return delegate.merge(entity);
+ }
+
+ public void remove(Object entity) {
+ log.info("[I78] remove: entity.class=" + entity.getClass()
+ .getSimpleName());
+ delegate.remove(entity);
+ }
+
+ public T find(Class entityClass, Object primaryKey) {
+ return delegate.find(entityClass, primaryKey);
+ }
+
+ public T find(Class entityClass, Object primaryKey, Map properties) {
+ return delegate.find(entityClass, primaryKey, properties);
+ }
+
+ public T find(Class entityClass, Object primaryKey, LockModeType lockMode) {
+ return delegate.find(entityClass, primaryKey, lockMode);
+ }
+
+ public T find(Class entityClass, Object primaryKey, LockModeType lockMode, Map properties) {
+ return delegate.find(entityClass, primaryKey, lockMode, properties);
+ }
+
+ public T getReference(Class entityClass, Object primaryKey) {
+ return delegate.getReference(entityClass, primaryKey);
+ }
+
+ public void flush() {
+ delegate.flush();
+ }
+
+ public void setFlushMode(FlushModeType flushMode) {
+ delegate.setFlushMode(flushMode);
+ }
+
+ public FlushModeType getFlushMode() {
+ return delegate.getFlushMode();
+ }
+
+ public void lock(Object entity, LockModeType lockMode) {
+ delegate.lock(entity, lockMode);
+ }
+
+ public void lock(Object entity, LockModeType lockMode, Map properties) {
+ delegate.lock(entity, lockMode, properties);
+ }
+
+ public void refresh(Object entity) {
+ delegate.refresh(entity);
+ }
+
+ public void refresh(Object entity, Map properties) {
+ delegate.refresh(entity, properties);
+ }
+
+ public void refresh(Object entity, LockModeType lockMode) {
+ delegate.refresh(entity, lockMode);
+ }
+
+ public void refresh(Object entity, LockModeType lockMode, Map properties) {
+ delegate.refresh(entity, lockMode, properties);
+ }
+
+ public void clear() {
+ delegate.clear();
+ }
+
+ public void detach(Object entity) {
+ delegate.detach(entity);
+ }
+
+ public boolean contains(Object entity) {
+ return delegate.contains(entity);
+ }
+
+ public LockModeType getLockMode(Object entity) {
+ return delegate.getLockMode(entity);
+ }
+
+ public void setProperty(String propertyName, Object value) {
+ delegate.setProperty(propertyName, value);
+ }
+
+ public Map getProperties() {
+ return delegate.getProperties();
+ }
+
+ public Query createQuery(String qlString) {
+ return delegate.createQuery(qlString);
+ }
+
+ public TypedQuery createQuery(CriteriaQuery criteriaQuery) {
+ return delegate.createQuery(criteriaQuery);
+ }
+
+ public Query createQuery(CriteriaUpdate updateQuery) {
+ return delegate.createQuery(updateQuery);
+ }
+
+ public Query createQuery(CriteriaDelete deleteQuery) {
+ return delegate.createQuery(deleteQuery);
+ }
+
+ public TypedQuery createQuery(String qlString, Class resultClass) {
+ return delegate.createQuery(qlString, resultClass);
+ }
+
+ public Query createNamedQuery(String name) {
+ return delegate.createNamedQuery(name);
+ }
+
+ public TypedQuery createNamedQuery(String name, Class resultClass) {
+ return delegate.createNamedQuery(name, resultClass);
+ }
+
+ public Query createNativeQuery(String sqlString) {
+ return delegate.createNativeQuery(sqlString);
+ }
+
+ public Query createNativeQuery(String sqlString, Class resultClass) {
+ return delegate.createNativeQuery(sqlString, resultClass);
+ }
+
+ public Query createNativeQuery(String sqlString, String resultSetMapping) {
+ return delegate.createNativeQuery(sqlString, resultSetMapping);
+ }
+
+ public StoredProcedureQuery createNamedStoredProcedureQuery(String name) {
+ return delegate.createNamedStoredProcedureQuery(name);
+ }
+
+ public StoredProcedureQuery createStoredProcedureQuery(String procedureName) {
+ return delegate.createStoredProcedureQuery(procedureName);
+ }
+
+ public StoredProcedureQuery createStoredProcedureQuery(String procedureName, Class... resultClasses) {
+ return delegate.createStoredProcedureQuery(procedureName, resultClasses);
+ }
+
+ public StoredProcedureQuery createStoredProcedureQuery(String procedureName, String... resultSetMappings) {
+ return delegate.createStoredProcedureQuery(procedureName, resultSetMappings);
+ }
+
+ public void joinTransaction() {
+ delegate.joinTransaction();
+ }
+
+ public boolean isJoinedToTransaction() {
+ return delegate.isJoinedToTransaction();
+ }
+
+ public T unwrap(Class cls) {
+ return delegate.unwrap(cls);
+ }
+
+ public Object getDelegate() {
+ return delegate.getDelegate();
+ }
+
+ public void close() {
+ log.info("[I229] close");
+ delegate.close();
+ }
+
+ public boolean isOpen() {
+ boolean isOpen = delegate.isOpen();
+ log.info("[I236] isOpen: " + isOpen);
+ return isOpen;
+ }
+
+ public EntityTransaction getTransaction() {
+ log.info("[I240] getTransaction()");
+ return delegate.getTransaction();
+ }
+
+ public EntityManagerFactory getEntityManagerFactory() {
+ return delegate.getEntityManagerFactory();
+ }
+
+ public CriteriaBuilder getCriteriaBuilder() {
+ return delegate.getCriteriaBuilder();
+ }
+
+ public Metamodel getMetamodel() {
+ return delegate.getMetamodel();
+ }
+
+ public EntityGraph createEntityGraph(Class rootType) {
+ return delegate.createEntityGraph(rootType);
+ }
+
+ public EntityGraph> createEntityGraph(String graphName) {
+ return delegate.createEntityGraph(graphName);
+ }
+
+ public EntityGraph> getEntityGraph(String graphName) {
+ return delegate.getEntityGraph(graphName);
+ }
+
+ public List> getEntityGraphs(Class entityClass) {
+ return delegate.getEntityGraphs(entityClass);
+ }
+
+ public EntityManagerWrapper(EntityManager delegate) {
+ this.delegate = delegate;
+ }
+
+ }
+
+}
diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java
new file mode 100644
index 0000000000..78caf99861
--- /dev/null
+++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/JerseyConfig.java
@@ -0,0 +1,125 @@
+ package org.baeldung.examples.olingo2;
+
+import java.io.IOException;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.servlet.ServletContext;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.ApplicationPath;
+import javax.ws.rs.Path;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.container.ContainerResponseContext;
+import javax.ws.rs.container.ContainerResponseFilter;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.ext.Provider;
+
+import org.apache.olingo.odata2.api.ODataServiceFactory;
+import org.apache.olingo.odata2.core.rest.ODataRootLocator;
+import org.apache.olingo.odata2.core.rest.app.ODataApplication;
+import org.glassfish.jersey.server.ResourceConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+/**
+ * Jersey JAX-RS configuration
+ * @author Philippe
+ *
+ */
+@Component
+@ApplicationPath("/odata")
+public class JerseyConfig extends ResourceConfig {
+
+
+ public JerseyConfig(CarsODataJPAServiceFactory serviceFactory, EntityManagerFactory emf) {
+
+ ODataApplication app = new ODataApplication();
+
+ app
+ .getClasses()
+ .forEach( c -> {
+ // Avoid using the default RootLocator, as we want
+ // a Spring Managed one
+ if ( !ODataRootLocator.class.isAssignableFrom(c)) {
+ register(c);
+ }
+ });
+
+ register(new CarsRootLocator(serviceFactory));
+ register( new EntityManagerFilter(emf));
+ }
+
+ /**
+ * This filter handles the EntityManager transaction lifecycle.
+ * @author Philippe
+ *
+ */
+ @Provider
+ public static class EntityManagerFilter implements ContainerRequestFilter, ContainerResponseFilter {
+
+ private static final Logger log = LoggerFactory.getLogger(EntityManagerFilter.class);
+ public static final String EM_REQUEST_ATTRIBUTE = EntityManagerFilter.class.getName() + "_ENTITY_MANAGER";
+
+ private final EntityManagerFactory emf;
+
+ @Context
+ private HttpServletRequest httpRequest;
+
+ public EntityManagerFilter(EntityManagerFactory emf) {
+ this.emf = emf;
+ }
+
+ @Override
+ public void filter(ContainerRequestContext ctx) throws IOException {
+ log.info("[I60] >>> filter");
+ EntityManager em = this.emf.createEntityManager();
+ httpRequest.setAttribute(EM_REQUEST_ATTRIBUTE, em);
+
+ // Start a new transaction unless we have a simple GET
+ if (!"GET".equalsIgnoreCase(ctx.getMethod())) {
+ em.getTransaction()
+ .begin();
+ }
+ }
+
+ @Override
+ public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
+
+ log.info("[I68] <<< filter");
+ EntityManager em = (EntityManager) httpRequest.getAttribute(EM_REQUEST_ATTRIBUTE);
+
+ if (!"GET".equalsIgnoreCase(requestContext.getMethod())) {
+ EntityTransaction t = em.getTransaction();
+ if (t.isActive()) {
+ if (!t.getRollbackOnly()) {
+ t.commit();
+ }
+ }
+ }
+
+ em.close();
+
+ }
+
+ }
+
+ @Path("/")
+ public static class CarsRootLocator extends ODataRootLocator {
+
+ private CarsODataJPAServiceFactory serviceFactory;
+
+ public CarsRootLocator(CarsODataJPAServiceFactory serviceFactory) {
+ this.serviceFactory = serviceFactory;
+ }
+
+ @Override
+ public ODataServiceFactory getServiceFactory() {
+ return this.serviceFactory;
+ }
+
+ }
+
+}
diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java
new file mode 100644
index 0000000000..fa58612088
--- /dev/null
+++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/Olingo2SampleApplication.java
@@ -0,0 +1,14 @@
+package org.baeldung.examples.olingo2;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.builder.SpringApplicationBuilder;
+import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
+
+@SpringBootApplication
+public class Olingo2SampleApplication extends SpringBootServletInitializer {
+
+ public static void main(String[] args) {
+ SpringApplication.run(Olingo2SampleApplication.class);
+ }
+}
diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java
new file mode 100644
index 0000000000..e66d266062
--- /dev/null
+++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarMaker.java
@@ -0,0 +1,115 @@
+package org.baeldung.examples.olingo2.domain;
+
+import java.util.List;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+import javax.validation.constraints.NotNull;
+
+@Entity
+@Table(name = "car_maker")
+public class CarMaker {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ @NotNull
+ @Column(name = "name")
+ private String name;
+
+ @OneToMany(mappedBy = "maker", orphanRemoval = true, cascade = CascadeType.ALL)
+ private List models;
+
+ /**
+ * @return the id
+ */
+ public Long getId() {
+ return id;
+ }
+
+ /**
+ * @param id the id to set
+ */
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ /**
+ * @return the name
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * @param name the name to set
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * @return the models
+ */
+ public List getModels() {
+ return models;
+ }
+
+ /**
+ * @param models the models to set
+ */
+ public void setModels(List models) {
+ this.models = models;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ result = prime * result + ((models == null) ? 0 : models.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ CarMaker other = (CarMaker) obj;
+ if (id == null) {
+ if (other.id != null)
+ return false;
+ } else if (!id.equals(other.id))
+ return false;
+ if (models == null) {
+ if (other.models != null)
+ return false;
+ } else if (!models.equals(other.models))
+ return false;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
+ }
+
+}
diff --git a/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java
new file mode 100644
index 0000000000..f9f563e01e
--- /dev/null
+++ b/apache-olingo/olingo2/src/main/java/org/baeldung/examples/olingo2/domain/CarModel.java
@@ -0,0 +1,159 @@
+package org.baeldung.examples.olingo2.domain;
+
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.validation.constraints.NotNull;
+
+@Entity
+@Table(name = "car_model")
+public class CarModel {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+ @NotNull
+ private String name;
+
+ @NotNull
+ private Integer year;
+
+ @NotNull
+ private String sku;
+
+ @ManyToOne(optional = false, fetch = FetchType.LAZY)
+ @JoinColumn(name = "maker_fk")
+ private CarMaker maker;
+
+ /**
+ * @return the id
+ */
+ public Long getId() {
+ return id;
+ }
+
+ /**
+ * @param id the id to set
+ */
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ /**
+ * @return the name
+ */
+ public String getName() {
+ return name;
+ }
+
+ /**
+ * @param name the name to set
+ */
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ /**
+ * @return the year
+ */
+ public Integer getYear() {
+ return year;
+ }
+
+ /**
+ * @param year the year to set
+ */
+ public void setYear(Integer year) {
+ this.year = year;
+ }
+
+ /**
+ * @return the sku
+ */
+ public String getSku() {
+ return sku;
+ }
+
+ /**
+ * @param sku the sku to set
+ */
+ public void setSku(String sku) {
+ this.sku = sku;
+ }
+
+ /**
+ * @return the maker
+ */
+ public CarMaker getMaker() {
+ return maker;
+ }
+
+ /**
+ * @param maker the maker to set
+ */
+ public void setMaker(CarMaker maker) {
+ this.maker = maker;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((id == null) ? 0 : id.hashCode());
+ result = prime * result + ((maker == null) ? 0 : maker.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ result = prime * result + ((sku == null) ? 0 : sku.hashCode());
+ result = prime * result + ((year == null) ? 0 : year.hashCode());
+ return result;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ CarModel other = (CarModel) obj;
+ if (id == null) {
+ if (other.id != null)
+ return false;
+ } else if (!id.equals(other.id))
+ return false;
+ if (maker == null) {
+ if (other.maker != null)
+ return false;
+ } else if (!maker.equals(other.maker))
+ return false;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ if (sku == null) {
+ if (other.sku != null)
+ return false;
+ } else if (!sku.equals(other.sku))
+ return false;
+ if (year == null) {
+ if (other.year != null)
+ return false;
+ } else if (!year.equals(other.year))
+ return false;
+ return true;
+ }
+
+}
diff --git a/apache-olingo/olingo2/src/main/resources/application.yml b/apache-olingo/olingo2/src/main/resources/application.yml
new file mode 100644
index 0000000000..71df0c4166
--- /dev/null
+++ b/apache-olingo/olingo2/src/main/resources/application.yml
@@ -0,0 +1,12 @@
+server:
+ port: 8080
+
+spring:
+ jersey:
+ application-path: /odata
+
+ jpa:
+ show-sql: true
+ open-in-view: false
+ hibernate:
+ ddl-auto: update
\ No newline at end of file
diff --git a/apache-olingo/olingo2/src/main/resources/data.sql b/apache-olingo/olingo2/src/main/resources/data.sql
new file mode 100644
index 0000000000..327f2688c5
--- /dev/null
+++ b/apache-olingo/olingo2/src/main/resources/data.sql
@@ -0,0 +1,12 @@
+insert into car_maker(id,name) values (1,'Special Motors');
+insert into car_maker(id,name) values (2,'BWM');
+insert into car_maker(id,name) values (3,'Dolores');
+
+insert into car_model(id,maker_fk,name,sku,year) values(1,1,'Muze','SM001',2018);
+insert into car_model(id,maker_fk,name,sku,year) values(2,1,'Empada','SM002',2008);
+
+insert into car_model(id,maker_fk,name,sku,year) values(4,2,'BWM-100','BWM100',2008);
+insert into car_model(id,maker_fk,name,sku,year) values(5,2,'BWM-200','BWM200',2009);
+insert into car_model(id,maker_fk,name,sku,year) values(6,2,'BWM-300','BWM300',2008);
+
+alter sequence hibernate_sequence restart with 100;
\ No newline at end of file
diff --git a/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java b/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java
new file mode 100644
index 0000000000..687f6ab1ff
--- /dev/null
+++ b/apache-olingo/olingo2/src/test/java/org/baeldung/examples/olingo2/Olingo2SampleApplicationTests.java
@@ -0,0 +1,16 @@
+package org.baeldung.examples.olingo2;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest
+public class Olingo2SampleApplicationTests {
+
+ @Test
+ public void contextLoads() {
+ }
+
+}
diff --git a/apache-olingo/olingo2/src/test/resources/olingo2-queries.json b/apache-olingo/olingo2/src/test/resources/olingo2-queries.json
new file mode 100644
index 0000000000..9fdade6d10
--- /dev/null
+++ b/apache-olingo/olingo2/src/test/resources/olingo2-queries.json
@@ -0,0 +1,256 @@
+{
+ "info": {
+ "_postman_id": "afa8e1e5-ab0e-4f1d-8b99-b7d1f091f975",
+ "name": "OLingo2 - Cars",
+ "schema": "https://schema.getpostman.com/json/collection/v2.0.0/collection.json"
+ },
+ "item": [
+ {
+ "name": "GET Metadata",
+ "request": {
+ "method": "GET",
+ "header": [],
+ "body": {
+ "mode": "raw",
+ "raw": ""
+ },
+ "url": "http://localhost:8080/odata/$metadata"
+ },
+ "response": []
+ },
+ {
+ "name": "GET All CarMakers",
+ "request": {
+ "method": "GET",
+ "header": [],
+ "body": {
+ "mode": "raw",
+ "raw": ""
+ },
+ "url": "http://localhost:8080/odata/CarMakers"
+ },
+ "response": []
+ },
+ {
+ "name": "GET Makers with Pagination",
+ "request": {
+ "method": "GET",
+ "header": [],
+ "body": {
+ "mode": "raw",
+ "raw": ""
+ },
+ "url": {
+ "raw": "http://localhost:8080/odata/CarMakers?$top=1&$orderby=Name&$skip=3",
+ "protocol": "http",
+ "host": [
+ "localhost"
+ ],
+ "port": "8080",
+ "path": [
+ "odata",
+ "CarMakers"
+ ],
+ "query": [
+ {
+ "key": "$top",
+ "value": "1"
+ },
+ {
+ "key": "$orderby",
+ "value": "Name"
+ },
+ {
+ "key": "$skip",
+ "value": "3"
+ }
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "GET Makers and Models",
+ "request": {
+ "method": "GET",
+ "header": [],
+ "body": {
+ "mode": "raw",
+ "raw": ""
+ },
+ "url": {
+ "raw": "http://localhost:8080/odata/CarMakers?$expand=CarModelDetails",
+ "protocol": "http",
+ "host": [
+ "localhost"
+ ],
+ "port": "8080",
+ "path": [
+ "odata",
+ "CarMakers"
+ ],
+ "query": [
+ {
+ "key": "$expand",
+ "value": "CarModelDetails"
+ }
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "GET Makers with filter",
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json",
+ "type": "text"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": ""
+ },
+ "url": {
+ "raw": "http://localhost:8080/odata/CarMakers?$filter=Name eq 'BWM'&$expand=CarModelDetails",
+ "protocol": "http",
+ "host": [
+ "localhost"
+ ],
+ "port": "8080",
+ "path": [
+ "odata",
+ "CarMakers"
+ ],
+ "query": [
+ {
+ "key": "$filter",
+ "value": "Name eq 'BWM'"
+ },
+ {
+ "key": "$expand",
+ "value": "CarModelDetails"
+ }
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Create CarMaker",
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "name": "Content-Type",
+ "value": "application/atom+xml",
+ "type": "text"
+ },
+ {
+ "key": "Accept",
+ "value": "application/atom+xml",
+ "type": "text"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": " \r\n\r\n \r\n 2019-04-02T21:36:47Z\r\n \r\n \r\n \r\n \r\n \r\n \r\n Lucien\r\n \r\n \r\n"
+ },
+ "url": "http://localhost:8080/odata/CarMakers"
+ },
+ "response": []
+ },
+ {
+ "name": "Create CarModel",
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "name": "Content-Type",
+ "type": "text",
+ "value": "application/atom+xml"
+ },
+ {
+ "key": "Accept",
+ "type": "text",
+ "value": "application/atom+xml"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": " \r\n\r\n \r\n 2019-04-02T21:36:47Z\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\t Tata\r\n\t TT101\r\n\t 2018\r\n \r\n \r\n"
+ },
+ "url": "http://localhost:8080/odata/CarModels"
+ },
+ "response": []
+ },
+ {
+ "name": "Update CarMaker",
+ "request": {
+ "method": "PUT",
+ "header": [
+ {
+ "key": "Content-Type",
+ "name": "Content-Type",
+ "type": "text",
+ "value": "application/atom+xml"
+ },
+ {
+ "key": "Accept",
+ "type": "text",
+ "value": "application/atom+xml"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": " \r\n\r\n \r\n 2019-04-02T21:36:47Z\r\n \r\n \r\n \r\n \r\n \r\n \r\n 5\r\n KaiserWagen\r\n \r\n \r\n"
+ },
+ "url": "http://localhost:8080/odata/CarMakers(5L)"
+ },
+ "response": []
+ },
+ {
+ "name": "All CarModels",
+ "request": {
+ "method": "GET",
+ "header": [],
+ "body": {
+ "mode": "raw",
+ "raw": ""
+ },
+ "url": "http://localhost:8080/odata/CarModels"
+ },
+ "response": []
+ },
+ {
+ "name": "Delete CarModel",
+ "request": {
+ "method": "DELETE",
+ "header": [
+ {
+ "key": "Content-Type",
+ "name": "Content-Type",
+ "type": "text",
+ "value": "application/atom+xml"
+ },
+ {
+ "key": "Accept",
+ "type": "text",
+ "value": "application/atom+xml"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": ""
+ },
+ "url": "http://localhost:8080/odata/CarModels(100L)"
+ },
+ "response": []
+ }
+ ]
+}
\ No newline at end of file
diff --git a/apache-velocity/pom.xml b/apache-velocity/pom.xml
index a0a8389f7d..24ab0b861d 100644
--- a/apache-velocity/pom.xml
+++ b/apache-velocity/pom.xml
@@ -59,7 +59,6 @@
- 1.2
4.5.2
1.7
2.0
diff --git a/autovalue/src/main/java/com/baeldung/autofactory/provided/IntermediateAssembler.java b/autovalue/src/main/java/com/baeldung/autofactory/provided/IntermediateAssembler.java
index e0ee8879a5..65d0eb6f58 100644
--- a/autovalue/src/main/java/com/baeldung/autofactory/provided/IntermediateAssembler.java
+++ b/autovalue/src/main/java/com/baeldung/autofactory/provided/IntermediateAssembler.java
@@ -1,8 +1,9 @@
package com.baeldung.autofactory.provided;
+import com.baeldung.autofactory.model.Camera;
import com.google.auto.factory.AutoFactory;
import com.google.auto.factory.Provided;
-import javafx.scene.Camera;
+
import javax.inject.Provider;
diff --git a/aws/README.md b/aws/README.md
index 2c61928095..d14ea8a75e 100644
--- a/aws/README.md
+++ b/aws/README.md
@@ -4,7 +4,6 @@
- [AWS S3 with Java](http://www.baeldung.com/aws-s3-java)
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
- [Managing EC2 Instances in Java](http://www.baeldung.com/ec2-java)
-- [http://www.baeldung.com/aws-s3-multipart-upload](https://github.com/eugenp/tutorials/tree/master/aws)
- [Multipart Uploads in Amazon S3 with Java](http://www.baeldung.com/aws-s3-multipart-upload)
- [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests)
- [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3)
diff --git a/azure/README.md b/azure/README.md
index c60186e1ce..ae8c443660 100644
--- a/azure/README.md
+++ b/azure/README.md
@@ -1,4 +1,4 @@
### Relevant Articles:
-- [Deploy Spring Boot App to Azure](http://www.baeldung.com/spring-boot-azure)
+- [Deploy a Spring Boot App to Azure](http://www.baeldung.com/spring-boot-azure)
diff --git a/blade/README.md b/blade/README.md
index d823de775f..1f2a00ed3f 100644
--- a/blade/README.md
+++ b/blade/README.md
@@ -1,5 +1,5 @@
### Relevant Articles:
-- [Blade - A Complete GuideBook](http://www.baeldung.com/blade)
+- [Blade – A Complete Guidebook](http://www.baeldung.com/blade)
-Run Integration Tests with `mvn integration-test`
\ No newline at end of file
+Run Integration Tests with `mvn integration-test`
diff --git a/cas/pom.xml b/cas/pom.xml
new file mode 100644
index 0000000000..6d141277c5
--- /dev/null
+++ b/cas/pom.xml
@@ -0,0 +1,21 @@
+
+
+ 4.0.0
+ cas
+ cas
+ pom
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+ ..
+
+
+
+ cas-secured-app
+ cas-server
+
+
+
diff --git a/cdi/pom.xml b/cdi/pom.xml
index 85da8518d0..c98ad57495 100644
--- a/cdi/pom.xml
+++ b/cdi/pom.xml
@@ -27,7 +27,7 @@
org.hamcrest
hamcrest-core
- ${hamcrest-core.version}
+ ${org.hamcrest.version}
test
@@ -64,7 +64,6 @@
2.0.SP1
3.0.5.Final
1.9.2
- 1.3
3.10.0
5.1.2.RELEASE
diff --git a/clojure/ring/.gitignore b/clojure/ring/.gitignore
new file mode 100644
index 0000000000..d18f225992
--- /dev/null
+++ b/clojure/ring/.gitignore
@@ -0,0 +1,12 @@
+/target
+/classes
+/checkouts
+profiles.clj
+pom.xml
+pom.xml.asc
+*.jar
+*.class
+/.lein-*
+/.nrepl-port
+.hgignore
+.hg/
diff --git a/clojure/ring/README.md b/clojure/ring/README.md
new file mode 100644
index 0000000000..20263c6b95
--- /dev/null
+++ b/clojure/ring/README.md
@@ -0,0 +1,19 @@
+# Clojure Ring Examples
+
+This project acts as a set of examples for the Clojure Ring library.
+
+## Runing the examples
+
+The examples can all be run from the Leiningen REPL.
+
+Firstly, start the REPL with `lein repl`. Then the examples can be executed with:
+
+* `(run simple-handler)` - A simple handler that just echos a constant string to the client
+* `(run check-ip-handler)` - A handler that echos the clients IP Address back to them
+* `(run echo-handler)` - A handler that echos the value of the "input" parameter back
+* `(run request-count-handler)` - A handler with a session that tracks how many times this session has requested this handler
+
+In all cases, the handlers can be accessed on http://localhost:3000.
+
+## Relevant Articles
+- [Writing Clojure Webapps with Ring](https://www.baeldung.com/clojure-ring)
diff --git a/clojure/ring/project.clj b/clojure/ring/project.clj
new file mode 100644
index 0000000000..7f2fcc4263
--- /dev/null
+++ b/clojure/ring/project.clj
@@ -0,0 +1,8 @@
+(defproject baeldung-ring "0.1.0-SNAPSHOT"
+ :dependencies [[org.clojure/clojure "1.10.0"]
+ [ring/ring-core "1.7.1"]
+ [ring/ring-jetty-adapter "1.7.1"]
+ [ring/ring-devel "1.7.1"]]
+ :plugins [[lein-ring "0.12.5"]]
+ :ring {:handler ring.core/simple-handler}
+ :repl-options {:init-ns ring.core})
diff --git a/clojure/ring/src/ring/core.clj b/clojure/ring/src/ring/core.clj
new file mode 100644
index 0000000000..a56e2f2bde
--- /dev/null
+++ b/clojure/ring/src/ring/core.clj
@@ -0,0 +1,48 @@
+(ns ring.core
+ (:use ring.adapter.jetty
+ [ring.middleware.content-type]
+ [ring.middleware.cookies]
+ [ring.middleware.params]
+ [ring.middleware.session]
+ [ring.middleware.session.cookie]
+ [ring.util.response]))
+
+;; Handler that just echos back the string "Hello World"
+(defn simple-handler [request]
+ {:status 200
+ :headers {"Content-Type" "text/plain"}
+ :body "Hello World"})
+
+;; Handler that echos back the clients IP Address
+;; This demonstrates building responses properly, and extracting values from the request
+(defn check-ip-handler [request]
+ (content-type
+ (response (:remote-addr request))
+ "text/plain"))
+
+;; Handler that echos back the incoming parameter "input"
+;; This demonstrates middleware chaining and accessing parameters
+(def echo-handler
+ (-> (fn [{params :params}]
+ (content-type
+ (response (get params "input"))
+ "text/plain"))
+ (wrap-params {:encoding "UTF-8"})
+ ))
+
+;; Handler that keeps track of how many times each session has accessed the service
+;; This demonstrates cookies and sessions
+(def request-count-handler
+ (-> (fn [{session :session}]
+ (let [count (:count session 0)
+ session (assoc session :count (inc count))]
+ (-> (response (str "You accessed this page " count " times."))
+ (assoc :session session))))
+ wrap-cookies
+ (wrap-session {:cookie-attrs {:max-age 3600}})
+ ))
+
+;; Run the provided handler on port 3000
+(defn run
+ [h]
+ (run-jetty h {:port 3000}))
diff --git a/cloud-foundry-uaa/README.md b/cloud-foundry-uaa/README.md
new file mode 100644
index 0000000000..b2f382cad1
--- /dev/null
+++ b/cloud-foundry-uaa/README.md
@@ -0,0 +1,3 @@
+### Revelant Articles
+
+- [A Quick Guide To Using Cloud Foundry UAA](https://www.baeldung.com/cloud-foundry-uaa)
diff --git a/cloud-foundry-uaa/cf-uaa-config/uaa.yml b/cloud-foundry-uaa/cf-uaa-config/uaa.yml
new file mode 100644
index 0000000000..ebaa99fb6c
--- /dev/null
+++ b/cloud-foundry-uaa/cf-uaa-config/uaa.yml
@@ -0,0 +1,68 @@
+issuer:
+ uri: http://localhost:8080/uaa
+
+spring_profiles: default,hsqldb
+
+encryption:
+ active_key_label: CHANGE-THIS-KEY
+ encryption_keys:
+ - label: CHANGE-THIS-KEY
+ passphrase: CHANGEME
+
+login:
+ serviceProviderKey: |
+ -----BEGIN RSA PRIVATE KEY-----
+ MIICXQIBAAKBgQDHtC5gUXxBKpEqZTLkNvFwNGnNIkggNOwOQVNbpO0WVHIivig5
+ L39WqS9u0hnA+O7MCA/KlrAR4bXaeVVhwfUPYBKIpaaTWFQR5cTR1UFZJL/OF9vA
+ fpOwznoD66DDCnQVpbCjtDYWX+x6imxn8HCYxhMol6ZnTbSsFW6VZjFMjQIDAQAB
+ AoGAVOj2Yvuigi6wJD99AO2fgF64sYCm/BKkX3dFEw0vxTPIh58kiRP554Xt5ges
+ 7ZCqL9QpqrChUikO4kJ+nB8Uq2AvaZHbpCEUmbip06IlgdA440o0r0CPo1mgNxGu
+ lhiWRN43Lruzfh9qKPhleg2dvyFGQxy5Gk6KW/t8IS4x4r0CQQD/dceBA+Ndj3Xp
+ ubHfxqNz4GTOxndc/AXAowPGpge2zpgIc7f50t8OHhG6XhsfJ0wyQEEvodDhZPYX
+ kKBnXNHzAkEAyCA76vAwuxqAd3MObhiebniAU3SnPf2u4fdL1EOm92dyFs1JxyyL
+ gu/DsjPjx6tRtn4YAalxCzmAMXFSb1qHfwJBAM3qx3z0gGKbUEWtPHcP7BNsrnWK
+ vw6By7VC8bk/ffpaP2yYspS66Le9fzbFwoDzMVVUO/dELVZyBnhqSRHoXQcCQQCe
+ A2WL8S5o7Vn19rC0GVgu3ZJlUrwiZEVLQdlrticFPXaFrn3Md82ICww3jmURaKHS
+ N+l4lnMda79eSp3OMmq9AkA0p79BvYsLshUJJnvbk76pCjR28PK4dV1gSDUEqQMB
+ qy45ptdwJLqLJCeNoR0JUcDNIRhOCuOPND7pcMtX6hI/
+ -----END RSA PRIVATE KEY-----
+ serviceProviderKeyPassword: password
+ serviceProviderCertificate: |
+ -----BEGIN CERTIFICATE-----
+ MIIDSTCCArKgAwIBAgIBADANBgkqhkiG9w0BAQQFADB8MQswCQYDVQQGEwJhdzEO
+ MAwGA1UECBMFYXJ1YmExDjAMBgNVBAoTBWFydWJhMQ4wDAYDVQQHEwVhcnViYTEO
+ MAwGA1UECxMFYXJ1YmExDjAMBgNVBAMTBWFydWJhMR0wGwYJKoZIhvcNAQkBFg5h
+ cnViYUBhcnViYS5hcjAeFw0xNTExMjAyMjI2MjdaFw0xNjExMTkyMjI2MjdaMHwx
+ CzAJBgNVBAYTAmF3MQ4wDAYDVQQIEwVhcnViYTEOMAwGA1UEChMFYXJ1YmExDjAM
+ BgNVBAcTBWFydWJhMQ4wDAYDVQQLEwVhcnViYTEOMAwGA1UEAxMFYXJ1YmExHTAb
+ BgkqhkiG9w0BCQEWDmFydWJhQGFydWJhLmFyMIGfMA0GCSqGSIb3DQEBAQUAA4GN
+ ADCBiQKBgQDHtC5gUXxBKpEqZTLkNvFwNGnNIkggNOwOQVNbpO0WVHIivig5L39W
+ qS9u0hnA+O7MCA/KlrAR4bXaeVVhwfUPYBKIpaaTWFQR5cTR1UFZJL/OF9vAfpOw
+ znoD66DDCnQVpbCjtDYWX+x6imxn8HCYxhMol6ZnTbSsFW6VZjFMjQIDAQABo4Ha
+ MIHXMB0GA1UdDgQWBBTx0lDzjH/iOBnOSQaSEWQLx1syGDCBpwYDVR0jBIGfMIGc
+ gBTx0lDzjH/iOBnOSQaSEWQLx1syGKGBgKR+MHwxCzAJBgNVBAYTAmF3MQ4wDAYD
+ VQQIEwVhcnViYTEOMAwGA1UEChMFYXJ1YmExDjAMBgNVBAcTBWFydWJhMQ4wDAYD
+ VQQLEwVhcnViYTEOMAwGA1UEAxMFYXJ1YmExHTAbBgkqhkiG9w0BCQEWDmFydWJh
+ QGFydWJhLmFyggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEEBQADgYEAYvBJ
+ 0HOZbbHClXmGUjGs+GS+xC1FO/am2suCSYqNB9dyMXfOWiJ1+TLJk+o/YZt8vuxC
+ KdcZYgl4l/L6PxJ982SRhc83ZW2dkAZI4M0/Ud3oePe84k8jm3A7EvH5wi5hvCkK
+ RpuRBwn3Ei+jCRouxTbzKPsuCVB+1sNyxMTXzf0=
+ -----END CERTIFICATE-----
+
+#The secret that an external login server will use to authenticate to the uaa using the id `login`
+LOGIN_SECRET: loginsecret
+
+jwt:
+ token:
+ signing-key: |
+ -----BEGIN RSA PRIVATE KEY-----
+ MIIEpAIBAAKCAQEAqUeygEfDGxI6c1VDQ6xIyUSLrP6iz1y97iHFbtXSxXaArL4a
+ ...
+ v6Mtt5LcRAAVP7pemunTdju4h8Q/noKYlVDVL30uLYUfKBL4UKfOBw==
+ -----END RSA PRIVATE KEY-----
+ verification-key: |
+ -----BEGIN PUBLIC KEY-----
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqUeygEfDGxI6c1VDQ6xI
+ ...
+ AwIDAQAB
+ -----END PUBLIC KEY-----
diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml b/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml
new file mode 100644
index 0000000000..c6de00dbe9
--- /dev/null
+++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/pom.xml
@@ -0,0 +1,38 @@
+
+
+ 4.0.0
+ com.example
+ cf-uaa-oauth2-client
+ 0.0.1-SNAPSHOT
+ uaa-client-webapp
+ Demo project for Spring Boot
+
+
+ parent-boot-2
+ com.baeldung
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-2
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-oauth2-client
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientApplication.java b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientApplication.java
new file mode 100644
index 0000000000..c9e81fcd5d
--- /dev/null
+++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.cfuaa.oauth2.client;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class CFUAAOAuth2ClientApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(CFUAAOAuth2ClientApplication.class, args);
+ }
+
+}
diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientController.java b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientController.java
new file mode 100644
index 0000000000..b1631ed327
--- /dev/null
+++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/java/com/baeldung/cfuaa/oauth2/client/CFUAAOAuth2ClientController.java
@@ -0,0 +1,80 @@
+package com.baeldung.cfuaa.oauth2.client;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
+import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
+import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
+import org.springframework.security.oauth2.core.OAuth2AccessToken;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.HttpClientErrorException;
+import org.springframework.web.client.RestTemplate;
+
+@RestController
+public class CFUAAOAuth2ClientController {
+
+ @Value("${resource.server.url}")
+ private String remoteResourceServer;
+
+ private RestTemplate restTemplate;
+
+ private OAuth2AuthorizedClientService authorizedClientService;
+
+ public CFUAAOAuth2ClientController(OAuth2AuthorizedClientService authorizedClientService) {
+ this.authorizedClientService = authorizedClientService;
+ this.restTemplate = new RestTemplate();
+ }
+
+ @RequestMapping("/")
+ public String index(OAuth2AuthenticationToken authenticationToken) {
+ OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
+ OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();
+
+ String response = "Hello, " + authenticationToken.getPrincipal().getName();
+ response += "";
+ response += "Here is your accees token :" + oAuth2AccessToken.getTokenValue();
+ response += "";
+ response += "You can use it to call these Resource Server APIs:";
+ response += "";
+ response += "Call Resource Server Read API";
+ response += "";
+ response += "Call Resource Server Write API";
+ return response;
+ }
+
+ @RequestMapping("/read")
+ public String read(OAuth2AuthenticationToken authenticationToken) {
+ String url = remoteResourceServer + "/read";
+ return callResourceServer(authenticationToken, url);
+ }
+
+ @RequestMapping("/write")
+ public String write(OAuth2AuthenticationToken authenticationToken) {
+ String url = remoteResourceServer + "/write";
+ return callResourceServer(authenticationToken, url);
+ }
+
+ private String callResourceServer(OAuth2AuthenticationToken authenticationToken, String url) {
+ OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
+ OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();
+
+ HttpHeaders headers = new HttpHeaders();
+ headers.add("Authorization", "Bearer " + oAuth2AccessToken.getTokenValue());
+
+ HttpEntity entity = new HttpEntity<>("parameters", headers);
+ ResponseEntity responseEntity = null;
+
+ String response = null;
+ try {
+ responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
+ response = responseEntity.getBody();
+ } catch (HttpClientErrorException e) {
+ response = e.getMessage();
+ }
+ return response;
+ }
+}
\ No newline at end of file
diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/application.properties b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/application.properties
new file mode 100644
index 0000000000..8e8797ce54
--- /dev/null
+++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/application.properties
@@ -0,0 +1,11 @@
+server.port=8081
+
+resource.server.url=http://localhost:8082
+
+spring.security.oauth2.client.registration.uaa.client-name=Web App Client
+spring.security.oauth2.client.registration.uaa.client-id=webappclient
+spring.security.oauth2.client.registration.uaa.client-secret=webappclientsecret
+spring.security.oauth2.client.registration.uaa.scope=resource.read,resource.write,openid,profile
+
+spring.security.oauth2.client.provider.uaa.issuer-uri=http://localhost:8080/uaa/oauth/token
+
diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/templates/index.html b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/templates/index.html
new file mode 100644
index 0000000000..eb6e267b94
--- /dev/null
+++ b/cloud-foundry-uaa/cf-uaa-oauth2-client/src/main/resources/templates/index.html
@@ -0,0 +1 @@
+tintin
\ No newline at end of file
diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml
new file mode 100644
index 0000000000..56fb23e9d8
--- /dev/null
+++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/pom.xml
@@ -0,0 +1,38 @@
+
+
+ 4.0.0
+ com.baeldung.cfuaa
+ cf-uaa-oauth2-resource-server
+ 0.0.1-SNAPSHOT
+ cf-uaa-oauth2-resource-server
+ Demo project for Spring Boot
+
+
+ parent-boot-2
+ com.baeldung
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-2
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-oauth2-resource-server
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerApplication.java b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerApplication.java
new file mode 100644
index 0000000000..51ad6e938d
--- /dev/null
+++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.cfuaa.oauth2.resourceserver;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class CFUAAOAuth2ResourceServerApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(CFUAAOAuth2ResourceServerApplication.class, args);
+ }
+
+}
diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerRestController.java b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerRestController.java
new file mode 100644
index 0000000000..c08f17d8d8
--- /dev/null
+++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerRestController.java
@@ -0,0 +1,28 @@
+package com.baeldung.cfuaa.oauth2.resourceserver;
+
+import org.springframework.security.core.annotation.AuthenticationPrincipal;
+import org.springframework.security.oauth2.jwt.Jwt;
+import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.security.Principal;
+
+@RestController
+public class CFUAAOAuth2ResourceServerRestController {
+
+ @GetMapping("/")
+ public String index(@AuthenticationPrincipal Jwt jwt) {
+ return String.format("Hello, %s!", jwt.getSubject());
+ }
+
+ @GetMapping("/read")
+ public String read(JwtAuthenticationToken jwtAuthenticationToken) {
+ return "Hello write: " + jwtAuthenticationToken.getTokenAttributes();
+ }
+
+ @GetMapping("/write")
+ public String write(Principal principal) {
+ return "Hello write: " + principal.getName();
+ }
+}
diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerSecurityConfiguration.java b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerSecurityConfiguration.java
new file mode 100644
index 0000000000..d04d51cda3
--- /dev/null
+++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/java/com/baeldung/cfuaa/oauth2/resourceserver/CFUAAOAuth2ResourceServerSecurityConfiguration.java
@@ -0,0 +1,21 @@
+package com.baeldung.cfuaa.oauth2.resourceserver;
+
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+
+@EnableWebSecurity
+public class CFUAAOAuth2ResourceServerSecurityConfiguration extends WebSecurityConfigurerAdapter {
+
+ @Override
+ protected void configure(HttpSecurity http) throws Exception {
+ http
+ .authorizeRequests()
+ .antMatchers("/read/**").hasAuthority("SCOPE_resource.read")
+ .antMatchers("/write/**").hasAuthority("SCOPE_resource.write")
+ .anyRequest().authenticated()
+ .and()
+ .oauth2ResourceServer()
+ .jwt();
+ }
+}
\ No newline at end of file
diff --git a/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/resources/application.properties b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/resources/application.properties
new file mode 100644
index 0000000000..a6e846a00f
--- /dev/null
+++ b/cloud-foundry-uaa/cf-uaa-oauth2-resource-server/src/main/resources/application.properties
@@ -0,0 +1,3 @@
+server.port=8082
+
+spring.security.oauth2.resourceserver.jwt.issuer-uri=http://localhost:8080/uaa/oauth/token
diff --git a/core-groovy-2/README.md b/core-groovy-2/README.md
new file mode 100644
index 0000000000..1d35669cd7
--- /dev/null
+++ b/core-groovy-2/README.md
@@ -0,0 +1,8 @@
+# Groovy
+
+## Relevant articles:
+
+- [String Matching in Groovy](http://www.baeldung.com/)
+- [Template Engines in Groovy](https://www.baeldung.com/groovy-template-engines)
+- [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword)
+- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
\ No newline at end of file
diff --git a/core-groovy-2/gmavenplus-pom.xml b/core-groovy-2/gmavenplus-pom.xml
new file mode 100644
index 0000000000..54c89b9834
--- /dev/null
+++ b/core-groovy-2/gmavenplus-pom.xml
@@ -0,0 +1,178 @@
+
+
+ 4.0.0
+ core-groovy-2
+ 1.0-SNAPSHOT
+ core-groovy-2
+ jar
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+ ch.qos.logback
+ logback-classic
+ ${logback.version}
+
+
+ org.codehaus.groovy
+ groovy-all
+ ${groovy.version}
+ pom
+
+
+ org.junit.platform
+ junit-platform-runner
+ ${junit.platform.version}
+ test
+
+
+ org.hsqldb
+ hsqldb
+ ${hsqldb.version}
+ test
+
+
+ org.spockframework
+ spock-core
+ ${spock-core.version}
+ test
+
+
+
+
+ src/main/groovy
+ src/main/java
+
+
+ org.codehaus.gmavenplus
+ gmavenplus-plugin
+ 1.7.0
+
+
+
+ execute
+ addSources
+ addTestSources
+ generateStubs
+ compile
+ generateTestStubs
+ compileTests
+ removeStubs
+ removeTestStubs
+
+
+
+
+
+ org.codehaus.groovy
+ groovy-all
+
+ ${groovy.version}
+ runtime
+ pom
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ maven-failsafe-plugin
+ ${maven-failsafe-plugin.version}
+
+
+ org.junit.platform
+ junit-platform-surefire-provider
+ ${junit.platform.version}
+
+
+
+
+ junit5
+
+ integration-test
+ verify
+
+
+
+ **/*Test5.java
+
+
+
+
+
+
+ maven-surefire-plugin
+ 2.20.1
+
+ false
+
+ **/*Test.java
+ **/*Spec.java
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+ 3.1.0
+
+
+
+ jar-with-dependencies
+
+
+
+
+ com.baeldung.MyJointCompilationApp
+
+
+
+
+
+
+ make-assembly
+
+ package
+
+ single
+
+
+
+
+
+
+
+
+
+ central
+ http://jcenter.bintray.com
+
+
+
+
+ UTF-8
+ 1.0.0
+ 2.4.0
+ 1.1-groovy-2.4
+ 3.9
+ 1.8
+ 1.2.3
+ 2.5.7
+ 1.6
+
+
+
diff --git a/core-groovy-2/pom.xml b/core-groovy-2/pom.xml
new file mode 100644
index 0000000000..b945546c8a
--- /dev/null
+++ b/core-groovy-2/pom.xml
@@ -0,0 +1,187 @@
+
+
+ 4.0.0
+ core-groovy-2
+ 1.0-SNAPSHOT
+ core-groovy-2
+ jar
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+ ch.qos.logback
+ logback-classic
+ ${logback.version}
+
+
+ org.codehaus.groovy
+ groovy-all
+ ${groovy.version}
+ pom
+
+
+ org.junit.platform
+ junit-platform-runner
+ ${junit.platform.version}
+ test
+
+
+ org.hsqldb
+ hsqldb
+ ${hsqldb.version}
+ test
+
+
+ org.spockframework
+ spock-core
+ ${spock-core.version}
+ test
+
+
+
+
+ src/main/groovy
+ src/main/java
+
+
+ org.codehaus.groovy
+ groovy-eclipse-compiler
+ 3.3.0-01
+ true
+
+
+ maven-compiler-plugin
+ 3.8.0
+
+ groovy-eclipse-compiler
+ ${java.version}
+ ${java.version}
+
+
+
+ org.codehaus.groovy
+ groovy-eclipse-compiler
+ 3.3.0-01
+
+
+ org.codehaus.groovy
+ groovy-eclipse-batch
+ ${groovy.version}-01
+
+
+
+
+ maven-failsafe-plugin
+ ${maven-failsafe-plugin.version}
+
+
+ org.junit.platform
+ junit-platform-surefire-provider
+ ${junit.platform.version}
+
+
+
+
+ junit5
+
+ integration-test
+ verify
+
+
+
+ **/*Test5.java
+
+
+
+
+
+
+ maven-surefire-plugin
+ 2.20.1
+
+ false
+
+ **/*Test.java
+ **/*Spec.java
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-assembly-plugin
+ 3.1.0
+
+
+
+ jar-with-dependencies
+
+
+
+
+ com.baeldung.MyJointCompilationApp
+
+
+
+
+
+
+ make-assembly
+
+ package
+
+ single
+
+
+
+
+
+
+
+
+
+ central
+ http://jcenter.bintray.com
+
+
+
+
+
+ bintray
+ Groovy Bintray
+ https://dl.bintray.com/groovy/maven
+
+
+ never
+
+
+ false
+
+
+
+
+
+
+ 1.0.0
+ 2.4.0
+ 1.1-groovy-2.4
+ 3.9
+ 1.8
+ 3.8.1
+ 1.2.3
+ 2.5.7
+ UTF-8
+
+
+
diff --git a/core-groovy-2/src/main/groovy/com/baeldung/CalcMath.groovy b/core-groovy-2/src/main/groovy/com/baeldung/CalcMath.groovy
new file mode 100644
index 0000000000..0e233793b2
--- /dev/null
+++ b/core-groovy-2/src/main/groovy/com/baeldung/CalcMath.groovy
@@ -0,0 +1,25 @@
+package com.baeldung
+
+import org.slf4j.LoggerFactory
+
+class CalcMath {
+ def log = LoggerFactory.getLogger(this.getClass())
+
+ def calcSum(x, y) {
+ log.info "Executing $x + $y"
+ x + y
+ }
+
+ /**
+ * example of method that in java would throw error at compile time
+ * @param x
+ * @param y
+ * @return
+ */
+ def calcSum2(x, y) {
+ log.info "Executing $x + $y"
+ // DANGER! This won't throw a compilation issue and fail only at runtime!!!
+ calcSum3()
+ log.info("Logging an undefined variable: $z")
+ }
+}
\ No newline at end of file
diff --git a/core-groovy-2/src/main/groovy/com/baeldung/CalcScript.groovy b/core-groovy-2/src/main/groovy/com/baeldung/CalcScript.groovy
new file mode 100644
index 0000000000..84615b2217
--- /dev/null
+++ b/core-groovy-2/src/main/groovy/com/baeldung/CalcScript.groovy
@@ -0,0 +1,16 @@
+package com.baeldung
+
+def calcSum(x, y) {
+ x + y
+}
+
+def calcSum2(x, y) {
+ // DANGER! The variable "log" may be undefined
+ log.info "Executing $x + $y"
+ // DANGER! This method doesn't exist!
+ calcSum3()
+ // DANGER! The logged variable "z" is undefined!
+ log.info("Logging an undefined variable: $z")
+}
+
+calcSum(1,5)
diff --git a/core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java b/core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java
new file mode 100644
index 0000000000..c49f6edc30
--- /dev/null
+++ b/core-groovy-2/src/main/java/com/baeldung/MyJointCompilationApp.java
@@ -0,0 +1,120 @@
+package com.baeldung;
+
+import groovy.lang.*;
+import groovy.util.GroovyScriptEngine;
+import groovy.util.ResourceException;
+import groovy.util.ScriptException;
+import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import javax.script.ScriptEngine;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+/**
+ * Hello world!
+ *
+ */
+public class MyJointCompilationApp {
+ private final static Logger LOG = LoggerFactory.getLogger(MyJointCompilationApp.class);
+ private final GroovyClassLoader loader;
+ private final GroovyShell shell;
+ private final GroovyScriptEngine engine;
+ private final ScriptEngine engineFromFactory;
+
+ public MyJointCompilationApp() {
+ loader = new GroovyClassLoader(this.getClass().getClassLoader());
+ shell = new GroovyShell(loader, new Binding());
+
+ URL url = null;
+ try {
+ url = new File("src/main/groovy/com/baeldung/").toURI().toURL();
+ } catch (MalformedURLException e) {
+ LOG.error("Exception while creating url", e);
+ }
+ engine = new GroovyScriptEngine(new URL[] {url}, this.getClass().getClassLoader());
+ engineFromFactory = new GroovyScriptEngineFactory().getScriptEngine();
+ }
+
+ private void addWithCompiledClasses(int x, int y) {
+ LOG.info("Executing {} + {}", x, y);
+ Object result1 = new CalcScript().calcSum(x, y);
+ LOG.info("Result of CalcScript.calcSum() method is {}", result1);
+
+ Object result2 = new CalcMath().calcSum(x, y);
+ LOG.info("Result of CalcMath.calcSum() method is {}", result2);
+ }
+
+ private void addWithGroovyShell(int x, int y) throws IOException {
+ Script script = shell.parse(new File("src/main/groovy/com/baeldung/", "CalcScript.groovy"));
+ LOG.info("Executing {} + {}", x, y);
+ Object result = script.invokeMethod("calcSum", new Object[] { x, y });
+ LOG.info("Result of CalcScript.calcSum() method is {}", result);
+ }
+
+ private void addWithGroovyShellRun() throws IOException {
+ Script script = shell.parse(new File("src/main/groovy/com/baeldung/", "CalcScript.groovy"));
+ LOG.info("Executing script run method");
+ Object result = script.run();
+ LOG.info("Result of CalcScript.run() method is {}", result);
+ }
+
+ private void addWithGroovyClassLoader(int x, int y) throws IllegalAccessException, InstantiationException, IOException {
+ Class calcClass = loader.parseClass(
+ new File("src/main/groovy/com/baeldung/", "CalcMath.groovy"));
+ GroovyObject calc = (GroovyObject) calcClass.newInstance();
+ Object result = calc.invokeMethod("calcSum", new Object[] { x + 14, y + 14 });
+ LOG.info("Result of CalcMath.calcSum() method is {}", result);
+ }
+
+ private void addWithGroovyScriptEngine(int x, int y) throws IllegalAccessException,
+ InstantiationException, ResourceException, ScriptException {
+ Class calcClass = engine.loadScriptByName("CalcMath.groovy");
+ GroovyObject calc = calcClass.newInstance();
+ //WARNING the following will throw a ClassCastException
+ //((CalcMath)calc).calcSum(1,2);
+ Object result = calc.invokeMethod("calcSum", new Object[] { x, y });
+ LOG.info("Result of CalcMath.calcSum() method is {}", result);
+ }
+
+ private void addWithEngineFactory(int x, int y) throws IllegalAccessException,
+ InstantiationException, javax.script.ScriptException, FileNotFoundException {
+ Class calcClass = (Class) engineFromFactory.eval(
+ new FileReader(new File("src/main/groovy/com/baeldung/", "CalcMath.groovy")));
+ GroovyObject calc = (GroovyObject) calcClass.newInstance();
+ Object result = calc.invokeMethod("calcSum", new Object[] { x, y });
+ LOG.info("Result of CalcMath.calcSum() method is {}", result);
+ }
+
+ private void addWithStaticCompiledClasses() {
+ LOG.info("Running the Groovy classes compiled statically...");
+ addWithCompiledClasses(5, 10);
+
+ }
+
+ private void addWithDynamicCompiledClasses() throws IOException, IllegalAccessException, InstantiationException,
+ ResourceException, ScriptException, javax.script.ScriptException {
+ LOG.info("Invocation of a dynamic groovy script...");
+ addWithGroovyShell(5, 10);
+ LOG.info("Invocation of the run method of a dynamic groovy script...");
+ addWithGroovyShellRun();
+ LOG.info("Invocation of a dynamic groovy class loaded with GroovyClassLoader...");
+ addWithGroovyClassLoader(10, 30);
+ LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine...");
+ addWithGroovyScriptEngine(15, 0);
+ LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine JSR223...");
+ addWithEngineFactory(5, 6);
+ }
+
+ public static void main(String[] args) throws InstantiationException, IllegalAccessException,
+ ResourceException, ScriptException, IOException, javax.script.ScriptException {
+ MyJointCompilationApp myJointCompilationApp = new MyJointCompilationApp();
+ LOG.info("Example of addition operation via Groovy scripts integration with Java.");
+ myJointCompilationApp.addWithStaticCompiledClasses();
+ myJointCompilationApp.addWithDynamicCompiledClasses();
+ }
+}
diff --git a/core-groovy-2/src/main/resources/articleEmail.template b/core-groovy-2/src/main/resources/articleEmail.template
new file mode 100644
index 0000000000..26488f6288
--- /dev/null
+++ b/core-groovy-2/src/main/resources/articleEmail.template
@@ -0,0 +1,5 @@
+Dear <% out << (user) %>,
+Please read the requested article below.
+<% out << (articleText) %>
+From,
+<% out << (signature) %>
\ No newline at end of file
diff --git a/core-groovy-2/src/main/resources/email.template b/core-groovy-2/src/main/resources/email.template
new file mode 100644
index 0000000000..fe4eaff851
--- /dev/null
+++ b/core-groovy-2/src/main/resources/email.template
@@ -0,0 +1,3 @@
+Dear $user,
+Thanks for subscribing our services.
+${signature}
\ No newline at end of file
diff --git a/core-groovy-2/src/test/groovy/com/baeldung/defkeyword/DefUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/defkeyword/DefUnitTest.groovy
new file mode 100644
index 0000000000..310d97d3fd
--- /dev/null
+++ b/core-groovy-2/src/test/groovy/com/baeldung/defkeyword/DefUnitTest.groovy
@@ -0,0 +1,79 @@
+package com.baeldung.defkeyword
+
+import org.codehaus.groovy.runtime.NullObject
+import org.codehaus.groovy.runtime.typehandling.GroovyCastException
+
+import groovy.transform.TypeChecked
+import groovy.transform.TypeCheckingMode
+
+@TypeChecked
+class DefUnitTest extends GroovyTestCase {
+
+ def id
+ def firstName = "Samwell"
+ def listOfCountries = ['USA', 'UK', 'FRANCE', 'INDIA']
+
+ @TypeChecked(TypeCheckingMode.SKIP)
+ def multiply(x, y) {
+ return x*y
+ }
+
+ @TypeChecked(TypeCheckingMode.SKIP)
+ void testDefVariableDeclaration() {
+
+ def list
+ assert list.getClass() == org.codehaus.groovy.runtime.NullObject
+ assert list.is(null)
+
+ list = [1,2,4]
+ assert list instanceof ArrayList
+ }
+
+ @TypeChecked(TypeCheckingMode.SKIP)
+ void testTypeVariables() {
+ int rate = 200
+ try {
+ rate = [12] //GroovyCastException
+ rate = "nill" //GroovyCastException
+ } catch(GroovyCastException) {
+ println "Cannot assign anything other than integer"
+ }
+ }
+
+ @TypeChecked(TypeCheckingMode.SKIP)
+ void testDefVariableMultipleAssignment() {
+ def rate
+ assert rate == null
+ assert rate.getClass() == org.codehaus.groovy.runtime.NullObject
+
+ rate = 12
+ assert rate instanceof Integer
+
+ rate = "Not Available"
+ assert rate instanceof String
+
+ rate = [1, 4]
+ assert rate instanceof List
+
+ assert divide(12, 3) instanceof BigDecimal
+ assert divide(1, 0) instanceof String
+
+ }
+
+ def divide(int x, int y) {
+ if(y==0) {
+ return "Should not divide by 0"
+ } else {
+ return x/y
+ }
+ }
+
+ def greetMsg() {
+ println "Hello! I am Groovy"
+ }
+
+ void testDefVsType() {
+ def int count
+ assert count instanceof Integer
+ }
+}
\ No newline at end of file
diff --git a/core-groovy-2/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy b/core-groovy-2/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy
new file mode 100644
index 0000000000..3865bc73fa
--- /dev/null
+++ b/core-groovy-2/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy
@@ -0,0 +1,44 @@
+package com.baeldung.strings
+
+import spock.lang.Specification
+
+import java.util.regex.Pattern
+
+class StringMatchingSpec extends Specification {
+
+ def "pattern operator example"() {
+ given: "a pattern"
+ def p = ~'foo'
+
+ expect:
+ p instanceof Pattern
+
+ and: "you can use slash strings to avoid escaping of blackslash"
+ def digitPattern = ~/\d*/
+ digitPattern.matcher('4711').matches()
+ }
+
+ def "match operator example"() {
+ expect:
+ 'foobar' ==~ /.*oba.*/
+
+ and: "matching is strict"
+ !('foobar' ==~ /foo/)
+ }
+
+ def "find operator example"() {
+ when: "using the find operator"
+ def matcher = 'foo and bar, baz and buz' =~ /(\w+) and (\w+)/
+
+ then: "will find groups"
+ matcher.size() == 2
+
+ and: "can access groups using array"
+ matcher[0][0] == 'foo and bar'
+ matcher[1][2] == 'buz'
+
+ and: "you can use it as a predicate"
+ 'foobarbaz' =~ /bar/
+ }
+
+}
diff --git a/core-groovy-2/src/test/groovy/com/baeldung/templateengine/TemplateEnginesUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/templateengine/TemplateEnginesUnitTest.groovy
new file mode 100644
index 0000000000..1846ae664c
--- /dev/null
+++ b/core-groovy-2/src/test/groovy/com/baeldung/templateengine/TemplateEnginesUnitTest.groovy
@@ -0,0 +1,96 @@
+package com.baeldung.templateengine
+
+import groovy.text.SimpleTemplateEngine
+import groovy.text.StreamingTemplateEngine
+import groovy.text.GStringTemplateEngine
+import groovy.text.XmlTemplateEngine
+import groovy.text.XmlTemplateEngine
+import groovy.text.markup.MarkupTemplateEngine
+import groovy.text.markup.TemplateConfiguration
+
+class TemplateEnginesUnitTest extends GroovyTestCase {
+
+ def bindMap = [user: "Norman", signature: "Baeldung"]
+
+ void testSimpleTemplateEngine() {
+ def smsTemplate = 'Dear <% print user %>, Thanks for reading our Article. ${signature}'
+ def smsText = new SimpleTemplateEngine().createTemplate(smsTemplate).make(bindMap)
+
+ assert smsText.toString() == "Dear Norman, Thanks for reading our Article. Baeldung"
+ }
+
+ void testStreamingTemplateEngine() {
+ def articleEmailTemplate = new File('src/main/resources/articleEmail.template')
+ bindMap.articleText = """1. Overview
+This is a tutorial article on Template Engines""" //can be a string larger than 64k
+
+ def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(bindMap)
+
+ assert articleEmailText.toString() == """Dear Norman,
+Please read the requested article below.
+1. Overview
+This is a tutorial article on Template Engines
+From,
+Baeldung"""
+
+ }
+
+ void testGStringTemplateEngine() {
+ def emailTemplate = new File('src/main/resources/email.template')
+ def emailText = new GStringTemplateEngine().createTemplate(emailTemplate).make(bindMap)
+
+ assert emailText.toString() == "Dear Norman,\nThanks for subscribing our services.\nBaeldung"
+ }
+
+ void testXmlTemplateEngine() {
+ def emailXmlTemplate = '''
+ def emailContent = "Thanks for subscribing our services."
+
+ Dear ${user}
+ emailContent
+ ${signature}
+
+ '''
+ def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(bindMap)
+ println emailXml.toString()
+ }
+
+ void testMarkupTemplateEngineHtml() {
+ def emailHtmlTemplate = """html {
+ head {
+ title('Service Subscription Email')
+ }
+ body {
+ p('Dear Norman')
+ p('Thanks for subscribing our services.')
+ p('Baeldung')
+ }
+ }"""
+
+
+ def emailHtml = new MarkupTemplateEngine().createTemplate(emailHtmlTemplate).make()
+ println emailHtml.toString()
+
+ }
+
+ void testMarkupTemplateEngineXml() {
+ def emailXmlTemplate = """xmlDeclaration()
+ xs{
+ email {
+ greet('Dear Norman')
+ content('Thanks for subscribing our services.')
+ signature('Baeldung')
+ }
+ }
+ """
+ TemplateConfiguration config = new TemplateConfiguration()
+ config.autoIndent = true
+ config.autoEscape = true
+ config.autoNewLine = true
+
+ def emailXml = new MarkupTemplateEngine(config).createTemplate(emailXmlTemplate).make()
+
+ println emailXml.toString()
+ }
+
+}
\ No newline at end of file
diff --git a/core-groovy-2/src/test/groovy/com/baeldung/xml/MarkupBuilderUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/xml/MarkupBuilderUnitTest.groovy
new file mode 100644
index 0000000000..c0c8c98392
--- /dev/null
+++ b/core-groovy-2/src/test/groovy/com/baeldung/xml/MarkupBuilderUnitTest.groovy
@@ -0,0 +1,40 @@
+package com.baeldung.xml
+
+import groovy.xml.MarkupBuilder
+import groovy.xml.XmlUtil
+import spock.lang.Specification
+
+class MarkupBuilderUnitTest extends Specification {
+
+ def xmlFile = getClass().getResource("articles_short_formatted.xml")
+
+def "Should create XML properly"() {
+ given: "Node structures"
+
+ when: "Using MarkupBuilderUnitTest to create com.baeldung.xml structure"
+ def writer = new StringWriter()
+ new MarkupBuilder(writer).articles {
+ article {
+ title('First steps in Java')
+ author(id: '1') {
+ firstname('Siena')
+ lastname('Kerr')
+ }
+ 'release-date'('2018-12-01')
+ }
+ article {
+ title('Dockerize your SpringBoot application')
+ author(id: '2') {
+ firstname('Jonas')
+ lastname('Lugo')
+ }
+ 'release-date'('2018-12-01')
+ }
+ }
+
+ then: "Xml is created properly"
+ XmlUtil.serialize(writer.toString()) == XmlUtil.serialize(xmlFile.text)
+}
+
+
+}
diff --git a/core-groovy-2/src/test/groovy/com/baeldung/xml/XmlParserUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/xml/XmlParserUnitTest.groovy
new file mode 100644
index 0000000000..ada47406a1
--- /dev/null
+++ b/core-groovy-2/src/test/groovy/com/baeldung/xml/XmlParserUnitTest.groovy
@@ -0,0 +1,94 @@
+package com.baeldung.xml
+
+
+import spock.lang.Shared
+import spock.lang.Specification
+
+class XmlParserUnitTest extends Specification {
+
+ def xmlFile = getClass().getResourceAsStream("articles.xml")
+
+ @Shared
+ def parser = new XmlParser()
+
+ def "Should read XML file properly"() {
+ given: "XML file"
+
+ when: "Using XmlParser to read file"
+ def articles = parser.parse(xmlFile)
+
+ then: "Xml is loaded properly"
+ articles.'*'.size() == 4
+ articles.article[0].author.firstname.text() == "Siena"
+ articles.article[2].'release-date'.text() == "2018-06-12"
+ articles.article[3].title.text() == "Java 12 insights"
+ articles.article.find { it.author.'@id'.text() == "3" }.author.firstname.text() == "Daniele"
+ }
+
+
+ def "Should add node to existing com.baeldung.xml using NodeBuilder"() {
+ given: "XML object"
+ def articles = parser.parse(xmlFile)
+
+ when: "Adding node to com.baeldung.xml"
+ def articleNode = new NodeBuilder().article(id: '5') {
+ title('Traversing XML in the nutshell')
+ author {
+ firstname('Martin')
+ lastname('Schmidt')
+ }
+ 'release-date'('2019-05-18')
+ }
+ articles.append(articleNode)
+
+ then: "Node is added to com.baeldung.xml properly"
+ articles.'*'.size() == 5
+ articles.article[4].title.text() == "Traversing XML in the nutshell"
+ }
+
+ def "Should replace node"() {
+ given: "XML object"
+ def articles = parser.parse(xmlFile)
+
+ when: "Adding node to com.baeldung.xml"
+ def articleNode = new NodeBuilder().article(id: '5') {
+ title('Traversing XML in the nutshell')
+ author {
+ firstname('Martin')
+ lastname('Schmidt')
+ }
+ 'release-date'('2019-05-18')
+ }
+ articles.article[0].replaceNode(articleNode)
+
+ then: "Node is added to com.baeldung.xml properly"
+ articles.'*'.size() == 4
+ articles.article[0].title.text() == "Traversing XML in the nutshell"
+ }
+
+ def "Should modify node"() {
+ given: "XML object"
+ def articles = parser.parse(xmlFile)
+
+ when: "Changing value of one of the nodes"
+ articles.article.each { it.'release-date'[0].value = "2019-05-18" }
+
+ then: "XML is updated"
+ articles.article.findAll { it.'release-date'.text() != "2019-05-18" }.isEmpty()
+ }
+
+ def "Should remove article from com.baeldung.xml"() {
+ given: "XML object"
+ def articles = parser.parse(xmlFile)
+
+ when: "Removing all articles but with id==3"
+ articles.article
+ .findAll { it.author.'@id'.text() != "3" }
+ .each { articles.remove(it) }
+
+ then: "There is only one article left"
+ articles.children().size() == 1
+ articles.article[0].author.'@id'.text() == "3"
+ }
+
+}
diff --git a/core-groovy-2/src/test/groovy/com/baeldung/xml/XmlSlurperUnitTest.groovy b/core-groovy-2/src/test/groovy/com/baeldung/xml/XmlSlurperUnitTest.groovy
new file mode 100644
index 0000000000..ffeaa46fce
--- /dev/null
+++ b/core-groovy-2/src/test/groovy/com/baeldung/xml/XmlSlurperUnitTest.groovy
@@ -0,0 +1,102 @@
+package com.baeldung.xml
+
+
+import groovy.xml.XmlUtil
+import spock.lang.Shared
+import spock.lang.Specification
+
+class XmlSlurperUnitTest extends Specification {
+
+ def xmlFile = getClass().getResourceAsStream("articles.xml")
+
+ @Shared
+ def parser = new XmlSlurper()
+
+ def "Should read XML file properly"() {
+ given: "XML file"
+
+ when: "Using XmlSlurper to read file"
+ def articles = parser.parse(xmlFile)
+
+ then: "Xml is loaded properly"
+ articles.'*'.size() == 4
+ articles.article[0].author.firstname == "Siena"
+ articles.article[2].'release-date' == "2018-06-12"
+ articles.article[3].title == "Java 12 insights"
+ articles.article.find { it.author.'@id' == "3" }.author.firstname == "Daniele"
+ }
+
+ def "Should add node to existing com.baeldung.xml"() {
+ given: "XML object"
+ def articles = parser.parse(xmlFile)
+
+ when: "Adding node to com.baeldung.xml"
+ articles.appendNode {
+ article(id: '5') {
+ title('Traversing XML in the nutshell')
+ author {
+ firstname('Martin')
+ lastname('Schmidt')
+ }
+ 'release-date'('2019-05-18')
+ }
+ }
+
+ articles = parser.parseText(XmlUtil.serialize(articles))
+
+ then: "Node is added to com.baeldung.xml properly"
+ articles.'*'.size() == 5
+ articles.article[4].title == "Traversing XML in the nutshell"
+ }
+
+ def "Should modify node"() {
+ given: "XML object"
+ def articles = parser.parse(xmlFile)
+
+ when: "Changing value of one of the nodes"
+ articles.article.each { it.'release-date' = "2019-05-18" }
+
+ then: "XML is updated"
+ articles.article.findAll { it.'release-date' != "2019-05-18" }.isEmpty()
+ }
+
+ def "Should replace node"() {
+ given: "XML object"
+ def articles = parser.parse(xmlFile)
+
+ when: "Replacing node"
+ articles.article[0].replaceNode {
+ article(id: '5') {
+ title('Traversing XML in the nutshell')
+ author {
+ firstname('Martin')
+ lastname('Schmidt')
+ }
+ 'release-date'('2019-05-18')
+ }
+ }
+
+ articles = parser.parseText(XmlUtil.serialize(articles))
+
+ then: "Node is replaced properly"
+ articles.'*'.size() == 4
+ articles.article[0].title == "Traversing XML in the nutshell"
+ }
+
+ def "Should remove article from com.baeldung.xml"() {
+ given: "XML object"
+ def articles = parser.parse(xmlFile)
+
+ when: "Removing all articles but with id==3"
+ articles.article
+ .findAll { it.author.'@id' != "3" }
+ .replaceNode {}
+
+ articles = parser.parseText(XmlUtil.serialize(articles))
+
+ then: "There is only one article left"
+ articles.children().size() == 1
+ articles.article[0].author.'@id' == "3"
+ }
+
+}
diff --git a/core-groovy-2/src/test/resources/com/baeldung/xml/articles.xml b/core-groovy-2/src/test/resources/com/baeldung/xml/articles.xml
new file mode 100644
index 0000000000..ef057405f5
--- /dev/null
+++ b/core-groovy-2/src/test/resources/com/baeldung/xml/articles.xml
@@ -0,0 +1,34 @@
+
+
+ First steps in Java
+
+ Siena
+ Kerr
+
+ 2018-12-01
+
+
+ Dockerize your SpringBoot application
+
+ Jonas
+ Lugo
+
+ 2018-12-01
+
+
+ SpringBoot tutorial
+
+ Daniele
+ Ferguson
+
+ 2018-06-12
+
+
+ Java 12 insights
+
+ Siena
+ Kerr
+
+ 2018-07-22
+
+
diff --git a/core-groovy-2/src/test/resources/com/baeldung/xml/articles_short_formatted.xml b/core-groovy-2/src/test/resources/com/baeldung/xml/articles_short_formatted.xml
new file mode 100644
index 0000000000..6492020e03
--- /dev/null
+++ b/core-groovy-2/src/test/resources/com/baeldung/xml/articles_short_formatted.xml
@@ -0,0 +1,18 @@
+
+
+ First steps in Java
+
+ Siena
+ Kerr
+
+ 2018-12-01
+
+
+ Dockerize your SpringBoot application
+
+ Jonas
+ Lugo
+
+ 2018-12-01
+
+
diff --git a/core-groovy-collections/README.md b/core-groovy-collections/README.md
new file mode 100644
index 0000000000..aeba8933be
--- /dev/null
+++ b/core-groovy-collections/README.md
@@ -0,0 +1,6 @@
+# Groovy
+
+## Relevant articles:
+
+- [Maps in Groovy](https://www.baeldung.com/groovy-maps)
+
diff --git a/core-groovy-collections/pom.xml b/core-groovy-collections/pom.xml
new file mode 100644
index 0000000000..bf3ae26592
--- /dev/null
+++ b/core-groovy-collections/pom.xml
@@ -0,0 +1,131 @@
+
+
+ 4.0.0
+ core-groovy-collections
+ 1.0-SNAPSHOT
+ core-groovy-collections
+ jar
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ org.codehaus.groovy
+ groovy
+ ${groovy.version}
+
+
+ org.codehaus.groovy
+ groovy-all
+ ${groovy-all.version}
+ pom
+
+
+ org.codehaus.groovy
+ groovy-dateutil
+ ${groovy.version}
+
+
+ org.codehaus.groovy
+ groovy-sql
+ ${groovy-sql.version}
+
+
+ org.junit.platform
+ junit-platform-runner
+ ${junit.platform.version}
+ test
+
+
+ org.hsqldb
+ hsqldb
+ ${hsqldb.version}
+ test
+
+
+ org.spockframework
+ spock-core
+ ${spock-core.version}
+ test
+
+
+
+
+
+
+ org.codehaus.gmavenplus
+ gmavenplus-plugin
+ ${gmavenplus-plugin.version}
+
+
+
+ addSources
+ addTestSources
+ compile
+ compileTests
+
+
+
+
+
+ maven-failsafe-plugin
+ ${maven-failsafe-plugin.version}
+
+
+ org.junit.platform
+ junit-platform-surefire-provider
+ ${junit.platform.version}
+
+
+
+
+ junit5
+
+ integration-test
+ verify
+
+
+
+ **/*Test5.java
+
+
+
+
+
+
+ maven-surefire-plugin
+ 2.20.1
+
+ false
+
+ **/*Test.java
+ **/*Spec.java
+
+
+
+
+
+
+
+
+ central
+ http://jcenter.bintray.com
+
+
+
+
+ 1.0.0
+ 2.5.6
+ 2.5.6
+ 2.5.6
+ 2.4.0
+ 1.1-groovy-2.4
+ 1.6
+
+
+
diff --git a/core-groovy-collections/src/test/groovy/com/baeldung/map/MapTest.groovy b/core-groovy-collections/src/test/groovy/com/baeldung/map/MapTest.groovy
new file mode 100644
index 0000000000..c6105eb1c4
--- /dev/null
+++ b/core-groovy-collections/src/test/groovy/com/baeldung/map/MapTest.groovy
@@ -0,0 +1,148 @@
+package com.baeldung.map;
+
+import static groovy.test.GroovyAssert.*
+import org.junit.Test
+
+class MapTest{
+
+ @Test
+ void createMap() {
+
+ def emptyMap = [:]
+ assertNotNull(emptyMap)
+
+ assertTrue(emptyMap instanceof java.util.LinkedHashMap)
+
+ def map = [name:"Jerry", age: 42, city: "New York"]
+ assertTrue(map.size() == 3)
+ }
+
+ @Test
+ void addItemsToMap() {
+
+ def map = [name:"Jerry"]
+
+ map["age"] = 42
+
+ map.city = "New York"
+
+ def hobbyLiteral = "hobby"
+ def hobbyMap = [(hobbyLiteral): "Singing"]
+ map.putAll(hobbyMap)
+
+ assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"])
+ assertTrue(hobbyMap.hobby == "Singing")
+ assertTrue(hobbyMap[hobbyLiteral] == "Singing")
+
+ map.plus([1:20]) // returns new map
+
+ map << [2:30]
+
+ }
+
+ @Test
+ void getItemsFromMap() {
+
+ def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
+
+ assertTrue(map["name"] == "Jerry")
+
+ assertTrue(map.name == "Jerry")
+
+ def propertyAge = "age"
+ assertTrue(map[propertyAge] == 42)
+ }
+
+ @Test
+ void removeItemsFromMap() {
+
+ def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49]
+
+ def minusMap = map.minus([2:42, 4:34]);
+ assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49])
+
+ minusMap.removeAll{it -> it.key instanceof String}
+ assertTrue( minusMap == [ 1:20, 6:39, 7:49])
+
+ minusMap.retainAll{it -> it.value %2 == 0}
+ assertTrue( minusMap == [1:20])
+ }
+
+ @Test
+ void iteratingOnMaps(){
+ def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
+
+ map.each{ entry -> println "$entry.key: $entry.value" }
+
+ map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" }
+
+ map.eachWithIndex{ key, value, i -> println "$i $key: $value" }
+ }
+
+ @Test
+ void filteringAndSearchingMaps(){
+ def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
+
+ assertTrue(map.find{ it.value == "New York"}.key == "city")
+
+ assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"])
+
+ map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")}
+
+ assertTrue(map.every{it -> it.value instanceof String} == false)
+
+ assertTrue(map.any{it -> it.value instanceof String} == true)
+ }
+
+ @Test
+ void collect(){
+
+ def map = [1: [name:"Jerry", age: 42, city: "New York"],
+ 2: [name:"Long", age: 25, city: "New York"],
+ 3: [name:"Dustin", age: 29, city: "New York"],
+ 4: [name:"Dustin", age: 34, city: "New York"]]
+
+ def names = map.collect{entry -> entry.value.name} // returns only list
+ assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"])
+
+ def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name}
+ assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set)
+
+ def idNames = map.collectEntries{key, value -> [key, value.name]}
+ assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"])
+
+ def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name}
+ assertTrue(below30Names == ["Long", "Dustin"])
+
+
+ }
+
+ @Test
+ void group(){
+ def map = [1:20, 2: 40, 3: 11, 4: 93]
+
+ def subMap = map.groupBy{it.value % 2}
+ println subMap
+ assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]])
+
+ def keySubMap = map.subMap([1, 2])
+ assertTrue(keySubMap == [1:20, 2:40])
+
+ }
+
+ @Test
+ void sorting(){
+ def map = [ab:20, a: 40, cb: 11, ba: 93]
+
+ def naturallyOrderedMap = map.sort()
+ assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap)
+
+ def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator)
+ assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap)
+
+ def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value })
+ assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap)
+
+ }
+
+}
diff --git a/core-groovy/.gitignore b/core-groovy/.gitignore
new file mode 100644
index 0000000000..09220fdf52
--- /dev/null
+++ b/core-groovy/.gitignore
@@ -0,0 +1 @@
+/src/main/resources/ioSerializedObject.txt
\ No newline at end of file
diff --git a/core-groovy/README.md b/core-groovy/README.md
index 71788acdb7..321c37be8d 100644
--- a/core-groovy/README.md
+++ b/core-groovy/README.md
@@ -4,3 +4,12 @@
- [JDBC with Groovy](http://www.baeldung.com/jdbc-groovy)
- [Working with JSON in Groovy](http://www.baeldung.com/groovy-json)
+- [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read)
+- [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings)
+- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating)
+- [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits)
+- [Closures in Groovy](https://www.baeldung.com/groovy-closures)
+- [Finding Elements in Collections in Groovy](https://www.baeldung.com/groovy-collections-find-elements)
+- [Lists in Groovy](https://www.baeldung.com/groovy-lists)
+- [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)
\ No newline at end of file
diff --git a/core-groovy/src/main/groovy/com/baeldung/Person.groovy b/core-groovy/src/main/groovy/com/baeldung/Person.groovy
new file mode 100644
index 0000000000..6a009aeee0
--- /dev/null
+++ b/core-groovy/src/main/groovy/com/baeldung/Person.groovy
@@ -0,0 +1,37 @@
+package com.baeldung
+
+class Person {
+ private String firstname
+ private String lastname
+ private Integer age
+
+ Person(String firstname, String lastname, Integer age) {
+ this.firstname = firstname
+ this.lastname = lastname
+ this.age = age
+ }
+
+ String getFirstname() {
+ return firstname
+ }
+
+ void setFirstname(String firstname) {
+ this.firstname = firstname
+ }
+
+ String getLastname() {
+ return lastname
+ }
+
+ void setLastname(String lastname) {
+ this.lastname = lastname
+ }
+
+ Integer getAge() {
+ return age
+ }
+
+ void setAge(Integer age) {
+ this.age = age
+ }
+}
diff --git a/core-groovy/src/main/groovy/com/baeldung/closures/Closures.groovy b/core-groovy/src/main/groovy/com/baeldung/closures/Closures.groovy
new file mode 100644
index 0000000000..607329ce88
--- /dev/null
+++ b/core-groovy/src/main/groovy/com/baeldung/closures/Closures.groovy
@@ -0,0 +1,87 @@
+package com.baeldung.closures
+
+class Closures {
+
+ def printWelcome = {
+ println "Welcome to Closures!"
+ }
+
+ def print = { name ->
+ println name
+ }
+
+ def formatToLowerCase(name) {
+ return name.toLowerCase()
+ }
+ def formatToLowerCaseClosure = { name ->
+ return name.toLowerCase()
+ }
+
+ def count=0
+
+ def increaseCount = {
+ count++
+ }
+
+ def greet = {
+ return "Hello! ${it}"
+ }
+
+ def multiply = { x, y ->
+ return x*y
+ }
+
+ def calculate = {int x, int y, String operation ->
+
+ //log closure
+ def log = {
+ println "Performing $it"
+ }
+
+ def result = 0
+ switch(operation) {
+ case "ADD":
+ log("Addition")
+ result = x+y
+ break
+ case "SUB":
+ log("Subtraction")
+ result = x-y
+ break
+ case "MUL":
+ log("Multiplication")
+ result = x*y
+ break
+ case "DIV":
+ log("Division")
+ result = x/y
+ break
+ }
+ return result
+ }
+
+ def addAll = { int... args ->
+ return args.sum()
+ }
+
+ def volume(Closure areaCalculator, int... dimensions) {
+ if(dimensions.size() == 3) {
+
+ //consider dimension[0] = length, dimension[1] = breadth, dimension[2] = height
+ //for cube and cuboid
+ return areaCalculator(dimensions[0], dimensions[1]) * dimensions[2]
+ } else if(dimensions.size() == 2) {
+
+ //consider dimension[0] = radius, dimension[1] = height
+ //for cylinder and cone
+ return areaCalculator(dimensions[0]) * dimensions[1]
+ } else if(dimensions.size() == 1) {
+
+ //consider dimension[0] = radius
+ //for sphere
+ return areaCalculator(dimensions[0]) * dimensions[0]
+ }
+
+ }
+
+}
\ No newline at end of file
diff --git a/core-groovy/src/main/groovy/com/baeldung/closures/Employee.groovy b/core-groovy/src/main/groovy/com/baeldung/closures/Employee.groovy
new file mode 100644
index 0000000000..78eb5aadeb
--- /dev/null
+++ b/core-groovy/src/main/groovy/com/baeldung/closures/Employee.groovy
@@ -0,0 +1,6 @@
+package com.baeldung.closures
+
+class Employee {
+
+ String fullName
+}
\ No newline at end of file
diff --git a/core-groovy/src/main/groovy/com/baeldung/io/Task.groovy b/core-groovy/src/main/groovy/com/baeldung/io/Task.groovy
new file mode 100644
index 0000000000..8a3bedc048
--- /dev/null
+++ b/core-groovy/src/main/groovy/com/baeldung/io/Task.groovy
@@ -0,0 +1,8 @@
+package com.baeldung.io
+
+class Task implements Serializable {
+ String description
+ Date startDate
+ Date dueDate
+ int status
+}
diff --git a/core-groovy/src/main/resources/binaryExample.jpg b/core-groovy/src/main/resources/binaryExample.jpg
new file mode 100644
index 0000000000..4b32645ac9
Binary files /dev/null and b/core-groovy/src/main/resources/binaryExample.jpg differ
diff --git a/core-groovy/src/main/resources/ioData.txt b/core-groovy/src/main/resources/ioData.txt
new file mode 100644
index 0000000000..d2741339d1
Binary files /dev/null and b/core-groovy/src/main/resources/ioData.txt differ
diff --git a/core-groovy/src/main/resources/ioInput.txt b/core-groovy/src/main/resources/ioInput.txt
new file mode 100644
index 0000000000..b180256dd5
--- /dev/null
+++ b/core-groovy/src/main/resources/ioInput.txt
@@ -0,0 +1,4 @@
+First line of text
+Second line of text
+Third line of text
+Fourth line of text
\ No newline at end of file
diff --git a/core-groovy/src/main/resources/ioOutput.txt b/core-groovy/src/main/resources/ioOutput.txt
new file mode 100644
index 0000000000..bcf76c43d8
--- /dev/null
+++ b/core-groovy/src/main/resources/ioOutput.txt
@@ -0,0 +1,3 @@
+Line one of output example
+Line two of output example
+Line three of output example
\ No newline at end of file
diff --git a/core-groovy/src/test/groovy/com/baeldung/closures/ClosuresUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/closures/ClosuresUnitTest.groovy
new file mode 100644
index 0000000000..32c67e99bc
--- /dev/null
+++ b/core-groovy/src/test/groovy/com/baeldung/closures/ClosuresUnitTest.groovy
@@ -0,0 +1,80 @@
+package com.baeldung.closures
+
+import spock.lang.Specification
+
+class ClosuresUnitTest extends GroovyTestCase {
+
+ Closures closures = new Closures()
+
+ void testDeclaration() {
+
+ closures.print("Hello! Closure")
+ closures.formatToLowerCaseClosure("Hello! Closure")
+
+ closures.print.call("Hello! Closure")
+ closures.formatToLowerCaseClosure.call("Hello! Closure")
+
+ }
+
+ void testClosureVsMethods() {
+ assert closures.formatToLowerCase("TONY STARK") == closures.formatToLowerCaseClosure("Tony STark")
+ }
+
+ void testParameters() {
+ //implicit parameter
+ assert closures.greet("Alex") == "Hello! Alex"
+
+ //multiple parameters
+ assert closures.multiply(2, 4) == 8
+
+ assert closures.calculate(12, 4, "ADD") == 16
+ assert closures.calculate(12, 4, "SUB") == 8
+ assert closures.calculate(43, 8, "DIV") == 5.375
+
+ //varags
+ assert closures.addAll(12, 10, 14) == 36
+
+ }
+
+ void testClosureAsAnArgument() {
+ assert closures.volume({ l, b -> return l*b }, 12, 6, 10) == 720
+
+ assert closures.volume({ radius -> return Math.PI*radius*radius/3 }, 5, 10) == Math.PI * 250/3
+ }
+
+ void testGStringsLazyEvaluation() {
+ def name = "Samwell"
+ def welcomeMsg = "Welcome! $name"
+
+ assert welcomeMsg == "Welcome! Samwell"
+
+ // changing the name does not affect original interpolated value
+ name = "Tarly"
+ assert welcomeMsg != "Welcome! Tarly"
+
+ def fullName = "Tarly Samson"
+ def greetStr = "Hello! ${-> fullName}"
+
+ assert greetStr == "Hello! Tarly Samson"
+
+ // this time changing the variable affects the interpolated String's value
+ fullName = "Jon Smith"
+ assert greetStr == "Hello! Jon Smith"
+ }
+
+ void testClosureInLists() {
+ def list = [10, 11, 12, 13, 14, true, false, "BUNTHER"]
+ list.each {
+ println it
+ }
+
+ assert [13, 14] == list.findAll{ it instanceof Integer && it >= 13}
+ }
+
+ void testClosureInMaps() {
+ def map = [1:10, 2:30, 4:5]
+
+ assert [10, 60, 20] == map.collect{it.key * it.value}
+ }
+
+}
\ No newline at end of file
diff --git a/core-groovy/src/test/groovy/com/baeldung/io/DataAndObjectsUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/io/DataAndObjectsUnitTest.groovy
new file mode 100644
index 0000000000..32a21f6b38
--- /dev/null
+++ b/core-groovy/src/test/groovy/com/baeldung/io/DataAndObjectsUnitTest.groovy
@@ -0,0 +1,53 @@
+package com.baeldung.io
+
+import static org.junit.Assert.*
+
+import org.junit.Test
+
+class DataAndObjectsUnitTest {
+ @Test
+ void whenUsingWithDataOutputStream_thenDataIsSerializedToAFile() {
+ String message = 'This is a serialized string'
+ int length = message.length()
+ boolean valid = true
+ new File('src/main/resources/ioData.txt').withDataOutputStream { out ->
+ out.writeUTF(message)
+ out.writeInt(length)
+ out.writeBoolean(valid)
+ }
+
+ String loadedMessage = ""
+ int loadedLength
+ boolean loadedValid
+
+ new File('src/main/resources/ioData.txt').withDataInputStream { is ->
+ loadedMessage = is.readUTF()
+ loadedLength = is.readInt()
+ loadedValid = is.readBoolean()
+ }
+
+ assertEquals(message, loadedMessage)
+ assertEquals(length, loadedLength)
+ assertEquals(valid, loadedValid)
+ }
+
+ @Test
+ void whenUsingWithObjectOutputStream_thenObjectIsSerializedToFile() {
+ Task task = new Task(description:'Take out the trash', startDate:new Date(), status:0)
+ def serializedDataFile = new File('src/main/resources/ioSerializedObject.txt')
+ serializedDataFile.createNewFile()
+ serializedDataFile.withObjectOutputStream { out ->
+ out.writeObject(task)
+ }
+
+ Task taskRead
+
+ new File('src/main/resources/ioSerializedObject.txt').withObjectInputStream { is ->
+ taskRead = is.readObject()
+ }
+
+ assertEquals(task.description, taskRead.description)
+ assertEquals(task.startDate, taskRead.startDate)
+ assertEquals(task.status, taskRead.status)
+ }
+}
diff --git a/core-groovy/src/test/groovy/com/baeldung/io/ReadExampleUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/io/ReadExampleUnitTest.groovy
new file mode 100644
index 0000000000..bed77b4d81
--- /dev/null
+++ b/core-groovy/src/test/groovy/com/baeldung/io/ReadExampleUnitTest.groovy
@@ -0,0 +1,134 @@
+package com.baeldung.io
+
+import static org.junit.Assert.*
+import org.junit.Test
+
+class ReadExampleUnitTest {
+
+ @Test
+ void whenUsingEachLine_thenCorrectLinesReturned() {
+ def expectedList = [
+ 'First line of text',
+ 'Second line of text',
+ 'Third line of text',
+ 'Fourth line of text']
+
+ def lines = []
+
+ new File('src/main/resources/ioInput.txt').eachLine { line ->
+ lines.add(line)
+ }
+ assertEquals(expectedList, lines)
+ }
+
+ @Test
+ void whenUsingReadEachLineWithLineNumber_thenCorrectLinesReturned() {
+ def expectedList = [
+ 'Second line of text',
+ 'Third line of text',
+ 'Fourth line of text']
+
+ def lineNoRange = 2..4
+ def lines = []
+
+ new File('src/main/resources/ioInput.txt').eachLine { line, lineNo ->
+ if (lineNoRange.contains(lineNo)) {
+ lines.add(line)
+ }
+ }
+ assertEquals(expectedList, lines)
+ }
+
+ @Test
+ void whenUsingReadEachLineWithLineNumberStartAtZero_thenCorrectLinesReturned() {
+ def expectedList = [
+ 'Second line of text',
+ 'Third line of text',
+ 'Fourth line of text']
+
+ def lineNoRange = 1..3
+ def lines = []
+
+ new File('src/main/resources/ioInput.txt').eachLine(0, { line, lineNo ->
+ if (lineNoRange.contains(lineNo)) {
+ lines.add(line)
+ }
+ })
+ assertEquals(expectedList, lines)
+ }
+
+ @Test
+ void whenUsingWithReader_thenLineCountReturned() {
+ def expectedCount = 4
+ def actualCount = 0
+ new File('src/main/resources/ioInput.txt').withReader { reader ->
+ while(reader.readLine()) {
+ actualCount++
+ }
+ }
+ assertEquals(expectedCount, actualCount)
+ }
+
+ @Test
+ void whenUsingNewReader_thenOutputFileCreated() {
+ def outputPath = 'src/main/resources/ioOut.txt'
+ def reader = new File('src/main/resources/ioInput.txt').newReader()
+ new File(outputPath).append(reader)
+ reader.close()
+ def ioOut = new File(outputPath)
+ assertTrue(ioOut.exists())
+ ioOut.delete()
+ }
+
+ @Test
+ void whenUsingWithInputStream_thenCorrectBytesAreReturned() {
+ def expectedLength = 1139
+ byte[] data = []
+ new File("src/main/resources/binaryExample.jpg").withInputStream { stream ->
+ data = stream.getBytes()
+ }
+ assertEquals(expectedLength, data.length)
+ }
+
+ @Test
+ void whenUsingNewInputStream_thenOutputFileCreated() {
+ def outputPath = 'src/main/resources/binaryOut.jpg'
+ def is = new File('src/main/resources/binaryExample.jpg').newInputStream()
+ new File(outputPath).append(is)
+ is.close()
+ def ioOut = new File(outputPath)
+ assertTrue(ioOut.exists())
+ ioOut.delete()
+ }
+
+ @Test
+ void whenUsingCollect_thenCorrectListIsReturned() {
+ def expectedList = ['First line of text', 'Second line of text', 'Third line of text', 'Fourth line of text']
+
+ def actualList = new File('src/main/resources/ioInput.txt').collect {it}
+ assertEquals(expectedList, actualList)
+ }
+
+ @Test
+ void whenUsingAsStringArray_thenCorrectArrayIsReturned() {
+ String[] expectedArray = ['First line of text', 'Second line of text', 'Third line of text', 'Fourth line of text']
+
+ def actualArray = new File('src/main/resources/ioInput.txt') as String[]
+ assertArrayEquals(expectedArray, actualArray)
+ }
+
+ @Test
+ void whenUsingText_thenCorrectStringIsReturned() {
+ def ln = System.getProperty('line.separator')
+ def expectedString = "First line of text${ln}Second line of text${ln}Third line of text${ln}Fourth line of text"
+ def actualString = new File('src/main/resources/ioInput.txt').text
+ assertEquals(expectedString.toString(), actualString)
+ }
+
+ @Test
+ void whenUsingBytes_thenByteArrayIsReturned() {
+ def expectedLength = 1139
+ def contents = new File('src/main/resources/binaryExample.jpg').bytes
+ assertEquals(expectedLength, contents.length)
+ }
+}
diff --git a/core-groovy/src/test/groovy/com/baeldung/io/TraverseFileTreeUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/io/TraverseFileTreeUnitTest.groovy
new file mode 100644
index 0000000000..dac0189fb9
--- /dev/null
+++ b/core-groovy/src/test/groovy/com/baeldung/io/TraverseFileTreeUnitTest.groovy
@@ -0,0 +1,61 @@
+package com.baeldung.io
+
+import org.junit.Test
+
+import groovy.io.FileType
+import groovy.io.FileVisitResult
+
+class TraverseFileTreeUnitTest {
+ @Test
+ void whenUsingEachFile_filesAreListed() {
+ new File('src/main/resources').eachFile { file ->
+ println file.name
+ }
+ }
+
+ @Test(expected = IllegalArgumentException)
+ void whenUsingEachFileOnAFile_anErrorOccurs() {
+ new File('src/main/resources/ioInput.txt').eachFile { file ->
+ println file.name
+ }
+ }
+
+ @Test
+ void whenUsingEachFileMatch_filesAreListed() {
+ new File('src/main/resources').eachFileMatch(~/io.*\.txt/) { file ->
+ println file.name
+ }
+ }
+
+ @Test
+ void whenUsingEachFileRecurse_thenFilesInSubfoldersAreListed() {
+ new File('src/main').eachFileRecurse(FileType.FILES) { file ->
+ println "$file.parent $file.name"
+ }
+ }
+
+ @Test
+ void whenUsingEachFileRecurse_thenDirsInSubfoldersAreListed() {
+ new File('src/main').eachFileRecurse(FileType.DIRECTORIES) { file ->
+ println "$file.parent $file.name"
+ }
+ }
+
+ @Test
+ void whenUsingEachDirRecurse_thenDirsAndSubDirsAreListed() {
+ new File('src/main').eachDirRecurse { dir ->
+ println "$dir.parent $dir.name"
+ }
+ }
+
+ @Test
+ void whenUsingTraverse_thenDirectoryIsTraversed() {
+ new File('src/main').traverse { file ->
+ if (file.directory && file.name == 'groovy') {
+ FileVisitResult.SKIP_SUBTREE
+ } else {
+ println "$file.parent - $file.name"
+ }
+ }
+ }
+}
diff --git a/core-groovy/src/test/groovy/com/baeldung/io/WriteExampleUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/io/WriteExampleUnitTest.groovy
new file mode 100644
index 0000000000..81758b430a
--- /dev/null
+++ b/core-groovy/src/test/groovy/com/baeldung/io/WriteExampleUnitTest.groovy
@@ -0,0 +1,96 @@
+package com.baeldung.io
+
+import static org.junit.Assert.*
+
+import org.junit.Before
+import org.junit.Test
+
+class WriteExampleUnitTest {
+ @Before
+ void clearOutputFile() {
+ new File('src/main/resources/ioOutput.txt').text = ''
+ new File('src/main/resources/ioBinaryOutput.bin').delete()
+ }
+
+ @Test
+ void whenUsingWithWriter_thenFileCreated() {
+ def outputLines = [
+ 'Line one of output example',
+ 'Line two of output example',
+ 'Line three of output example'
+ ]
+
+ def outputFileName = 'src/main/resources/ioOutput.txt'
+ new File(outputFileName).withWriter { writer ->
+ outputLines.each { line ->
+ writer.writeLine line
+ }
+ }
+ def writtenLines = new File(outputFileName).collect {it}
+ assertEquals(outputLines, writtenLines)
+ }
+
+ @Test
+ void whenUsingNewWriter_thenFileCreated() {
+ def outputLines = [
+ 'Line one of output example',
+ 'Line two of output example',
+ 'Line three of output example'
+ ]
+
+ def outputFileName = 'src/main/resources/ioOutput.txt'
+ def writer = new File(outputFileName).newWriter()
+ outputLines.forEach {line ->
+ writer.writeLine line
+ }
+ writer.flush()
+ writer.close()
+
+ def writtenLines = new File(outputFileName).collect {it}
+ assertEquals(outputLines, writtenLines)
+ }
+
+ @Test
+ void whenUsingDoubleLessThanOperator_thenFileCreated() {
+ def outputLines = [
+ 'Line one of output example',
+ 'Line two of output example',
+ 'Line three of output example'
+ ]
+
+ def ln = System.getProperty('line.separator')
+ def outputFileName = 'src/main/resources/ioOutput.txt'
+ new File(outputFileName) << "Line one of output example${ln}Line two of output example${ln}Line three of output example"
+ def writtenLines = new File(outputFileName).collect {it}
+ assertEquals(outputLines.size(), writtenLines.size())
+ }
+
+ @Test
+ void whenUsingBytes_thenBinaryFileCreated() {
+ def outputFileName = 'src/main/resources/ioBinaryOutput.bin'
+ def outputFile = new File(outputFileName)
+ byte[] outBytes = [44, 88, 22]
+ outputFile.bytes = outBytes
+ assertEquals(3, new File(outputFileName).size())
+ }
+
+ @Test
+ void whenUsingWithOutputStream_thenBinaryFileCreated() {
+ def outputFileName = 'src/main/resources/ioBinaryOutput.bin'
+ byte[] outBytes = [44, 88, 22]
+ new File(outputFileName).withOutputStream { stream ->
+ stream.write(outBytes)
+ }
+ assertEquals(3, new File(outputFileName).size())
+ }
+
+ @Test
+ void whenUsingNewOutputStream_thenBinaryFileCreated() {
+ def outputFileName = 'src/main/resources/ioBinaryOutput.bin'
+ byte[] outBytes = [44, 88, 22]
+ def os = new File(outputFileName).newOutputStream()
+ os.write(outBytes)
+ os.close()
+ assertEquals(3, new File(outputFileName).size())
+ }
+}
diff --git a/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy b/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy
new file mode 100644
index 0000000000..7771028132
--- /dev/null
+++ b/core-groovy/src/test/groovy/com/baeldung/lists/ListTest.groovy
@@ -0,0 +1,173 @@
+package com.baeldung.groovy.lists
+
+import static groovy.test.GroovyAssert.*
+import org.junit.Test
+
+class ListTest{
+
+ @Test
+ void testCreateList() {
+
+ def list = [1, 2, 3]
+ assertNotNull(list)
+
+ def listMix = ['A', "b", 1, true]
+ assertTrue(listMix == ['A', "b", 1, true])
+
+ def linkedList = [1, 2, 3] as LinkedList
+ assertTrue(linkedList instanceof LinkedList)
+
+ ArrayList arrList = [1, 2, 3]
+ assertTrue(arrList.class == ArrayList)
+
+ def copyList = new ArrayList(arrList)
+ assertTrue(copyList == arrList)
+
+ def cloneList = arrList.clone()
+ assertTrue(cloneList == arrList)
+ }
+
+ @Test
+ void testCreateEmptyList() {
+
+ def emptyList = []
+ assertTrue(emptyList.size() == 0)
+ }
+
+ @Test
+ void testCompareTwoLists() {
+
+ def list1 = [5, 6.0, 'p']
+ def list2 = [5, 6.0, 'p']
+ assertTrue(list1 == list2)
+ }
+
+ @Test
+ void testGetItemsFromList(){
+
+ def list = ["Hello", "World"]
+
+ assertTrue(list.get(1) == "World")
+ assertTrue(list[1] == "World")
+ assertTrue(list[-1] == "World")
+ assertTrue(list.getAt(1) == "World")
+ assertTrue(list.getAt(-2) == "Hello")
+ }
+
+ @Test
+ void testAddItemsToList() {
+
+ def list = []
+
+ list << 1
+ list.add("Apple")
+ assertTrue(list == [1, "Apple"])
+
+ list[2] = "Box"
+ list[4] = true
+ assertTrue(list == [1, "Apple", "Box", null, true])
+
+ list.add(1, 6.0)
+ assertTrue(list == [1, 6.0, "Apple", "Box", null, true])
+
+ def list2 = [1, 2]
+ list += list2
+ list += 12
+ assertTrue(list == [1, 6.0, "Apple", "Box", null, true, 1, 2, 12])
+ }
+
+ @Test
+ void testUpdateItemsInList() {
+
+ def list =[1, "Apple", 80, "App"]
+ list[1] = "Box"
+ list.set(2,90)
+ assertTrue(list == [1, "Box", 90, "App"])
+ }
+
+ @Test
+ void testRemoveItemsFromList(){
+
+ def list = [1, 2, 3, 4, 5, 5, 6, 6, 7]
+
+ list.remove(3)
+ assertTrue(list == [1, 2, 3, 5, 5, 6, 6, 7])
+
+ list.removeElement(5)
+ assertTrue(list == [1, 2, 3, 5, 6, 6, 7])
+
+ assertTrue(list - 6 == [1, 2, 3, 5, 7])
+ }
+
+ @Test
+ void testIteratingOnAList(){
+
+ def list = [1, "App", 3, 4]
+ list.each{ println it * 2}
+
+ list.eachWithIndex{ it, i -> println "$i : $it" }
+ }
+
+ @Test
+ void testCollectingToAnotherList(){
+
+ def list = ["Kay", "Henry", "Justin", "Tom"]
+ assertTrue(list.collect{"Hi " + it} == ["Hi Kay", "Hi Henry", "Hi Justin", "Hi Tom"])
+ }
+
+ @Test
+ void testJoinItemsInAList(){
+ assertTrue(["One", "Two", "Three"].join(",") == "One,Two,Three")
+ }
+
+ @Test
+ void testFilteringOnLists(){
+ def filterList = [2, 1, 3, 4, 5, 6, 76]
+
+ assertTrue(filterList.find{it > 3} == 4)
+
+ assertTrue(filterList.findAll{it > 3} == [4, 5, 6, 76])
+
+ assertTrue(filterList.findAll{ it instanceof Number} == [2, 1, 3, 4, 5, 6, 76])
+
+ assertTrue(filterList.grep( Number )== [2, 1, 3, 4, 5, 6, 76])
+
+ assertTrue(filterList.grep{ it> 6 }== [76])
+
+ def conditionList = [2, 1, 3, 4, 5, 6, 76]
+
+ assertFalse(conditionList.every{ it < 6})
+
+ assertTrue(conditionList.any{ it%2 == 0})
+
+ }
+
+ @Test
+ void testGetUniqueItemsInAList(){
+ assertTrue([1, 3, 3, 4].toUnique() == [1, 3, 4])
+
+ def uniqueList = [1, 3, 3, 4]
+ uniqueList.unique()
+ assertTrue(uniqueList == [1, 3, 4])
+
+ assertTrue(["A", "B", "Ba", "Bat", "Cat"].toUnique{ it.size()} == ["A", "Ba", "Bat"])
+ }
+
+ @Test
+ void testSorting(){
+
+ assertTrue([1, 2, 1, 0].sort() == [0, 1, 1, 2])
+ Comparator mc = {a,b -> a == b? 0: a < b? 1 : -1}
+
+ def list = [1, 2, 1, 0]
+ list.sort(mc)
+ assertTrue(list == [2, 1, 1, 0])
+
+ def strList = ["na", "ppp", "as"]
+ assertTrue(strList.max() == "ppp")
+
+ Comparator minc = {a,b -> a == b? 0: a < b? -1 : 1}
+ def numberList = [3, 2, 0, 7]
+ assertTrue(numberList.min(minc) == 0)
+ }
+}
\ No newline at end of file
diff --git a/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy
new file mode 100644
index 0000000000..9617c099ce
--- /dev/null
+++ b/core-groovy/src/test/groovy/com/baeldung/lists/ListUnitTest.groovy
@@ -0,0 +1,58 @@
+package com.baeldung.lists
+
+import com.baeldung.Person
+import org.junit.Test
+
+import static org.junit.Assert.*
+
+class ListUnitTest {
+
+ private final personList = [
+ new Person("Regina", "Fitzpatrick", 25),
+ new Person("Abagail", "Ballard", 26),
+ new Person("Lucian", "Walter", 30),
+ ]
+
+ @Test
+ void whenListContainsElement_thenCheckReturnsTrue() {
+ def list = ['a', 'b', 'c']
+
+ assertTrue(list.indexOf('a') > -1)
+ assertTrue(list.contains('a'))
+ }
+
+ @Test
+ void whenListContainsElement_thenCheckWithMembershipOperatorReturnsTrue() {
+ def list = ['a', 'b', 'c']
+
+ assertTrue('a' in list)
+ }
+
+ @Test
+ void givenListOfPerson_whenUsingStreamMatching_thenShouldEvaluateList() {
+ assertTrue(personList.stream().anyMatch {it.age > 20})
+ assertFalse(personList.stream().allMatch {it.age < 30})
+ }
+
+ @Test
+ void givenListOfPerson_whenUsingCollectionMatching_thenShouldEvaluateList() {
+ assertTrue(personList.any {it.age > 20})
+ assertFalse(personList.every {it.age < 30})
+ }
+
+ @Test
+ void givenListOfPerson_whenUsingStreamFind_thenShouldReturnMatchingElements() {
+ assertTrue(personList.stream().filter {it.age > 20}.findAny().isPresent())
+ assertFalse(personList.stream().filter {it.age > 30}.findAny().isPresent())
+ assertTrue(personList.stream().filter {it.age > 20}.findAll().size() == 3)
+ assertTrue(personList.stream().filter {it.age > 30}.findAll().isEmpty())
+ }
+
+ @Test
+ void givenListOfPerson_whenUsingCollectionFind_thenShouldReturnMatchingElements() {
+ assertNotNull(personList.find {it.age > 20})
+ assertNull(personList.find {it.age > 30})
+ assertTrue(personList.findAll {it.age > 20}.size() == 3)
+ assertTrue(personList.findAll {it.age > 30}.isEmpty())
+ }
+}
diff --git a/core-groovy/src/test/groovy/com/baeldung/map/MapTest.groovy b/core-groovy/src/test/groovy/com/baeldung/map/MapTest.groovy
new file mode 100644
index 0000000000..f1d528207f
--- /dev/null
+++ b/core-groovy/src/test/groovy/com/baeldung/map/MapTest.groovy
@@ -0,0 +1,148 @@
+package com.baeldung.groovy.map;
+
+import static groovy.test.GroovyAssert.*
+import org.junit.Test
+
+class MapTest{
+
+ @Test
+ void createMap() {
+
+ def emptyMap = [:]
+ assertNotNull(emptyMap)
+
+ assertTrue(emptyMap instanceof java.util.LinkedHashMap)
+
+ def map = [name:"Jerry", age: 42, city: "New York"]
+ assertTrue(map.size() == 3)
+ }
+
+ @Test
+ void addItemsToMap() {
+
+ def map = [name:"Jerry"]
+
+ map["age"] = 42
+
+ map.city = "New York"
+
+ def hobbyLiteral = "hobby"
+ def hobbyMap = [(hobbyLiteral): "Singing"]
+ map.putAll(hobbyMap)
+
+ assertTrue(map == [name:"Jerry", age: 42, city: "New York", hobby:"Singing"])
+ assertTrue(hobbyMap.hobby == "Singing")
+ assertTrue(hobbyMap[hobbyLiteral] == "Singing")
+
+ map.plus([1:20]) // returns new map
+
+ map << [2:30]
+
+ }
+
+ @Test
+ void getItemsFromMap() {
+
+ def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
+
+ assertTrue(map["name"] == "Jerry")
+
+ assertTrue(map.name == "Jerry")
+
+ def propertyAge = "age"
+ assertTrue(map[propertyAge] == 42)
+ }
+
+ @Test
+ void removeItemsFromMap() {
+
+ def map = [1:20, a:30, 2:42, 4:34, ba:67, 6:39, 7:49]
+
+ def minusMap = map.minus([2:42, 4:34]);
+ assertTrue(minusMap == [1:20, a:30, ba:67, 6:39, 7:49])
+
+ minusMap.removeAll{it -> it.key instanceof String}
+ assertTrue( minusMap == [ 1:20, 6:39, 7:49])
+
+ minusMap.retainAll{it -> it.value %2 == 0}
+ assertTrue( minusMap == [1:20])
+ }
+
+ @Test
+ void iteratingOnMaps(){
+ def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
+
+ map.each{ entry -> println "$entry.key: $entry.value" }
+
+ map.eachWithIndex{ entry, i -> println "$i $entry.key: $entry.value" }
+
+ map.eachWithIndex{ key, value, i -> println "$i $key: $value" }
+ }
+
+ @Test
+ void filteringAndSearchingMaps(){
+ def map = [name:"Jerry", age: 42, city: "New York", hobby:"Singing"]
+
+ assertTrue(map.find{ it.value == "New York"}.key == "city")
+
+ assertTrue(map.findAll{ it.value == "New York"} == [city : "New York"])
+
+ map.grep{it.value == "New York"}.each{ it -> assertTrue(it.key == "city" && it.value == "New York")}
+
+ assertTrue(map.every{it -> it.value instanceof String} == false)
+
+ assertTrue(map.any{it -> it.value instanceof String} == true)
+ }
+
+ @Test
+ void collect(){
+
+ def map = [1: [name:"Jerry", age: 42, city: "New York"],
+ 2: [name:"Long", age: 25, city: "New York"],
+ 3: [name:"Dustin", age: 29, city: "New York"],
+ 4: [name:"Dustin", age: 34, city: "New York"]]
+
+ def names = map.collect{entry -> entry.value.name} // returns only list
+ assertTrue(names == ["Jerry", "Long", "Dustin", "Dustin"])
+
+ def uniqueNames = map.collect([] as HashSet){entry -> entry.value.name}
+ assertTrue(uniqueNames == ["Jerry", "Long", "Dustin"] as Set)
+
+ def idNames = map.collectEntries{key, value -> [key, value.name]}
+ assertTrue(idNames == [1:"Jerry", 2: "Long", 3:"Dustin", 4: "Dustin"])
+
+ def below30Names = map.findAll{it.value.age < 30}.collect{key, value -> value.name}
+ assertTrue(below30Names == ["Long", "Dustin"])
+
+
+ }
+
+ @Test
+ void group(){
+ def map = [1:20, 2: 40, 3: 11, 4: 93]
+
+ def subMap = map.groupBy{it.value % 2}
+ println subMap
+ assertTrue(subMap == [0:[1:20, 2:40 ], 1:[3:11, 4:93]])
+
+ def keySubMap = map.subMap([1, 2])
+ assertTrue(keySubMap == [1:20, 2:40])
+
+ }
+
+ @Test
+ void sorting(){
+ def map = [ab:20, a: 40, cb: 11, ba: 93]
+
+ def naturallyOrderedMap = map.sort()
+ assertTrue([a:40, ab:20, ba:93, cb:11] == naturallyOrderedMap)
+
+ def compSortedMap = map.sort({ k1, k2 -> k1 <=> k2 } as Comparator)
+ assertTrue([a:40, ab:20, ba:93, cb:11] == compSortedMap)
+
+ def cloSortedMap = map.sort({ it1, it2 -> it1.value <=> it1.value })
+ assertTrue([cb:11, ab:20, a:40, ba:93] == cloSortedMap)
+
+ }
+
+}
diff --git a/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy
index 97ffc50c76..0d6bbed04b 100644
--- a/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy
+++ b/core-groovy/src/test/groovy/com/baeldung/map/MapUnitTest.groovy
@@ -1,10 +1,18 @@
package com.baeldung.map
-import static org.junit.Assert.*
+import com.baeldung.Person
import org.junit.Test
+import static org.junit.Assert.*
+
class MapUnitTest {
+ private final personMap = [
+ Regina : new Person("Regina", "Fitzpatrick", 25),
+ Abagail: new Person("Abagail", "Ballard", 26),
+ Lucian : new Person("Lucian", "Walter", 30)
+ ]
+
@Test
void whenUsingEach_thenMapIsIterated() {
def map = [
@@ -63,7 +71,7 @@ class MapUnitTest {
'FF6347' : 'Tomato',
'FF4500' : 'Orange Red'
]
-
+
map.eachWithIndex { key, val, index ->
def indent = ((index == 0 || index % 2 == 0) ? " " : "")
println "$indent Hex Code: $key = Color Name: $val"
@@ -82,4 +90,65 @@ class MapUnitTest {
println "Hex Code: $entry.key = Color Name: $entry.value"
}
}
+
+ @Test
+ void whenMapContainsKeyElement_thenCheckReturnsTrue() {
+ def map = [a: 'd', b: 'e', c: 'f']
+
+ assertTrue(map.containsKey('a'))
+ assertFalse(map.containsKey('e'))
+ assertTrue(map.containsValue('e'))
+ }
+
+ @Test
+ void whenMapContainsKeyElement_thenCheckByMembershipReturnsTrue() {
+ def map = [a: 'd', b: 'e', c: 'f']
+
+ assertTrue('a' in map)
+ assertFalse('f' in map)
+ }
+
+ @Test
+ void whenMapContainsFalseBooleanValues_thenCheckReturnsFalse() {
+ def map = [a: true, b: false, c: null]
+
+ assertTrue(map.containsKey('b'))
+ assertTrue('a' in map)
+ assertFalse('b' in map)
+ assertFalse('c' in map)
+ }
+
+ @Test
+ void givenMapOfPerson_whenUsingStreamMatching_thenShouldEvaluateMap() {
+ assertTrue(personMap.keySet().stream().anyMatch {it == "Regina"})
+ assertFalse(personMap.keySet().stream().allMatch {it == "Albert"})
+ assertFalse(personMap.values().stream().allMatch {it.age < 30})
+ assertTrue(personMap.entrySet().stream().anyMatch {it.key == "Abagail" && it.value.lastname == "Ballard"})
+ }
+
+ @Test
+ void givenMapOfPerson_whenUsingCollectionMatching_thenShouldEvaluateMap() {
+ assertTrue(personMap.keySet().any {it == "Regina"})
+ assertFalse(personMap.keySet().every {it == "Albert"})
+ assertFalse(personMap.values().every {it.age < 30})
+ assertTrue(personMap.any {firstname, person -> firstname == "Abagail" && person.lastname == "Ballard"})
+ }
+
+ @Test
+ void givenMapOfPerson_whenUsingCollectionFind_thenShouldReturnElements() {
+ assertNotNull(personMap.find {it.key == "Abagail" && it.value.lastname == "Ballard"})
+ assertTrue(personMap.findAll {it.value.age > 20}.size() == 3)
+ }
+
+ @Test
+ void givenMapOfPerson_whenUsingStreamFind_thenShouldReturnElements() {
+ assertTrue(
+ personMap.entrySet().stream()
+ .filter {it.key == "Abagail" && it.value.lastname == "Ballard"}
+ .findAny().isPresent())
+ assertTrue(
+ personMap.entrySet().stream()
+ .filter {it.value.age > 20}
+ .findAll().size() == 3)
+ }
}
diff --git a/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy b/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy
new file mode 100644
index 0000000000..1248c9ac91
--- /dev/null
+++ b/core-groovy/src/test/groovy/com/baeldung/set/SetUnitTest.groovy
@@ -0,0 +1,16 @@
+package com.baeldung.set
+
+import org.junit.Test
+
+import static org.junit.Assert.assertTrue
+
+class SetUnitTest {
+
+ @Test
+ void whenSetContainsElement_thenCheckReturnsTrue() {
+ def set = ['a', 'b', 'c'] as Set
+
+ assertTrue(set.contains('a'))
+ assertTrue('a' in set)
+ }
+}
\ No newline at end of file
diff --git a/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy b/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy
new file mode 100644
index 0000000000..3865bc73fa
--- /dev/null
+++ b/core-groovy/src/test/groovy/com/baeldung/strings/StringMatchingSpec.groovy
@@ -0,0 +1,44 @@
+package com.baeldung.strings
+
+import spock.lang.Specification
+
+import java.util.regex.Pattern
+
+class StringMatchingSpec extends Specification {
+
+ def "pattern operator example"() {
+ given: "a pattern"
+ def p = ~'foo'
+
+ expect:
+ p instanceof Pattern
+
+ and: "you can use slash strings to avoid escaping of blackslash"
+ def digitPattern = ~/\d*/
+ digitPattern.matcher('4711').matches()
+ }
+
+ def "match operator example"() {
+ expect:
+ 'foobar' ==~ /.*oba.*/
+
+ and: "matching is strict"
+ !('foobar' ==~ /foo/)
+ }
+
+ def "find operator example"() {
+ when: "using the find operator"
+ def matcher = 'foo and bar, baz and buz' =~ /(\w+) and (\w+)/
+
+ then: "will find groups"
+ matcher.size() == 2
+
+ and: "can access groups using array"
+ matcher[0][0] == 'foo and bar'
+ matcher[1][2] == 'buz'
+
+ and: "you can use it as a predicate"
+ 'foobarbaz' =~ /bar/
+ }
+
+}
diff --git a/core-java-11/README.md b/core-java-11/README.md
deleted file mode 100644
index 3c8b94fa28..0000000000
--- a/core-java-11/README.md
+++ /dev/null
@@ -1,6 +0,0 @@
-### Relevant articles
-
-- [Java 11 Single File Source Code](https://www.baeldung.com/java-single-file-source-code)
-- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params)
-- [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api)
-- [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control)
diff --git a/core-java-8/src/main/java/com/baeldung/Adder.java b/core-java-8/src/main/java/com/baeldung/Adder.java
deleted file mode 100644
index e3e100f121..0000000000
--- a/core-java-8/src/main/java/com/baeldung/Adder.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package com.baeldung;
-
-import java.util.function.Consumer;
-import java.util.function.Function;
-
-public interface Adder {
-
- String addWithFunction(Function f);
-
- void addWithConsumer(Consumer f);
-
-}
diff --git a/core-java-8/src/main/java/com/baeldung/AdderImpl.java b/core-java-8/src/main/java/com/baeldung/AdderImpl.java
deleted file mode 100644
index 7852934d55..0000000000
--- a/core-java-8/src/main/java/com/baeldung/AdderImpl.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.baeldung;
-
-
-import java.util.function.Consumer;
-import java.util.function.Function;
-
-public class AdderImpl implements Adder {
-
- @Override
- public String addWithFunction(final Function f) {
- return f.apply("Something ");
- }
-
- @Override
- public void addWithConsumer(final Consumer f) {
- }
-
-}
diff --git a/core-java-9/README.md b/core-java-9/README.md
deleted file mode 100644
index d9586ba684..0000000000
--- a/core-java-9/README.md
+++ /dev/null
@@ -1,29 +0,0 @@
-=========
-
-## Core Java 9 Examples
-
-[Java 9 New Features](http://www.baeldung.com/new-java-9)
-
-### Relevant Articles:
-- [Java 9 Stream API Improvements](http://www.baeldung.com/java-9-stream-api)
-- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
-- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
-- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java-9-completablefuture)
-- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
-- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)
-- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
-- [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional)
-- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
-- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
-- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
-- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client)
-- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
-- [Introduction to Chronicle Queue](http://www.baeldung.com/java-chronicle-queue)
-- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)
-- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
-- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)
-- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
-- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
-- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
-- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
-- [Immutable Set in Java](https://www.baeldung.com/java-immutable-set)
diff --git a/core-java-arrays/README.MD b/core-java-arrays/README.MD
new file mode 100644
index 0000000000..9ee6998784
--- /dev/null
+++ b/core-java-arrays/README.MD
@@ -0,0 +1,3 @@
+## Relevant Articles
+
+- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
diff --git a/core-java-arrays/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java b/core-java-arrays/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java
new file mode 100644
index 0000000000..26a4ca7ef4
--- /dev/null
+++ b/core-java-arrays/src/main/java/com/baeldung/array/conversions/StreamArrayConversion.java
@@ -0,0 +1,52 @@
+package com.baeldung.array.conversions;
+
+import java.util.Arrays;
+import java.util.function.IntFunction;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
+public class StreamArrayConversion {
+
+ public static String[] stringStreamToStringArrayUsingFunctionalInterface(Stream stringStream) {
+ IntFunction intFunction = new IntFunction() {
+ @Override
+ public String[] apply(int value) {
+ return new String[value];
+ }
+ };
+
+ return stringStream.toArray(intFunction);
+ }
+
+ public static String[] stringStreamToStringArrayUsingMethodReference(Stream stringStream) {
+ return stringStream.toArray(String[]::new);
+ }
+
+ public static String[] stringStreamToStringArrayUsingLambda(Stream stringStream) {
+ return stringStream.toArray(value -> new String[value]);
+ }
+
+ public static Integer[] integerStreamToIntegerArray(Stream integerStream) {
+ return integerStream.toArray(Integer[]::new);
+ }
+
+ public static int[] intStreamToPrimitiveIntArray(Stream integerStream) {
+ return integerStream.mapToInt(i -> i).toArray();
+ }
+
+ public static Stream stringArrayToStreamUsingArraysStream(String[] stringArray) {
+ return Arrays.stream(stringArray);
+ }
+
+ public static Stream stringArrayToStreamUsingStreamOf(String[] stringArray) {
+ return Stream.of(stringArray);
+ }
+
+ public static IntStream primitiveIntArrayToStreamUsingArraysStream(int[] intArray) {
+ return Arrays.stream(intArray);
+ }
+
+ public static Stream primitiveIntArrayToStreamUsingStreamOf(int[] intArray) {
+ return Stream.of(intArray);
+ }
+}
diff --git a/core-java-arrays/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java b/core-java-arrays/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java
new file mode 100644
index 0000000000..d2173fea5b
--- /dev/null
+++ b/core-java-arrays/src/test/java/com/baeldung/array/conversions/StreamArrayConversionUnitTest.java
@@ -0,0 +1,70 @@
+package com.baeldung.array.conversions;
+
+import static com.baeldung.array.conversions.StreamArrayConversion.intStreamToPrimitiveIntArray;
+import static com.baeldung.array.conversions.StreamArrayConversion.integerStreamToIntegerArray;
+import static com.baeldung.array.conversions.StreamArrayConversion.stringStreamToStringArrayUsingFunctionalInterface;
+import static com.baeldung.array.conversions.StreamArrayConversion.stringStreamToStringArrayUsingLambda;
+import static com.baeldung.array.conversions.StreamArrayConversion.stringStreamToStringArrayUsingMethodReference;
+import static com.baeldung.array.conversions.StreamArrayConversion.stringArrayToStreamUsingArraysStream;
+import static com.baeldung.array.conversions.StreamArrayConversion.stringArrayToStreamUsingStreamOf;
+import static com.baeldung.array.conversions.StreamArrayConversion.primitiveIntArrayToStreamUsingArraysStream;
+import static com.baeldung.array.conversions.StreamArrayConversion.primitiveIntArrayToStreamUsingStreamOf;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import com.google.common.collect.Iterators;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+import org.junit.Test;
+
+public class StreamArrayConversionUnitTest {
+
+ private String[] stringArray = new String[]{"baeldung", "convert", "to", "string", "array"};
+ private Integer[] integerArray = new Integer[]{1, 2, 3, 4, 5, 6, 7};
+ private int[] intPrimitiveArray = new int[]{1, 2, 3, 4, 5, 6, 7};
+
+ @Test
+ public void givenStringStream_thenConvertToStringArrayUsingFunctionalInterface() {
+ Stream stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
+ assertArrayEquals(stringArray, stringStreamToStringArrayUsingFunctionalInterface(stringStream));
+ }
+
+ @Test
+ public void givenStringStream_thenConvertToStringArrayUsingMethodReference() {
+ Stream stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
+ assertArrayEquals(stringArray, stringStreamToStringArrayUsingMethodReference(stringStream));
+ }
+
+ @Test
+ public void givenStringStream_thenConvertToStringArrayUsingLambda() {
+ Stream stringStream = Stream.of("baeldung", "convert", "to", "string", "array");
+ assertArrayEquals(stringArray, stringStreamToStringArrayUsingLambda(stringStream));
+ }
+
+ @Test
+ public void givenIntegerStream_thenConvertToIntegerArray() {
+ Stream integerStream = Stream.of(1, 2, 3, 4, 5, 6, 7);
+ assertArrayEquals(integerArray, integerStreamToIntegerArray(integerStream));
+ }
+
+ @Test
+ public void givenIntStream_thenConvertToIntegerArray() {
+ Stream integerStream = IntStream.rangeClosed(1, 7).boxed();
+ assertArrayEquals(intPrimitiveArray, intStreamToPrimitiveIntArray(integerStream));
+ }
+
+ @Test
+ public void givenStringArray_whenConvertedTwoWays_thenConvertedStreamsAreEqual() {
+ assertTrue(Iterators
+ .elementsEqual(stringArrayToStreamUsingArraysStream(stringArray).iterator(),
+ stringArrayToStreamUsingStreamOf(stringArray).iterator()));
+ }
+
+ @Test
+ public void givenPrimitiveArray_whenConvertedTwoWays_thenConvertedStreamsAreNotEqual() {
+ assertFalse(Iterators.elementsEqual(
+ primitiveIntArrayToStreamUsingArraysStream(intPrimitiveArray).iterator(),
+ primitiveIntArrayToStreamUsingStreamOf(intPrimitiveArray).iterator()));
+ }
+}
diff --git a/core-java-collections-list/README.md b/core-java-collections-list/README.md
deleted file mode 100644
index 3a4a7c69e8..0000000000
--- a/core-java-collections-list/README.md
+++ /dev/null
@@ -1,30 +0,0 @@
-=========
-
-## Core Java Collections List Cookbooks and Examples
-
-### Relevant Articles:
-- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
-- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
-- [Random List Element](http://www.baeldung.com/java-random-list-element)
-- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
-- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
-- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
-- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
-- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
-- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
-- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
-- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
-- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
-- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
-- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
-- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
-- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
-- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
-- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
-- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
-- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
-- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
-- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
-- [Intersection of Two Lists in Java](https://www.baeldung.com/java-lists-intersection)
-- [Multi Dimensional ArrayList in Java](https://www.baeldung.com/java-multi-dimensional-arraylist)
-- [Determine If All Elements Are the Same in a Java List](https://www.baeldung.com/java-list-all-equal)
diff --git a/core-java-lambdas/README.md b/core-java-lambdas/README.md
new file mode 100644
index 0000000000..5b94953e68
--- /dev/null
+++ b/core-java-lambdas/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Java 9 java.lang.Module API](https://www.baeldung.com/java-lambda-effectively-final-local-variables)
diff --git a/core-java-lang-syntax/src/main/java/com/baeldung/enums/README.md b/core-java-lang-syntax/src/main/java/com/baeldung/enums/README.md
deleted file mode 100644
index 6ccfa725f5..0000000000
--- a/core-java-lang-syntax/src/main/java/com/baeldung/enums/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-### Relevant Articles:
-- [A Guide to Java Enums](http://www.baeldung.com/a-guide-to-java-enums)
diff --git a/core-java-lang/native/nativedatetimeutils.dll b/core-java-lang/native/nativedatetimeutils.dll
deleted file mode 100644
index ecdd388380..0000000000
Binary files a/core-java-lang/native/nativedatetimeutils.dll and /dev/null differ
diff --git a/core-java-modules/README.md b/core-java-modules/README.md
new file mode 100644
index 0000000000..7a7d0a7a1b
--- /dev/null
+++ b/core-java-modules/README.md
@@ -0,0 +1,5 @@
+## Relevant articles:
+
+- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
+- [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel)
+- [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception)
diff --git a/core-java-10/README.md b/core-java-modules/core-java-10/README.md
similarity index 100%
rename from core-java-10/README.md
rename to core-java-modules/core-java-10/README.md
diff --git a/core-java-10/pom.xml b/core-java-modules/core-java-10/pom.xml
similarity index 96%
rename from core-java-10/pom.xml
rename to core-java-modules/core-java-10/pom.xml
index b15f8b5d63..7163619679 100644
--- a/core-java-10/pom.xml
+++ b/core-java-modules/core-java-10/pom.xml
@@ -12,6 +12,7 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
+ ../../
diff --git a/core-java-10/src/main/java/com/baeldung/App.java b/core-java-modules/core-java-10/src/main/java/com/baeldung/App.java
similarity index 100%
rename from core-java-10/src/main/java/com/baeldung/App.java
rename to core-java-modules/core-java-10/src/main/java/com/baeldung/App.java
diff --git a/core-java-10/src/main/java/com/baeldung/graal/CountUppercase.java b/core-java-modules/core-java-10/src/main/java/com/baeldung/graal/CountUppercase.java
similarity index 100%
rename from core-java-10/src/main/java/com/baeldung/graal/CountUppercase.java
rename to core-java-modules/core-java-10/src/main/java/com/baeldung/graal/CountUppercase.java
diff --git a/core-java-modules/core-java-10/src/main/java/com/baeldung/set/CopySets.java b/core-java-modules/core-java-10/src/main/java/com/baeldung/set/CopySets.java
new file mode 100644
index 0000000000..d49724f81d
--- /dev/null
+++ b/core-java-modules/core-java-10/src/main/java/com/baeldung/set/CopySets.java
@@ -0,0 +1,13 @@
+package com.baeldung.set;
+
+import java.util.Set;
+
+public class CopySets {
+
+ // Using Java 10
+ public static Set copyBySetCopyOf(Set original) {
+ Set copy = Set.copyOf(original);
+ return copy;
+ }
+
+}
diff --git a/core-java-11/src/main/resources/logback.xml b/core-java-modules/core-java-10/src/main/resources/logback.xml
similarity index 100%
rename from core-java-11/src/main/resources/logback.xml
rename to core-java-modules/core-java-10/src/main/resources/logback.xml
diff --git a/core-java-10/src/test/java/com/baeldung/AppTest.java b/core-java-modules/core-java-10/src/test/java/com/baeldung/AppTest.java
similarity index 100%
rename from core-java-10/src/test/java/com/baeldung/AppTest.java
rename to core-java-modules/core-java-10/src/test/java/com/baeldung/AppTest.java
diff --git a/core-java-10/src/test/java/com/baeldung/java10/Java10FeaturesUnitTest.java b/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/Java10FeaturesUnitTest.java
similarity index 100%
rename from core-java-10/src/test/java/com/baeldung/java10/Java10FeaturesUnitTest.java
rename to core-java-modules/core-java-10/src/test/java/com/baeldung/java10/Java10FeaturesUnitTest.java
diff --git a/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java b/core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java
similarity index 100%
rename from core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java
rename to core-java-modules/core-java-10/src/test/java/com/baeldung/java10/list/CopyListServiceUnitTest.java
diff --git a/core-java-modules/core-java-11/README.md b/core-java-modules/core-java-11/README.md
new file mode 100644
index 0000000000..11c7d9d388
--- /dev/null
+++ b/core-java-modules/core-java-11/README.md
@@ -0,0 +1,11 @@
+### Relevant articles
+
+- [Java 11 Single File Source Code](https://www.baeldung.com/java-single-file-source-code)
+- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params)
+- [Java 11 String API Additions](https://www.baeldung.com/java-11-string-api)
+- [Java 11 Nest Based Access Control](https://www.baeldung.com/java-nest-based-access-control)
+- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
+- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
+- [Guide to jlink](https://www.baeldung.com/jlink)
+- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
+- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)
diff --git a/core-java-11/pom.xml b/core-java-modules/core-java-11/pom.xml
similarity index 57%
rename from core-java-11/pom.xml
rename to core-java-modules/core-java-11/pom.xml
index a9776d8f3b..4d950bdf8d 100644
--- a/core-java-11/pom.xml
+++ b/core-java-modules/core-java-11/pom.xml
@@ -1,5 +1,7 @@
-
+
4.0.0
com.baeldung
core-java-11
@@ -12,8 +14,23 @@
com.baeldung
parent-modules
1.0.0-SNAPSHOT
+ ../..
+
+
+ com.google.guava
+ guava
+ ${guava.version}
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+
@@ -31,6 +48,8 @@
11
11
+ 27.1-jre
+ 3.11.1
diff --git a/core-java-11/src/main/java/com/baeldung/App.java b/core-java-modules/core-java-11/src/main/java/com/baeldung/App.java
similarity index 100%
rename from core-java-11/src/main/java/com/baeldung/App.java
rename to core-java-modules/core-java-11/src/main/java/com/baeldung/App.java
diff --git a/core-java-11/src/main/java/com/baeldung/Outer.java b/core-java-modules/core-java-11/src/main/java/com/baeldung/Outer.java
similarity index 100%
rename from core-java-11/src/main/java/com/baeldung/Outer.java
rename to core-java-modules/core-java-11/src/main/java/com/baeldung/Outer.java
diff --git a/core-java-11/src/main/java/com/baeldung/add b/core-java-modules/core-java-11/src/main/java/com/baeldung/add
old mode 100755
new mode 100644
similarity index 100%
rename from core-java-11/src/main/java/com/baeldung/add
rename to core-java-modules/core-java-11/src/main/java/com/baeldung/add
diff --git a/core-java-11/src/main/java/com/baeldung/epsilongc/MemoryPolluter.java b/core-java-modules/core-java-11/src/main/java/com/baeldung/epsilongc/MemoryPolluter.java
similarity index 100%
rename from core-java-11/src/main/java/com/baeldung/epsilongc/MemoryPolluter.java
rename to core-java-modules/core-java-11/src/main/java/com/baeldung/epsilongc/MemoryPolluter.java
diff --git a/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java b/core-java-modules/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java
similarity index 97%
rename from core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java
rename to core-java-modules/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java
index fb4abd3bb6..725f969596 100644
--- a/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java
+++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/java11/httpclient/HttpClientExample.java
@@ -1,132 +1,132 @@
-/*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
-package com.baeldung.java11.httpclient;
-
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.http.HttpClient;
-import java.net.http.HttpClient.Version;
-import java.net.http.HttpRequest;
-import java.net.http.HttpRequest.BodyPublishers;
-import java.net.http.HttpResponse;
-import java.net.http.HttpResponse.BodyHandlers;
-import java.net.http.HttpResponse.PushPromiseHandler;
-import java.util.Arrays;
-import java.util.List;
-import java.util.concurrent.CompletableFuture;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-public class HttpClientExample {
-
- public static void main(String[] args) throws Exception {
- httpGetRequest();
- httpPostRequest();
- asynchronousGetRequest();
- asynchronousMultipleRequests();
- pushRequest();
- }
-
- public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
- HttpClient client = HttpClient.newHttpClient();
- HttpRequest request = HttpRequest.newBuilder()
- .version(HttpClient.Version.HTTP_2)
- .uri(URI.create("http://jsonplaceholder.typicode.com/posts/1"))
- .headers("Accept-Enconding", "gzip, deflate")
- .build();
- HttpResponse response = client.send(request, BodyHandlers.ofString());
-
- String responseBody = response.body();
- int responseStatusCode = response.statusCode();
-
- System.out.println("httpGetRequest: " + responseBody);
- System.out.println("httpGetRequest status code: " + responseStatusCode);
- }
-
- public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
- HttpClient client = HttpClient.newBuilder()
- .version(HttpClient.Version.HTTP_2)
- .build();
- HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
- .version(HttpClient.Version.HTTP_2)
- .POST(BodyPublishers.ofString("Sample Post Request"))
- .build();
- HttpResponse response = client.send(request, BodyHandlers.ofString());
- String responseBody = response.body();
- System.out.println("httpPostRequest : " + responseBody);
- }
-
- public static void asynchronousGetRequest() throws URISyntaxException {
- HttpClient client = HttpClient.newHttpClient();
- URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
- HttpRequest request = HttpRequest.newBuilder(httpURI)
- .version(HttpClient.Version.HTTP_2)
- .build();
- CompletableFuture futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
- .thenAccept(resp -> {
- System.out.println("Got pushed response " + resp.uri());
- System.out.println("Response statuscode: " + resp.statusCode());
- System.out.println("Response body: " + resp.body());
- });
- System.out.println("futureResponse" + futureResponse);
-
- }
-
- public static void asynchronousMultipleRequests() throws URISyntaxException {
- HttpClient client = HttpClient.newHttpClient();
- List uris = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
- List requests = uris.stream()
- .map(HttpRequest::newBuilder)
- .map(reqBuilder -> reqBuilder.build())
- .collect(Collectors.toList());
- System.out.println("Got pushed response1 " + requests);
- CompletableFuture.allOf(requests.stream()
- .map(request -> client.sendAsync(request, BodyHandlers.ofString()))
- .toArray(CompletableFuture>[]::new))
- .thenAccept(System.out::println)
- .join();
- }
-
- public static void pushRequest() throws URISyntaxException, InterruptedException {
- System.out.println("Running HTTP/2 Server Push example...");
-
- HttpClient httpClient = HttpClient.newBuilder()
- .version(Version.HTTP_2)
- .build();
-
- HttpRequest pageRequest = HttpRequest.newBuilder()
- .uri(URI.create("https://http2.golang.org/serverpush"))
- .build();
-
- // Interface HttpResponse.PushPromiseHandler
- // void applyPushPromise(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, Function,CompletableFuture>> acceptor)
- httpClient.sendAsync(pageRequest, BodyHandlers.ofString(), pushPromiseHandler())
- .thenAccept(pageResponse -> {
- System.out.println("Page response status code: " + pageResponse.statusCode());
- System.out.println("Page response headers: " + pageResponse.headers());
- String responseBody = pageResponse.body();
- System.out.println(responseBody);
- }).join();
-
- Thread.sleep(1000); // waiting for full response
- }
-
- private static PushPromiseHandler pushPromiseHandler() {
- return (HttpRequest initiatingRequest,
- HttpRequest pushPromiseRequest,
- Function,
- CompletableFuture>> acceptor) -> {
- acceptor.apply(BodyHandlers.ofString())
- .thenAccept(resp -> {
- System.out.println(" Pushed response: " + resp.uri() + ", headers: " + resp.headers());
- });
- System.out.println("Promise request: " + pushPromiseRequest.uri());
- System.out.println("Promise request: " + pushPromiseRequest.headers());
- };
- }
-
-}
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package com.baeldung.java11.httpclient;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpClient.Version;
+import java.net.http.HttpRequest;
+import java.net.http.HttpRequest.BodyPublishers;
+import java.net.http.HttpResponse;
+import java.net.http.HttpResponse.BodyHandlers;
+import java.net.http.HttpResponse.PushPromiseHandler;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+public class HttpClientExample {
+
+ public static void main(String[] args) throws Exception {
+ httpGetRequest();
+ httpPostRequest();
+ asynchronousGetRequest();
+ asynchronousMultipleRequests();
+ pushRequest();
+ }
+
+ public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException {
+ HttpClient client = HttpClient.newHttpClient();
+ HttpRequest request = HttpRequest.newBuilder()
+ .version(HttpClient.Version.HTTP_2)
+ .uri(URI.create("http://jsonplaceholder.typicode.com/posts/1"))
+ .headers("Accept-Enconding", "gzip, deflate")
+ .build();
+ HttpResponse response = client.send(request, BodyHandlers.ofString());
+
+ String responseBody = response.body();
+ int responseStatusCode = response.statusCode();
+
+ System.out.println("httpGetRequest: " + responseBody);
+ System.out.println("httpGetRequest status code: " + responseStatusCode);
+ }
+
+ public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException {
+ HttpClient client = HttpClient.newBuilder()
+ .version(HttpClient.Version.HTTP_2)
+ .build();
+ HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts"))
+ .version(HttpClient.Version.HTTP_2)
+ .POST(BodyPublishers.ofString("Sample Post Request"))
+ .build();
+ HttpResponse response = client.send(request, BodyHandlers.ofString());
+ String responseBody = response.body();
+ System.out.println("httpPostRequest : " + responseBody);
+ }
+
+ public static void asynchronousGetRequest() throws URISyntaxException {
+ HttpClient client = HttpClient.newHttpClient();
+ URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
+ HttpRequest request = HttpRequest.newBuilder(httpURI)
+ .version(HttpClient.Version.HTTP_2)
+ .build();
+ CompletableFuture futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
+ .thenAccept(resp -> {
+ System.out.println("Got pushed response " + resp.uri());
+ System.out.println("Response statuscode: " + resp.statusCode());
+ System.out.println("Response body: " + resp.body());
+ });
+ System.out.println("futureResponse" + futureResponse);
+
+ }
+
+ public static void asynchronousMultipleRequests() throws URISyntaxException {
+ HttpClient client = HttpClient.newHttpClient();
+ List uris = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
+ List requests = uris.stream()
+ .map(HttpRequest::newBuilder)
+ .map(reqBuilder -> reqBuilder.build())
+ .collect(Collectors.toList());
+ System.out.println("Got pushed response1 " + requests);
+ CompletableFuture.allOf(requests.stream()
+ .map(request -> client.sendAsync(request, BodyHandlers.ofString()))
+ .toArray(CompletableFuture>[]::new))
+ .thenAccept(System.out::println)
+ .join();
+ }
+
+ public static void pushRequest() throws URISyntaxException, InterruptedException {
+ System.out.println("Running HTTP/2 Server Push example...");
+
+ HttpClient httpClient = HttpClient.newBuilder()
+ .version(Version.HTTP_2)
+ .build();
+
+ HttpRequest pageRequest = HttpRequest.newBuilder()
+ .uri(URI.create("https://http2.golang.org/serverpush"))
+ .build();
+
+ // Interface HttpResponse.PushPromiseHandler
+ // void applyPushPromise(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, Function,CompletableFuture>> acceptor)
+ httpClient.sendAsync(pageRequest, BodyHandlers.ofString(), pushPromiseHandler())
+ .thenAccept(pageResponse -> {
+ System.out.println("Page response status code: " + pageResponse.statusCode());
+ System.out.println("Page response headers: " + pageResponse.headers());
+ String responseBody = pageResponse.body();
+ System.out.println(responseBody);
+ }).join();
+
+ Thread.sleep(1000); // waiting for full response
+ }
+
+ private static PushPromiseHandler pushPromiseHandler() {
+ return (HttpRequest initiatingRequest,
+ HttpRequest pushPromiseRequest,
+ Function,
+ CompletableFuture>> acceptor) -> {
+ acceptor.apply(BodyHandlers.ofString())
+ .thenAccept(resp -> {
+ System.out.println(" Pushed response: " + resp.uri() + ", headers: " + resp.headers());
+ });
+ System.out.println("Promise request: " + pushPromiseRequest.uri());
+ System.out.println("Promise request: " + pushPromiseRequest.headers());
+ };
+ }
+
+}
diff --git a/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/Person.java b/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/Person.java
new file mode 100644
index 0000000000..3c93e08194
--- /dev/null
+++ b/core-java-modules/core-java-11/src/main/java/com/baeldung/predicate/not/Person.java
@@ -0,0 +1,19 @@
+package com.baeldung.predicate.not;
+
+public class Person {
+ private static final int ADULT_AGE = 18;
+
+ private int age;
+
+ public Person(int age) {
+ this.age = age;
+ }
+
+ public boolean isAdult() {
+ return age >= ADULT_AGE;
+ }
+
+ public boolean isNotAdult() {
+ return !isAdult();
+ }
+}
diff --git a/core-java-8/src/main/resources/logback.xml b/core-java-modules/core-java-11/src/main/resources/logback.xml
similarity index 100%
rename from core-java-8/src/main/resources/logback.xml
rename to core-java-modules/core-java-11/src/main/resources/logback.xml
diff --git a/core-java-modules/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java b/core-java-modules/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java
new file mode 100644
index 0000000000..47fe62ba40
--- /dev/null
+++ b/core-java-modules/core-java-11/src/modules/jlinkModule/com/baeldung/jlink/HelloWorld.java
@@ -0,0 +1,12 @@
+package com.baeldung.jlink;
+
+import java.util.logging.Logger;
+
+public class HelloWorld {
+
+ private static final Logger LOG = Logger.getLogger(HelloWorld.class.getName());
+
+ public static void main(String[] args) {
+ LOG.info("Hello World!");
+ }
+}
diff --git a/core-java-modules/core-java-11/src/modules/jlinkModule/module-info.java b/core-java-modules/core-java-11/src/modules/jlinkModule/module-info.java
new file mode 100644
index 0000000000..0587c65b53
--- /dev/null
+++ b/core-java-modules/core-java-11/src/modules/jlinkModule/module-info.java
@@ -0,0 +1,3 @@
+module jlinkModule {
+ requires java.logging;
+}
\ No newline at end of file
diff --git a/core-java-11/src/test/java/com/baeldung/AppTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/AppUnitTest.java
similarity index 82%
rename from core-java-11/src/test/java/com/baeldung/AppTest.java
rename to core-java-modules/core-java-11/src/test/java/com/baeldung/AppUnitTest.java
index c9f61455bd..73eb8e661a 100644
--- a/core-java-11/src/test/java/com/baeldung/AppTest.java
+++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/AppUnitTest.java
@@ -7,7 +7,7 @@ import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
-public class AppTest
+public class AppUnitTest
extends TestCase
{
/**
@@ -15,7 +15,7 @@ public class AppTest
*
* @param testName name of the test case
*/
- public AppTest( String testName )
+ public AppUnitTest(String testName )
{
super( testName );
}
@@ -25,7 +25,7 @@ public class AppTest
*/
public static Test suite()
{
- return new TestSuite( AppTest.class );
+ return new TestSuite( AppUnitTest.class );
}
/**
diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/EmptyStringToEmptyOptionalUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/EmptyStringToEmptyOptionalUnitTest.java
new file mode 100644
index 0000000000..cc429209d4
--- /dev/null
+++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/EmptyStringToEmptyOptionalUnitTest.java
@@ -0,0 +1,32 @@
+package com.baeldung;
+
+import com.google.common.base.Strings;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.Optional;
+import java.util.function.Predicate;
+
+public class EmptyStringToEmptyOptionalUnitTest {
+
+ @Test
+ public void givenEmptyString_whenFilteringOnOptional_thenEmptyOptionalIsReturned() {
+ String str = "";
+ Optional opt = Optional.ofNullable(str).filter(s -> !s.isEmpty());
+ Assert.assertFalse(opt.isPresent());
+ }
+
+ @Test
+ public void givenEmptyString_whenFilteringOnOptionalInJava11_thenEmptyOptionalIsReturned() {
+ String str = "";
+ Optional opt = Optional.ofNullable(str).filter(Predicate.not(String::isEmpty));
+ Assert.assertFalse(opt.isPresent());
+ }
+
+ @Test
+ public void givenEmptyString_whenPassingResultOfEmptyToNullToOfNullable_thenEmptyOptionalIsReturned() {
+ String str = "";
+ Optional opt = Optional.ofNullable(Strings.emptyToNull(str));
+ Assert.assertFalse(opt.isPresent());
+ }
+}
diff --git a/core-java-11/src/test/java/com/baeldung/NewStringAPIUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/NewStringAPIUnitTest.java
similarity index 100%
rename from core-java-11/src/test/java/com/baeldung/NewStringAPIUnitTest.java
rename to core-java-modules/core-java-11/src/test/java/com/baeldung/NewStringAPIUnitTest.java
diff --git a/core-java-11/src/test/java/com/baeldung/OuterUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/OuterUnitTest.java
similarity index 100%
rename from core-java-11/src/test/java/com/baeldung/OuterUnitTest.java
rename to core-java-modules/core-java-11/src/test/java/com/baeldung/OuterUnitTest.java
diff --git a/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientUnitTest.java
similarity index 97%
rename from core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientTest.java
rename to core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientUnitTest.java
index bade666636..42f56838c4 100644
--- a/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientTest.java
+++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpClientUnitTest.java
@@ -1,240 +1,240 @@
-package com.baeldung.java11.httpclient.test;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.IOException;
-import java.net.Authenticator;
-import java.net.CookieManager;
-import java.net.CookiePolicy;
-import java.net.HttpURLConnection;
-import java.net.PasswordAuthentication;
-import java.net.ProxySelector;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.http.HttpClient;
-import java.net.http.HttpRequest;
-import java.net.http.HttpResponse;
-import java.net.http.HttpResponse.BodyHandlers;
-import java.util.Arrays;
-import java.util.List;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CompletionException;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
-import org.junit.jupiter.api.Test;
-
-public class HttpClientTest {
-
- @Test
- public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/post"))
- .headers("Content-Type", "text/plain;charset=UTF-8")
- .POST(HttpRequest.BodyPublishers.ofString("Sample body"))
- .build();
-
-
- HttpResponse response = HttpClient.newBuilder()
- .proxy(ProxySelector.getDefault())
- .build()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- assertThat(response.body(), containsString("Sample body"));
- }
-
- @Test
- public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("http://stackoverflow.com"))
- .version(HttpClient.Version.HTTP_1_1)
- .GET()
- .build();
- HttpResponse response = HttpClient.newBuilder()
- .build()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
- assertThat(response.body(), containsString("https://stackoverflow.com/"));
- }
-
- @Test
- public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("http://stackoverflow.com"))
- .version(HttpClient.Version.HTTP_1_1)
- .GET()
- .build();
- HttpResponse response = HttpClient.newBuilder()
- .followRedirects(HttpClient.Redirect.ALWAYS)
- .build()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- assertThat(response.request()
- .uri()
- .toString(), equalTo("https://stackoverflow.com/"));
- }
-
- @Test
- public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/basic-auth"))
- .GET()
- .build();
- HttpResponse response = HttpClient.newBuilder()
- .authenticator(new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication("postman", "password".toCharArray());
- }
- })
- .build()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- }
-
- @Test
- public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/post"))
- .headers("Content-Type", "text/plain;charset=UTF-8")
- .POST(HttpRequest.BodyPublishers.ofString("Sample body"))
- .build();
- CompletableFuture> response = HttpClient.newBuilder()
- .build()
- .sendAsync(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.get()
- .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- }
-
- @Test
- public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/get"))
- .GET()
- .build();
-
- ExecutorService executorService = Executors.newFixedThreadPool(2);
-
- CompletableFuture> response1 = HttpClient.newBuilder()
- .executor(executorService)
- .build()
- .sendAsync(request, HttpResponse.BodyHandlers.ofString());
-
- CompletableFuture> response2 = HttpClient.newBuilder()
- .executor(executorService)
- .build()
- .sendAsync(request, HttpResponse.BodyHandlers.ofString());
-
- CompletableFuture> response3 = HttpClient.newBuilder()
- .executor(executorService)
- .build()
- .sendAsync(request, HttpResponse.BodyHandlers.ofString());
-
- CompletableFuture.allOf(response1, response2, response3)
- .join();
-
- assertThat(response1.get()
- .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- assertThat(response2.get()
- .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- assertThat(response3.get()
- .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- }
-
- @Test
- public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/get"))
- .GET()
- .build();
-
- HttpClient httpClient = HttpClient.newBuilder()
- .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
- .build();
-
- httpClient.send(request, HttpResponse.BodyHandlers.ofString());
-
- assertTrue(httpClient.cookieHandler()
- .isPresent());
- }
-
- @Test
- public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/get"))
- .GET()
- .build();
-
- HttpClient httpClient = HttpClient.newBuilder()
- .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
- .build();
-
- httpClient.send(request, HttpResponse.BodyHandlers.ofString());
-
- assertTrue(httpClient.cookieHandler()
- .isPresent());
- }
-
- @Test
- public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
- List targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));
-
- HttpClient client = HttpClient.newHttpClient();
-
- List> futures = targets.stream()
- .map(target -> client.sendAsync(HttpRequest.newBuilder(target)
- .GET()
- .build(), HttpResponse.BodyHandlers.ofString())
- .thenApply(response -> response.body()))
- .collect(Collectors.toList());
-
- CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
- .join();
-
- if (futures.get(0)
- .get()
- .contains("foo1")) {
- assertThat(futures.get(0)
- .get(), containsString("bar1"));
- assertThat(futures.get(1)
- .get(), containsString("bar2"));
- } else {
- assertThat(futures.get(1)
- .get(), containsString("bar2"));
- assertThat(futures.get(1)
- .get(), containsString("bar1"));
- }
-
- }
-
- @Test
- public void completeExceptionallyExample() {
- CompletableFuture cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase,
- CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
- CompletableFuture exceptionHandler = cf.handle((s, th) -> { return (th != null) ? "message upon cancel" : ""; });
- cf.completeExceptionally(new RuntimeException("completed exceptionally"));
- assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally());
- try {
- cf.join();
- fail("Should have thrown an exception");
- } catch (CompletionException ex) { // just for testing
- assertEquals("completed exceptionally", ex.getCause().getMessage());
- }
-
- assertEquals("message upon cancel", exceptionHandler.join());
- }
-
-}
+package com.baeldung.java11.httpclient.test;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.net.Authenticator;
+import java.net.CookieManager;
+import java.net.CookiePolicy;
+import java.net.HttpURLConnection;
+import java.net.PasswordAuthentication;
+import java.net.ProxySelector;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.http.HttpResponse.BodyHandlers;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.Test;
+
+public class HttpClientUnitTest {
+
+ @Test
+ public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/post"))
+ .headers("Content-Type", "text/plain;charset=UTF-8")
+ .POST(HttpRequest.BodyPublishers.ofString("Sample body"))
+ .build();
+
+
+ HttpResponse response = HttpClient.newBuilder()
+ .proxy(ProxySelector.getDefault())
+ .build()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ assertThat(response.body(), containsString("Sample body"));
+ }
+
+ @Test
+ public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("http://stackoverflow.com"))
+ .version(HttpClient.Version.HTTP_1_1)
+ .GET()
+ .build();
+ HttpResponse response = HttpClient.newBuilder()
+ .build()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
+ assertThat(response.body(), containsString("https://stackoverflow.com/"));
+ }
+
+ @Test
+ public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("http://stackoverflow.com"))
+ .version(HttpClient.Version.HTTP_1_1)
+ .GET()
+ .build();
+ HttpResponse response = HttpClient.newBuilder()
+ .followRedirects(HttpClient.Redirect.ALWAYS)
+ .build()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ assertThat(response.request()
+ .uri()
+ .toString(), equalTo("https://stackoverflow.com/"));
+ }
+
+ @Test
+ public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/basic-auth"))
+ .GET()
+ .build();
+ HttpResponse response = HttpClient.newBuilder()
+ .authenticator(new Authenticator() {
+ @Override
+ protected PasswordAuthentication getPasswordAuthentication() {
+ return new PasswordAuthentication("postman", "password".toCharArray());
+ }
+ })
+ .build()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ }
+
+ @Test
+ public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/post"))
+ .headers("Content-Type", "text/plain;charset=UTF-8")
+ .POST(HttpRequest.BodyPublishers.ofString("Sample body"))
+ .build();
+ CompletableFuture> response = HttpClient.newBuilder()
+ .build()
+ .sendAsync(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.get()
+ .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ }
+
+ @Test
+ public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/get"))
+ .GET()
+ .build();
+
+ ExecutorService executorService = Executors.newFixedThreadPool(2);
+
+ CompletableFuture> response1 = HttpClient.newBuilder()
+ .executor(executorService)
+ .build()
+ .sendAsync(request, HttpResponse.BodyHandlers.ofString());
+
+ CompletableFuture> response2 = HttpClient.newBuilder()
+ .executor(executorService)
+ .build()
+ .sendAsync(request, HttpResponse.BodyHandlers.ofString());
+
+ CompletableFuture> response3 = HttpClient.newBuilder()
+ .executor(executorService)
+ .build()
+ .sendAsync(request, HttpResponse.BodyHandlers.ofString());
+
+ CompletableFuture.allOf(response1, response2, response3)
+ .join();
+
+ assertThat(response1.get()
+ .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ assertThat(response2.get()
+ .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ assertThat(response3.get()
+ .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ }
+
+ @Test
+ public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/get"))
+ .GET()
+ .build();
+
+ HttpClient httpClient = HttpClient.newBuilder()
+ .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
+ .build();
+
+ httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertTrue(httpClient.cookieHandler()
+ .isPresent());
+ }
+
+ @Test
+ public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/get"))
+ .GET()
+ .build();
+
+ HttpClient httpClient = HttpClient.newBuilder()
+ .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
+ .build();
+
+ httpClient.send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertTrue(httpClient.cookieHandler()
+ .isPresent());
+ }
+
+ @Test
+ public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
+ List targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));
+
+ HttpClient client = HttpClient.newHttpClient();
+
+ List> futures = targets.stream()
+ .map(target -> client.sendAsync(HttpRequest.newBuilder(target)
+ .GET()
+ .build(), HttpResponse.BodyHandlers.ofString())
+ .thenApply(response -> response.body()))
+ .collect(Collectors.toList());
+
+ CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
+ .join();
+
+ if (futures.get(0)
+ .get()
+ .contains("foo1")) {
+ assertThat(futures.get(0)
+ .get(), containsString("bar1"));
+ assertThat(futures.get(1)
+ .get(), containsString("bar2"));
+ } else {
+ assertThat(futures.get(1)
+ .get(), containsString("bar2"));
+ assertThat(futures.get(1)
+ .get(), containsString("bar1"));
+ }
+
+ }
+
+ @Test
+ public void completeExceptionallyExample() {
+ CompletableFuture cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase,
+ CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
+ CompletableFuture exceptionHandler = cf.handle((s, th) -> { return (th != null) ? "message upon cancel" : ""; });
+ cf.completeExceptionally(new RuntimeException("completed exceptionally"));
+ assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally());
+ try {
+ cf.join();
+ fail("Should have thrown an exception");
+ } catch (CompletionException ex) { // just for testing
+ assertEquals("completed exceptionally", ex.getCause().getMessage());
+ }
+
+ assertEquals("message upon cancel", exceptionHandler.join());
+ }
+
+}
diff --git a/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestUnitTest.java
similarity index 97%
rename from core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestTest.java
rename to core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestUnitTest.java
index 7d138bd8d5..b87e6b3c6e 100644
--- a/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestTest.java
+++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpRequestUnitTest.java
@@ -1,168 +1,168 @@
-package com.baeldung.java11.httpclient.test;
-
-import static java.time.temporal.ChronoUnit.SECONDS;
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.net.HttpURLConnection;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.http.HttpClient;
-import java.net.http.HttpRequest;
-import java.net.http.HttpResponse;
-import java.nio.file.Paths;
-import java.security.NoSuchAlgorithmException;
-import java.time.Duration;
-
-import org.junit.Test;
-
-public class HttpRequestTest {
-
- @Test
- public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/get"))
- .GET()
- .build();
-
- HttpResponse response = HttpClient.newHttpClient()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- }
-
- @Test
- public void shouldUseHttp2WhenWebsiteUsesHttp2() throws IOException, InterruptedException, URISyntaxException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://stackoverflow.com"))
- .version(HttpClient.Version.HTTP_2)
- .GET()
- .build();
- HttpResponse response = HttpClient.newHttpClient()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
- }
-
- @Test
- public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/get"))
- .version(HttpClient.Version.HTTP_2)
- .GET()
- .build();
-
- HttpResponse response = HttpClient.newHttpClient()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1));
- }
-
- @Test
- public void shouldReturnStatusOKWhenSendGetRequestWithDummyHeaders() throws IOException, InterruptedException, URISyntaxException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/get"))
- .headers("key1", "value1", "key2", "value2")
- .GET()
- .build();
-
- HttpResponse response = HttpClient.newHttpClient()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- }
-
- @Test
- public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/get"))
- .timeout(Duration.of(10, SECONDS))
- .GET()
- .build();
-
- HttpResponse response = HttpClient.newHttpClient()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- }
-
- @Test
- public void shouldReturnNoContentWhenPostWithNoBody() throws IOException, InterruptedException, URISyntaxException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/post"))
- .POST(HttpRequest.BodyPublishers.noBody())
- .build();
-
- HttpResponse response = HttpClient.newHttpClient()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- }
-
- @Test
- public void shouldReturnSampleDataContentWhenPostWithBodyText() throws IOException, InterruptedException, URISyntaxException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/post"))
- .headers("Content-Type", "text/plain;charset=UTF-8")
- .POST(HttpRequest.BodyPublishers.ofString("Sample request body"))
- .build();
-
- HttpResponse response = HttpClient.newHttpClient()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- assertThat(response.body(), containsString("Sample request body"));
- }
-
- @Test
- public void shouldReturnSampleDataContentWhenPostWithInputStream() throws IOException, InterruptedException, URISyntaxException {
- byte[] sampleData = "Sample request body".getBytes();
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/post"))
- .headers("Content-Type", "text/plain;charset=UTF-8")
- .POST(HttpRequest.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(sampleData)))
- .build();
-
- HttpResponse response = HttpClient.newHttpClient()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- assertThat(response.body(), containsString("Sample request body"));
- }
-
- @Test
- public void shouldReturnSampleDataContentWhenPostWithByteArrayProcessorStream() throws IOException, InterruptedException, URISyntaxException {
- byte[] sampleData = "Sample request body".getBytes();
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/post"))
- .headers("Content-Type", "text/plain;charset=UTF-8")
- .POST(HttpRequest.BodyPublishers.ofByteArray(sampleData))
- .build();
-
- HttpResponse response = HttpClient.newHttpClient()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- assertThat(response.body(), containsString("Sample request body"));
- }
-
- @Test
- public void shouldReturnSampleDataContentWhenPostWithFileProcessorStream() throws IOException, InterruptedException, URISyntaxException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/post"))
- .headers("Content-Type", "text/plain;charset=UTF-8")
- .POST(HttpRequest.BodyPublishers.ofFile(Paths.get("src/test/resources/sample.txt")))
- .build();
-
- HttpResponse response = HttpClient.newHttpClient()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- assertThat(response.body(), containsString("Sample file content"));
- }
-
-}
+package com.baeldung.java11.httpclient.test;
+
+import static java.time.temporal.ChronoUnit.SECONDS;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertThat;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.file.Paths;
+import java.security.NoSuchAlgorithmException;
+import java.time.Duration;
+
+import org.junit.Test;
+
+public class HttpRequestUnitTest {
+
+ @Test
+ public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/get"))
+ .GET()
+ .build();
+
+ HttpResponse response = HttpClient.newHttpClient()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ }
+
+ @Test
+ public void shouldUseHttp2WhenWebsiteUsesHttp2() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://stackoverflow.com"))
+ .version(HttpClient.Version.HTTP_2)
+ .GET()
+ .build();
+ HttpResponse response = HttpClient.newHttpClient()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ assertThat(response.version(), equalTo(HttpClient.Version.HTTP_2));
+ }
+
+ @Test
+ public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/get"))
+ .version(HttpClient.Version.HTTP_2)
+ .GET()
+ .build();
+
+ HttpResponse response = HttpClient.newHttpClient()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1));
+ }
+
+ @Test
+ public void shouldReturnStatusOKWhenSendGetRequestWithDummyHeaders() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/get"))
+ .headers("key1", "value1", "key2", "value2")
+ .GET()
+ .build();
+
+ HttpResponse response = HttpClient.newHttpClient()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ }
+
+ @Test
+ public void shouldReturnStatusOKWhenSendGetRequestTimeoutSet() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/get"))
+ .timeout(Duration.of(10, SECONDS))
+ .GET()
+ .build();
+
+ HttpResponse response = HttpClient.newHttpClient()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ }
+
+ @Test
+ public void shouldReturnNoContentWhenPostWithNoBody() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/post"))
+ .POST(HttpRequest.BodyPublishers.noBody())
+ .build();
+
+ HttpResponse response = HttpClient.newHttpClient()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ }
+
+ @Test
+ public void shouldReturnSampleDataContentWhenPostWithBodyText() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/post"))
+ .headers("Content-Type", "text/plain;charset=UTF-8")
+ .POST(HttpRequest.BodyPublishers.ofString("Sample request body"))
+ .build();
+
+ HttpResponse response = HttpClient.newHttpClient()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ assertThat(response.body(), containsString("Sample request body"));
+ }
+
+ @Test
+ public void shouldReturnSampleDataContentWhenPostWithInputStream() throws IOException, InterruptedException, URISyntaxException {
+ byte[] sampleData = "Sample request body".getBytes();
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/post"))
+ .headers("Content-Type", "text/plain;charset=UTF-8")
+ .POST(HttpRequest.BodyPublishers.ofInputStream(() -> new ByteArrayInputStream(sampleData)))
+ .build();
+
+ HttpResponse response = HttpClient.newHttpClient()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ assertThat(response.body(), containsString("Sample request body"));
+ }
+
+ @Test
+ public void shouldReturnSampleDataContentWhenPostWithByteArrayProcessorStream() throws IOException, InterruptedException, URISyntaxException {
+ byte[] sampleData = "Sample request body".getBytes();
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/post"))
+ .headers("Content-Type", "text/plain;charset=UTF-8")
+ .POST(HttpRequest.BodyPublishers.ofByteArray(sampleData))
+ .build();
+
+ HttpResponse response = HttpClient.newHttpClient()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ assertThat(response.body(), containsString("Sample request body"));
+ }
+
+ @Test
+ public void shouldReturnSampleDataContentWhenPostWithFileProcessorStream() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/post"))
+ .headers("Content-Type", "text/plain;charset=UTF-8")
+ .POST(HttpRequest.BodyPublishers.ofFile(Paths.get("src/test/resources/sample.txt")))
+ .build();
+
+ HttpResponse response = HttpClient.newHttpClient()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ assertThat(response.body(), containsString("Sample file content"));
+ }
+
+}
diff --git a/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseUnitTest.java
similarity index 95%
rename from core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseTest.java
rename to core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseUnitTest.java
index 78d86fbf4e..a5cfc3f6b1 100644
--- a/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseTest.java
+++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/java11/httpclient/test/HttpResponseUnitTest.java
@@ -1,54 +1,54 @@
-package com.baeldung.java11.httpclient.test;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-import java.io.IOException;
-import java.net.HttpURLConnection;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.http.HttpClient;
-import java.net.http.HttpRequest;
-import java.net.http.HttpResponse;
-
-import org.junit.Test;
-
-public class HttpResponseTest {
-
- @Test
- public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("https://postman-echo.com/get"))
- .version(HttpClient.Version.HTTP_2)
- .GET()
- .build();
-
- HttpResponse response = HttpClient.newBuilder()
- .followRedirects(HttpClient.Redirect.NORMAL)
- .build()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
- assertNotNull(response.body());
- }
-
- @Test
- public void shouldResponseURIDifferentThanRequestUIRWhenRedirect() throws IOException, InterruptedException, URISyntaxException {
- HttpRequest request = HttpRequest.newBuilder()
- .uri(new URI("http://stackoverflow.com"))
- .version(HttpClient.Version.HTTP_2)
- .GET()
- .build();
- HttpResponse response = HttpClient.newBuilder()
- .followRedirects(HttpClient.Redirect.NORMAL)
- .build()
- .send(request, HttpResponse.BodyHandlers.ofString());
-
- assertThat(request.uri()
- .toString(), equalTo("http://stackoverflow.com"));
- assertThat(response.uri()
- .toString(), equalTo("https://stackoverflow.com/"));
- }
-
-}
+package com.baeldung.java11.httpclient.test;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+
+import org.junit.Test;
+
+public class HttpResponseUnitTest {
+
+ @Test
+ public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("https://postman-echo.com/get"))
+ .version(HttpClient.Version.HTTP_2)
+ .GET()
+ .build();
+
+ HttpResponse response = HttpClient.newBuilder()
+ .followRedirects(HttpClient.Redirect.NORMAL)
+ .build()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
+ assertNotNull(response.body());
+ }
+
+ @Test
+ public void shouldResponseURIDifferentThanRequestUIRWhenRedirect() throws IOException, InterruptedException, URISyntaxException {
+ HttpRequest request = HttpRequest.newBuilder()
+ .uri(new URI("http://stackoverflow.com"))
+ .version(HttpClient.Version.HTTP_2)
+ .GET()
+ .build();
+ HttpResponse response = HttpClient.newBuilder()
+ .followRedirects(HttpClient.Redirect.NORMAL)
+ .build()
+ .send(request, HttpResponse.BodyHandlers.ofString());
+
+ assertThat(request.uri()
+ .toString(), equalTo("http://stackoverflow.com"));
+ assertThat(response.uri()
+ .toString(), equalTo("https://stackoverflow.com/"));
+ }
+
+}
diff --git a/core-java-11/src/test/java/com/baeldung/optional/OptionalUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/optional/OptionalUnitTest.java
similarity index 100%
rename from core-java-11/src/test/java/com/baeldung/optional/OptionalUnitTest.java
rename to core-java-modules/core-java-11/src/test/java/com/baeldung/optional/OptionalUnitTest.java
diff --git a/core-java-modules/core-java-11/src/test/java/com/baeldung/predicate/not/PersonUnitTest.java b/core-java-modules/core-java-11/src/test/java/com/baeldung/predicate/not/PersonUnitTest.java
new file mode 100644
index 0000000000..a4989287be
--- /dev/null
+++ b/core-java-modules/core-java-11/src/test/java/com/baeldung/predicate/not/PersonUnitTest.java
@@ -0,0 +1,61 @@
+package com.baeldung.predicate.not;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static java.util.function.Predicate.not;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class PersonUnitTest {
+ private List people;
+
+ @BeforeEach
+ void preparePeople() {
+ people = Arrays.asList(
+ new Person(1),
+ new Person(18),
+ new Person(2)
+ );
+ }
+
+ @Test
+ void givenPeople_whenFilterIsAdult_thenOneResult() {
+ List adults = people.stream()
+ .filter(Person::isAdult)
+ .collect(Collectors.toList());
+
+ assertThat(adults).size().isEqualTo(1);
+ }
+
+ @Test
+ void givenPeople_whenFilterIsAdultNegated_thenTwoResults() {
+ List nonAdults = people.stream()
+ .filter(person -> !person.isAdult())
+ .collect(Collectors.toList());
+
+ assertThat(nonAdults).size().isEqualTo(2);
+ }
+
+ @Test
+ void givenPeople_whenFilterIsNotAdult_thenTwoResults() {
+ List nonAdults = people.stream()
+ .filter(Person::isNotAdult)
+ .collect(Collectors.toList());
+
+ assertThat(nonAdults).size().isEqualTo(2);
+ }
+
+ @Test
+ void givenPeople_whenFilterNotIsAdult_thenTwoResults() {
+ List nonAdults = people.stream()
+ .filter(not(Person::isAdult))
+ .collect(Collectors.toList());
+
+ assertThat(nonAdults).size().isEqualTo(2);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-12/pom.xml b/core-java-modules/core-java-12/pom.xml
new file mode 100644
index 0000000000..06c49a0021
--- /dev/null
+++ b/core-java-modules/core-java-12/pom.xml
@@ -0,0 +1,50 @@
+
+
+ 4.0.0
+ com.baeldung
+ core-java-12
+ 0.1.0-SNAPSHOT
+ core-java-12
+ jar
+ http://maven.apache.org
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+ ../../
+
+
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${maven.compiler.source.version}
+ ${maven.compiler.target.version}
+ --enable-preview
+
+
+
+
+
+
+ 12
+ 12
+ 3.6.1
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java b/core-java-modules/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java
new file mode 100644
index 0000000000..7c4cb9e8f0
--- /dev/null
+++ b/core-java-modules/core-java-12/src/test/java/com/baeldung/collectors/CollectorsUnitTest.java
@@ -0,0 +1,71 @@
+package com.baeldung.collectors;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+import org.junit.Test;
+
+import static java.util.stream.Collectors.maxBy;
+import static java.util.stream.Collectors.minBy;
+import static java.util.stream.Collectors.teeing;
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * Unit tests for collectors additions in Java 12.
+ */
+public class CollectorsUnitTest {
+
+ @Test
+ public void whenTeeing_ItShouldCombineTheResultsAsExpected() {
+ List numbers = Arrays.asList(42, 4, 2, 24);
+ Range range = numbers.stream()
+ .collect(teeing(minBy(Integer::compareTo), maxBy(Integer::compareTo), (min, max) -> new Range(min.orElse(null), max.orElse(null))));
+
+ assertThat(range).isEqualTo(new Range(2, 42));
+ }
+
+ /**
+ * Represents a closed range of numbers between {@link #min} and
+ * {@link #max}, both inclusive.
+ */
+ private static class Range {
+
+ private final Integer min;
+
+ private final Integer max;
+
+ Range(Integer min, Integer max) {
+ this.min = min;
+ this.max = max;
+ }
+
+ Integer getMin() {
+ return min;
+ }
+
+ Integer getMax() {
+ return max;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+ Range range = (Range) o;
+ return Objects.equals(getMin(), range.getMin()) && Objects.equals(getMax(), range.getMax());
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(getMin(), getMax());
+ }
+
+ @Override
+ public String toString() {
+ return "Range{" + "min=" + min + ", max=" + max + '}';
+ }
+ }
+}
diff --git a/core-java-modules/core-java-12/src/test/java/com/baeldung/string/StringAPITest.java b/core-java-modules/core-java-12/src/test/java/com/baeldung/string/StringAPITest.java
new file mode 100644
index 0000000000..3d80a36bf6
--- /dev/null
+++ b/core-java-modules/core-java-12/src/test/java/com/baeldung/string/StringAPITest.java
@@ -0,0 +1,43 @@
+package com.baeldung.string;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import org.junit.Test;
+
+public class StringAPITest {
+
+ @Test
+ public void whenPositiveArgument_thenReturnIndentedString() {
+ String multilineStr = "This is\na multiline\nstring.";
+ String outputStr = " This is\n a multiline\n string.\n";
+
+ String postIndent = multilineStr.indent(3);
+
+ assertThat(postIndent, equalTo(outputStr));
+ }
+
+ @Test
+ public void whenNegativeArgument_thenReturnReducedIndentedString() {
+ String multilineStr = " This is\n a multiline\n string.";
+ String outputStr = " This is\n a multiline\n string.\n";
+
+ String postIndent = multilineStr.indent(-2);
+
+ assertThat(postIndent, equalTo(outputStr));
+ }
+
+ @Test
+ public void whenTransformUsingLamda_thenReturnTransformedString() {
+ String result = "hello".transform(input -> input + " world!");
+
+ assertThat(result, equalTo("hello world!"));
+ }
+
+ @Test
+ public void whenTransformUsingParseInt_thenReturnInt() {
+ int result = "42".transform(Integer::parseInt);
+
+ assertThat(result, equalTo(42));
+ }
+}
diff --git a/core-java-modules/core-java-12/src/test/java/com/baeldung/switchExpression/SwitchUnitTest.java b/core-java-modules/core-java-12/src/test/java/com/baeldung/switchExpression/SwitchUnitTest.java
new file mode 100644
index 0000000000..708e416090
--- /dev/null
+++ b/core-java-modules/core-java-12/src/test/java/com/baeldung/switchExpression/SwitchUnitTest.java
@@ -0,0 +1,37 @@
+package com.baeldung.switchExpression;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class SwitchUnitTest {
+
+ @Test
+ public void switchJava12(){
+
+ var month = Month.AUG;
+
+ var value = switch(month){
+ case JAN,JUN, JUL -> 3;
+ case FEB,SEP, OCT, NOV, DEC -> 1;
+ case MAR,MAY, APR, AUG -> 2;
+ };
+
+ Assert.assertEquals(value, 2);
+ }
+
+ @Test
+ public void switchLocalVariable(){
+ var month = Month.AUG;
+ int i = switch (month){
+ case JAN,JUN, JUL -> 3;
+ case FEB,SEP, OCT, NOV, DEC -> 1;
+ case MAR,MAY, APR, AUG -> {
+ int j = month.toString().length() * 4;
+ break j;
+ }
+ };
+ Assert.assertEquals(12, i);
+ }
+
+ enum Month {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC}
+}
diff --git a/core-java-arrays/.gitignore b/core-java-modules/core-java-8-2/.gitignore
similarity index 100%
rename from core-java-arrays/.gitignore
rename to core-java-modules/core-java-8-2/.gitignore
diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md
new file mode 100644
index 0000000000..d53b731878
--- /dev/null
+++ b/core-java-modules/core-java-8-2/README.md
@@ -0,0 +1,8 @@
+=========
+
+## Core Java 8 Cookbooks and Examples (part 2)
+
+### Relevant Articles:
+- [Anonymous Classes in Java](http://www.baeldung.com/)
+- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
+- [Run JAR Application With Command Line Arguments](https://www.baeldung.com/java-run-jar-with-arguments)
diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml
new file mode 100644
index 0000000000..cc184de529
--- /dev/null
+++ b/core-java-modules/core-java-8-2/pom.xml
@@ -0,0 +1,49 @@
+
+
+ 4.0.0
+ com.baeldung
+ core-java-8-2
+ 0.1.0-SNAPSHOT
+ core-java-8-2
+ jar
+
+
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../../parent-java
+
+
+
+ UTF-8
+ 1.8
+ 1.8
+ 64.2
+
+
+
+
+ com.ibm.icu
+ icu4j
+ ${icu.version}
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${maven.compiler.source}
+ ${maven.compiler.target}
+
+
+
+
+
+
diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/jarArguments/JarExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/jarArguments/JarExample.java
new file mode 100644
index 0000000000..c2fb809790
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/jarArguments/JarExample.java
@@ -0,0 +1,18 @@
+package com.baeldung.jarArguments;
+
+public class JarExample {
+
+ public static void main(String[] args) {
+ System.out.println("Hello Baeldung Reader in JarExample!");
+
+ if(args == null) {
+ System.out.println("You have not provided any arguments!");
+ }else {
+ System.out.println("There are "+args.length+" argument(s)!");
+ for(int i=0; i locales = Arrays.asList(new Locale[] { Locale.UK, Locale.ITALY, Locale.FRANCE, Locale.forLanguageTag("pl-PL") });
+ Localization.run(locales);
+ JavaSEFormat.run(locales);
+ ICUFormat.run(locales);
+ }
+
+}
diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/localization/ICUFormat.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/localization/ICUFormat.java
new file mode 100644
index 0000000000..f7bc357933
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/localization/ICUFormat.java
@@ -0,0 +1,29 @@
+package com.baeldung.localization;
+
+import java.util.List;
+import java.util.Locale;
+import java.util.ResourceBundle;
+
+import com.ibm.icu.text.MessageFormat;
+
+public class ICUFormat {
+
+ public static String getLabel(Locale locale, Object[] data) {
+ ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
+ String format = bundle.getString("label-icu");
+ MessageFormat formatter = new MessageFormat(format, locale);
+ return formatter.format(data);
+ }
+
+ public static void run(List locales) {
+ System.out.println("ICU formatter");
+ locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 0 })));
+ locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 1 })));
+ locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 2 })));
+ locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 3 })));
+ locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 0 })));
+ locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 1 })));
+ locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 2 })));
+ locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 3 })));
+ }
+}
diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/localization/JavaSEFormat.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/localization/JavaSEFormat.java
new file mode 100644
index 0000000000..c95dfffa13
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/localization/JavaSEFormat.java
@@ -0,0 +1,24 @@
+package com.baeldung.localization;
+
+import java.text.MessageFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.Locale;
+import java.util.ResourceBundle;
+
+public class JavaSEFormat {
+
+ public static String getLabel(Locale locale, Object[] data) {
+ ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
+ final String pattern = bundle.getString("label");
+ final MessageFormat formatter = new MessageFormat(pattern, locale);
+ return formatter.format(data);
+ }
+
+ public static void run(List locales) {
+ System.out.println("Java formatter");
+ final Date date = new Date(System.currentTimeMillis());
+ locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 0 })));
+ locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 2 })));
+ }
+}
diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/localization/Localization.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/localization/Localization.java
new file mode 100644
index 0000000000..17a6598ce0
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/localization/Localization.java
@@ -0,0 +1,18 @@
+package com.baeldung.localization;
+
+import java.util.List;
+import java.util.Locale;
+import java.util.ResourceBundle;
+
+public class Localization {
+
+ public static String getLabel(Locale locale) {
+ final ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
+ return bundle.getString("label");
+ }
+
+ public static void run(List locales) {
+ locales.forEach(locale -> System.out.println(getLabel(locale)));
+ }
+
+}
diff --git a/core-java-modules/core-java-8-2/src/main/resources/META-INF/persistence.xml b/core-java-modules/core-java-8-2/src/main/resources/META-INF/persistence.xml
new file mode 100644
index 0000000000..e8cd723ec2
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/resources/META-INF/persistence.xml
@@ -0,0 +1,34 @@
+
+
+
+
+ Persist Optional Return Type Demo
+ org.hibernate.jpa.HibernatePersistenceProvider
+ com.baeldung.optionalReturnType.User
+ com.baeldung.optionalReturnType.UserOptional
+
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-8-2/src/main/resources/example_manifest.txt b/core-java-modules/core-java-8-2/src/main/resources/example_manifest.txt
new file mode 100644
index 0000000000..71abcb05fb
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/resources/example_manifest.txt
@@ -0,0 +1 @@
+Main-Class: com.baeldung.jarArguments.JarExample
diff --git a/core-java-modules/core-java-8-2/src/main/resources/formats_en.properties b/core-java-modules/core-java-8-2/src/main/resources/formats_en.properties
new file mode 100644
index 0000000000..41e0e00119
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/resources/formats_en.properties
@@ -0,0 +1,2 @@
+label=On {0, date, short} {1} has sent you {2, choice, 0#no messages|1#a message|2#two messages|2<{2,number,integer} messages}.
+label-icu={0} has sent you {2, plural, =0 {no messages} =1 {a message} other {{2, number, integer} messages}}.
\ No newline at end of file
diff --git a/core-java-modules/core-java-8-2/src/main/resources/formats_fr.properties b/core-java-modules/core-java-8-2/src/main/resources/formats_fr.properties
new file mode 100644
index 0000000000..c2d5159b32
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/resources/formats_fr.properties
@@ -0,0 +1,2 @@
+label={0, date, short}, {1}{2, choice, 0# ne|0<} vous a envoy {2, choice, 0#aucun message|1#un message|2#deux messages|2<{2,number,integer} messages}.
+label-icu={0} {2, plural, =0 {ne } other {}}vous a envoy {2, plural, =0 {aucun message} =1 {un message} other {{2, number, integer} messages}}.
\ No newline at end of file
diff --git a/core-java-modules/core-java-8-2/src/main/resources/formats_it.properties b/core-java-modules/core-java-8-2/src/main/resources/formats_it.properties
new file mode 100644
index 0000000000..43fd1eee1c
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/resources/formats_it.properties
@@ -0,0 +1,2 @@
+label={0, date, short} {1} ti ha inviato {2, choice, 0#nessun messagio|1#un messaggio|2#due messaggi|2<{2, number, integer} messaggi}.
+label-icu={0} {2, plural, =0 {non } other {}}ti ha inviato {2, plural, =0 {nessun messaggio} =1 {un messaggio} other {{2, number, integer} messaggi}}.
\ No newline at end of file
diff --git a/core-java-modules/core-java-8-2/src/main/resources/formats_pl.properties b/core-java-modules/core-java-8-2/src/main/resources/formats_pl.properties
new file mode 100644
index 0000000000..9333ec3396
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/resources/formats_pl.properties
@@ -0,0 +1,2 @@
+label=W {0, date, short} {1}{2, choice, 0# nie|0<} wys\u0142a\u0142a ci {2, choice, 0#\u017Cadnych wiadomo\u015Bci|1#wiadomo\u015B\u0107|2#dwie wiadomo\u015Bci|2<{2, number, integer} wiadomo\u015Bci}.
+label-icu={0} {2, plural, =0 {nie } other {}}{1, select, male {wys\u0142a\u0142} female {wys\u0142a\u0142a} other {wys\u0142a\u0142o}} ci {2, plural, =0 {\u017Cadnej wiadomo\u015Bci} =1 {wiadomo\u015B\u0107} other {{2, number, integer} wiadomo\u015Bci}}.
diff --git a/core-java-modules/core-java-8-2/src/main/resources/messages_en.properties b/core-java-modules/core-java-8-2/src/main/resources/messages_en.properties
new file mode 100644
index 0000000000..bcbca9483c
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/resources/messages_en.properties
@@ -0,0 +1 @@
+label=Alice has sent you a message.
diff --git a/core-java-modules/core-java-8-2/src/main/resources/messages_fr.properties b/core-java-modules/core-java-8-2/src/main/resources/messages_fr.properties
new file mode 100644
index 0000000000..6716102568
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/resources/messages_fr.properties
@@ -0,0 +1 @@
+label=Alice vous a envoy un message.
\ No newline at end of file
diff --git a/core-java-modules/core-java-8-2/src/main/resources/messages_it.properties b/core-java-modules/core-java-8-2/src/main/resources/messages_it.properties
new file mode 100644
index 0000000000..6929a8c091
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/resources/messages_it.properties
@@ -0,0 +1 @@
+label=Alice ti ha inviato un messaggio.
\ No newline at end of file
diff --git a/core-java-modules/core-java-8-2/src/main/resources/messages_pl.properties b/core-java-modules/core-java-8-2/src/main/resources/messages_pl.properties
new file mode 100644
index 0000000000..5515a9920e
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/resources/messages_pl.properties
@@ -0,0 +1 @@
+label=Alice wys\u0142a\u0142a ci wiadomo\u015B\u0107.
\ No newline at end of file
diff --git a/core-java-modules/core-java-8-2/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java
new file mode 100644
index 0000000000..2c8f9b47f3
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/localization/ICUFormatUnitTest.java
@@ -0,0 +1,74 @@
+package com.baeldung.localization;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Locale;
+
+import org.junit.Test;
+
+import com.baeldung.localization.ICUFormat;
+
+public class ICUFormatUnitTest {
+
+ @Test
+ public void givenInUK_whenAliceSendsNothing_thenCorrectMessage() {
+ assertEquals("Alice has sent you no messages.", ICUFormat.getLabel(Locale.UK, new Object[] { "Alice", "female", 0 }));
+ }
+
+ @Test
+ public void givenInUK_whenAliceSendsOneMessage_thenCorrectMessage() {
+ assertEquals("Alice has sent you a message.", ICUFormat.getLabel(Locale.UK, new Object[] { "Alice", "female", 1 }));
+ }
+
+ @Test
+ public void givenInUK_whenBobSendsSixMessages_thenCorrectMessage() {
+ assertEquals("Bob has sent you 6 messages.", ICUFormat.getLabel(Locale.UK, new Object[] { "Bob", "male", 6 }));
+ }
+
+ @Test
+ public void givenInItaly_whenAliceSendsNothing_thenCorrectMessage() {
+ assertEquals("Alice non ti ha inviato nessun messaggio.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Alice", "female", 0 }));
+ }
+
+ @Test
+ public void givenInItaly_whenAliceSendsOneMessage_thenCorrectMessage() {
+ assertEquals("Alice ti ha inviato un messaggio.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Alice", "female", 1 }));
+ }
+
+ @Test
+ public void givenInItaly_whenBobSendsSixMessages_thenCorrectMessage() {
+ assertEquals("Bob ti ha inviato 6 messaggi.", ICUFormat.getLabel(Locale.ITALY, new Object[] { "Bob", "male", 6 }));
+ }
+
+ @Test
+ public void givenInFrance_whenAliceSendsNothing_thenCorrectMessage() {
+ assertEquals("Alice ne vous a envoyé aucun message.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Alice", "female", 0 }));
+ }
+
+ @Test
+ public void givenInFrance_whenAliceSendsOneMessage_thenCorrectMessage() {
+ assertEquals("Alice vous a envoyé un message.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Alice", "female", 1 }));
+ }
+
+ @Test
+ public void givenInFrance_whenBobSendsSixMessages_thenCorrectMessage() {
+ assertEquals("Bob vous a envoyé 6 messages.", ICUFormat.getLabel(Locale.FRANCE, new Object[] { "Bob", "male", 6 }));
+ }
+
+
+ @Test
+ public void givenInPoland_whenAliceSendsNothing_thenCorrectMessage() {
+ assertEquals("Alice nie wysłała ci żadnej wiadomości.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Alice", "female", 0 }));
+ }
+
+ @Test
+ public void givenInPoland_whenAliceSendsOneMessage_thenCorrectMessage() {
+ assertEquals("Alice wysłała ci wiadomość.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Alice", "female", 1 }));
+ }
+
+ @Test
+ public void givenInPoland_whenBobSendsSixMessages_thenCorrectMessage() {
+ assertEquals("Bob wysłał ci 6 wiadomości.", ICUFormat.getLabel(Locale.forLanguageTag("pl-PL"), new Object[] { "Bob", "male", 6 }));
+ }
+
+}
diff --git a/core-java-8/.gitignore b/core-java-modules/core-java-8/.gitignore
similarity index 100%
rename from core-java-8/.gitignore
rename to core-java-modules/core-java-8/.gitignore
diff --git a/core-java-8/README.md b/core-java-modules/core-java-8/README.md
similarity index 87%
rename from core-java-8/README.md
rename to core-java-modules/core-java-8/README.md
index 892dc71f76..d11d2debce 100644
--- a/core-java-8/README.md
+++ b/core-java-modules/core-java-8/README.md
@@ -3,10 +3,10 @@
## Core Java 8 Cookbooks and Examples
### Relevant Articles:
-- [Java 8 Collectors](http://www.baeldung.com/java-8-collectors)
-- [Guide to Java 8’s Functional Interfaces](http://www.baeldung.com/java-8-functional-interfaces)
+- [Guide to Java 8’s Collectors](http://www.baeldung.com/java-8-collectors)
+- [Functional Interfaces in Java 8](http://www.baeldung.com/java-8-functional-interfaces)
- [Java 8 – Powerful Comparison with Lambdas](http://www.baeldung.com/java-8-sort-lambda)
-- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
+- [New Features in Java 8](http://www.baeldung.com/java-8-new-features)
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
@@ -38,3 +38,5 @@
- [Java @SafeVarargs Annotation](https://www.baeldung.com/java-safevarargs)
- [Java @Deprecated Annotation](https://www.baeldung.com/java-deprecated)
- [Java 8 Predicate Chain](https://www.baeldung.com/java-predicate-chain)
+- [Method References in Java](https://www.baeldung.com/java-method-references)
+- [Creating a Custom Annotation in Java](https://www.baeldung.com/java-custom-annotation)
diff --git a/core-java-8/pom.xml b/core-java-modules/core-java-8/pom.xml
similarity index 96%
rename from core-java-8/pom.xml
rename to core-java-modules/core-java-8/pom.xml
index b63afef7d4..c09c970e07 100644
--- a/core-java-8/pom.xml
+++ b/core-java-modules/core-java-8/pom.xml
@@ -1,199 +1,199 @@
-
- 4.0.0
- com.baeldung
- core-java-8
- 0.1.0-SNAPSHOT
- core-java-8
- jar
-
-
- com.baeldung
- parent-java
- 0.0.1-SNAPSHOT
- ../parent-java
-
-
-
-
- org.apache.commons
- commons-collections4
- ${commons-collections4.version}
-
-
- commons-io
- commons-io
- ${commons-io.version}
-
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
-
-
- org.apache.commons
- commons-math3
- ${commons-math3.version}
-
-
- log4j
- log4j
- ${log4j.version}
-
-
- commons-codec
- commons-codec
- ${commons-codec.version}
-
-
- org.projectlombok
- lombok
- ${lombok.version}
- provided
-
-
-
- org.assertj
- assertj-core
- ${assertj.version}
- test
-
-
- com.jayway.awaitility
- awaitility
- ${avaitility.version}
- test
-
-
- org.openjdk.jmh
- jmh-core
- ${jmh-core.version}
-
-
- org.openjdk.jmh
- jmh-generator-annprocess
- ${jmh-generator.version}
-
-
- org.openjdk.jmh
- jmh-generator-bytecode
- ${jmh-generator.version}
-
-
- com.codepoetics
- protonpack
- ${protonpack.version}
-
-
- io.vavr
- vavr
- ${vavr.version}
-
-
- joda-time
- joda-time
- ${joda.version}
-
-
- org.aspectj
- aspectjrt
- ${asspectj.version}
-
-
- org.aspectj
- aspectjweaver
- ${asspectj.version}
-
-
- org.powermock
- powermock-module-junit4
- ${powermock.version}
- test
-
-
- org.powermock
- powermock-api-mockito2
- ${powermock.version}
- test
-
-
- org.jmockit
- jmockit
- ${jmockit.version}
- test
-
-
-
-
- core-java-8
-
-
- src/main/resources
- true
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- 1.8
- 1.8
- -parameters
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
- ${spring-boot-maven-plugin.version}
-
-
-
- repackage
-
-
- spring-boot
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
- -javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar
-
- true
-
-
-
-
-
-
-
- 3.5
- 3.6.1
- 4.1
- 4.01
- 1.10
- 0.9.0
- 1.13
- 2.10
-
- 3.6.1
- 1.8.9
- 2.0.0-RC.4
- 1.44
- 1.7.0
- 1.19
- 1.19
- 2.0.4.RELEASE
-
- 3.8.0
- 2.22.1
-
-
+
+ 4.0.0
+ com.baeldung
+ core-java-8
+ 0.1.0-SNAPSHOT
+ core-java-8
+ jar
+
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../../parent-java
+
+
+
+
+ org.apache.commons
+ commons-collections4
+ ${commons-collections4.version}
+
+
+ commons-io
+ commons-io
+ ${commons-io.version}
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+ org.apache.commons
+ commons-math3
+ ${commons-math3.version}
+
+
+ log4j
+ log4j
+ ${log4j.version}
+
+
+ commons-codec
+ commons-codec
+ ${commons-codec.version}
+
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+ provided
+
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+ com.jayway.awaitility
+ awaitility
+ ${avaitility.version}
+ test
+
+
+ org.openjdk.jmh
+ jmh-core
+ ${jmh-core.version}
+
+
+ org.openjdk.jmh
+ jmh-generator-annprocess
+ ${jmh-generator.version}
+
+
+ org.openjdk.jmh
+ jmh-generator-bytecode
+ ${jmh-generator.version}
+
+
+ com.codepoetics
+ protonpack
+ ${protonpack.version}
+
+
+ io.vavr
+ vavr
+ ${vavr.version}
+
+
+ joda-time
+ joda-time
+ ${joda.version}
+
+
+ org.aspectj
+ aspectjrt
+ ${asspectj.version}
+
+
+ org.aspectj
+ aspectjweaver
+ ${asspectj.version}
+
+
+ org.powermock
+ powermock-module-junit4
+ ${powermock.version}
+ test
+
+
+ org.powermock
+ powermock-api-mockito2
+ ${powermock.version}
+ test
+
+
+ org.jmockit
+ jmockit
+ ${jmockit.version}
+ test
+
+
+
+
+ core-java-8
+
+
+ src/main/resources
+ true
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ 1.8
+ 1.8
+ -parameters
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
+
+
+
+ repackage
+
+
+ spring-boot
+ org.baeldung.executable.ExecutableMavenJar
+
+
+
+
+
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ -javaagent:${settings.localRepository}/org/jmockit/jmockit/${jmockit.version}/jmockit-${jmockit.version}.jar
+
+ true
+
+
+
+
+
+
+
+ 3.5
+ 3.6.1
+ 4.1
+ 4.01
+ 1.10
+ 0.9.0
+ 1.13
+ 2.10
+
+ 3.6.1
+ 1.8.9
+ 2.0.0-RC.4
+ 1.44
+ 1.7.0
+ 1.19
+ 1.19
+ 2.0.4.RELEASE
+
+ 3.8.0
+ 2.22.1
+
+
diff --git a/core-java-8/src/main/java/com/baeldung/annotations/ClassWithAnnotation.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/ClassWithAnnotation.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/annotations/ClassWithAnnotation.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/ClassWithAnnotation.java
diff --git a/core-java-8/src/main/java/com/baeldung/annotations/ClassWithDeprecatedMethod.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/ClassWithDeprecatedMethod.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/annotations/ClassWithDeprecatedMethod.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/ClassWithDeprecatedMethod.java
diff --git a/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSafeVarargs.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSafeVarargs.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/annotations/ClassWithSafeVarargs.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSafeVarargs.java
diff --git a/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSuppressWarnings.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSuppressWarnings.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/annotations/ClassWithSuppressWarnings.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/ClassWithSuppressWarnings.java
diff --git a/core-java-8/src/main/java/com/baeldung/annotations/IntConsumer.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/IntConsumer.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/annotations/IntConsumer.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/IntConsumer.java
diff --git a/core-java-8/src/main/java/com/baeldung/annotations/Interval.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/Interval.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/annotations/Interval.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/Interval.java
diff --git a/core-java-8/src/main/java/com/baeldung/annotations/IntervalUsage.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/IntervalUsage.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/annotations/IntervalUsage.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/IntervalUsage.java
diff --git a/core-java-8/src/main/java/com/baeldung/annotations/Intervals.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/Intervals.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/annotations/Intervals.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/Intervals.java
diff --git a/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotation.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotation.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/annotations/MyAnnotation.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotation.java
diff --git a/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotationTarget.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotationTarget.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/annotations/MyAnnotationTarget.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/MyAnnotationTarget.java
diff --git a/core-java-8/src/main/java/com/baeldung/annotations/MyOperation.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/MyOperation.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/annotations/MyOperation.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/MyOperation.java
diff --git a/core-java-8/src/main/java/com/baeldung/annotations/MyOperationImpl.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/MyOperationImpl.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/annotations/MyOperationImpl.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/annotations/MyOperationImpl.java
diff --git a/core-java-8/src/main/java/com/baeldung/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj b/core-java-modules/core-java-8/src/main/java/com/baeldung/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj
diff --git a/core-java-8/src/main/java/com/baeldung/customannotations/Init.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/Init.java
similarity index 95%
rename from core-java-8/src/main/java/com/baeldung/customannotations/Init.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/Init.java
index 265e7ba1d6..c27d7d7980 100644
--- a/core-java-8/src/main/java/com/baeldung/customannotations/Init.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/Init.java
@@ -1,13 +1,13 @@
-package com.baeldung.customannotations;
-
-import static java.lang.annotation.ElementType.METHOD;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-@Retention(RUNTIME)
-@Target(METHOD)
-public @interface Init {
-
-}
+package com.baeldung.customannotations;
+
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+@Retention(RUNTIME)
+@Target(METHOD)
+public @interface Init {
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/customannotations/JsonElement.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/JsonElement.java
similarity index 96%
rename from core-java-8/src/main/java/com/baeldung/customannotations/JsonElement.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/JsonElement.java
index e41a5b1e30..3c953f9081 100644
--- a/core-java-8/src/main/java/com/baeldung/customannotations/JsonElement.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/JsonElement.java
@@ -1,13 +1,13 @@
-package com.baeldung.customannotations;
-
-import static java.lang.annotation.ElementType.FIELD;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-@Retention(RUNTIME)
-@Target({ FIELD })
-public @interface JsonElement {
- public String key() default "";
-}
+package com.baeldung.customannotations;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+@Retention(RUNTIME)
+@Target({ FIELD })
+public @interface JsonElement {
+ public String key() default "";
+}
diff --git a/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializable.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializable.java
similarity index 95%
rename from core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializable.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializable.java
index 48eeb09a1b..f6feba1b7b 100644
--- a/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializable.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializable.java
@@ -1,13 +1,13 @@
-package com.baeldung.customannotations;
-
-import static java.lang.annotation.ElementType.TYPE;
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-@Retention(RUNTIME)
-@Target(TYPE)
-public @interface JsonSerializable {
-
-}
+package com.baeldung.customannotations;
+
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+@Retention(RUNTIME)
+@Target(TYPE)
+public @interface JsonSerializable {
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializationException.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializationException.java
similarity index 96%
rename from core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializationException.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializationException.java
index f2c29855ac..544d1311aa 100644
--- a/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializationException.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/JsonSerializationException.java
@@ -1,10 +1,10 @@
-package com.baeldung.customannotations;
-
-public class JsonSerializationException extends RuntimeException {
-
- private static final long serialVersionUID = 1L;
-
- public JsonSerializationException(String message) {
- super(message);
- }
-}
+package com.baeldung.customannotations;
+
+public class JsonSerializationException extends RuntimeException {
+
+ private static final long serialVersionUID = 1L;
+
+ public JsonSerializationException(String message) {
+ super(message);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/customannotations/ObjectToJsonConverter.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/ObjectToJsonConverter.java
similarity index 97%
rename from core-java-8/src/main/java/com/baeldung/customannotations/ObjectToJsonConverter.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/ObjectToJsonConverter.java
index dd126be8ed..b809ea0d1d 100644
--- a/core-java-8/src/main/java/com/baeldung/customannotations/ObjectToJsonConverter.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/ObjectToJsonConverter.java
@@ -1,67 +1,67 @@
-package com.baeldung.customannotations;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-import java.util.stream.Collectors;
-
-public class ObjectToJsonConverter {
- public String convertToJson(Object object) throws JsonSerializationException {
- try {
-
- checkIfSerializable(object);
- initializeObject(object);
- return getJsonString(object);
-
- } catch (Exception e) {
- throw new JsonSerializationException(e.getMessage());
- }
- }
-
- private void checkIfSerializable(Object object) {
- if (Objects.isNull(object)) {
- throw new JsonSerializationException("Can't serialize a null object");
- }
-
- Class> clazz = object.getClass();
- if (!clazz.isAnnotationPresent(JsonSerializable.class)) {
- throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable");
- }
- }
-
- private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
- Class> clazz = object.getClass();
- for (Method method : clazz.getDeclaredMethods()) {
- if (method.isAnnotationPresent(Init.class)) {
- method.setAccessible(true);
- method.invoke(object);
- }
- }
- }
-
- private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException {
- Class> clazz = object.getClass();
- Map jsonElementsMap = new HashMap<>();
- for (Field field : clazz.getDeclaredFields()) {
- field.setAccessible(true);
- if (field.isAnnotationPresent(JsonElement.class)) {
- jsonElementsMap.put(getKey(field), (String) field.get(object));
- }
- }
-
- String jsonString = jsonElementsMap.entrySet()
- .stream()
- .map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"")
- .collect(Collectors.joining(","));
- return "{" + jsonString + "}";
- }
-
- private String getKey(Field field) {
- String value = field.getAnnotation(JsonElement.class)
- .key();
- return value.isEmpty() ? field.getName() : value;
- }
-}
+package com.baeldung.customannotations;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class ObjectToJsonConverter {
+ public String convertToJson(Object object) throws JsonSerializationException {
+ try {
+
+ checkIfSerializable(object);
+ initializeObject(object);
+ return getJsonString(object);
+
+ } catch (Exception e) {
+ throw new JsonSerializationException(e.getMessage());
+ }
+ }
+
+ private void checkIfSerializable(Object object) {
+ if (Objects.isNull(object)) {
+ throw new JsonSerializationException("Can't serialize a null object");
+ }
+
+ Class> clazz = object.getClass();
+ if (!clazz.isAnnotationPresent(JsonSerializable.class)) {
+ throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable");
+ }
+ }
+
+ private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
+ Class> clazz = object.getClass();
+ for (Method method : clazz.getDeclaredMethods()) {
+ if (method.isAnnotationPresent(Init.class)) {
+ method.setAccessible(true);
+ method.invoke(object);
+ }
+ }
+ }
+
+ private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException {
+ Class> clazz = object.getClass();
+ Map jsonElementsMap = new HashMap<>();
+ for (Field field : clazz.getDeclaredFields()) {
+ field.setAccessible(true);
+ if (field.isAnnotationPresent(JsonElement.class)) {
+ jsonElementsMap.put(getKey(field), (String) field.get(object));
+ }
+ }
+
+ String jsonString = jsonElementsMap.entrySet()
+ .stream()
+ .map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"")
+ .collect(Collectors.joining(","));
+ return "{" + jsonString + "}";
+ }
+
+ private String getKey(Field field) {
+ String value = field.getAnnotation(JsonElement.class)
+ .key();
+ return value.isEmpty() ? field.getName() : value;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/customannotations/Person.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/Person.java
similarity index 95%
rename from core-java-8/src/main/java/com/baeldung/customannotations/Person.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/Person.java
index 5db1a7f279..ba702d6d76 100644
--- a/core-java-8/src/main/java/com/baeldung/customannotations/Person.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/customannotations/Person.java
@@ -1,66 +1,66 @@
-package com.baeldung.customannotations;
-
-@JsonSerializable
-public class Person {
- @JsonElement
- private String firstName;
- @JsonElement
- private String lastName;
- @JsonElement(key = "personAge")
- private String age;
-
- private String address;
-
- public Person(String firstName, String lastName) {
- super();
- this.firstName = firstName;
- this.lastName = lastName;
- }
-
- public Person(String firstName, String lastName, String age) {
- this.firstName = firstName;
- this.lastName = lastName;
- this.age = age;
- }
-
- @Init
- private void initNames() {
- this.firstName = this.firstName.substring(0, 1)
- .toUpperCase() + this.firstName.substring(1);
- this.lastName = this.lastName.substring(0, 1)
- .toUpperCase() + this.lastName.substring(1);
- }
-
- public String getFirstName() {
- return firstName;
- }
-
- public void setFirstName(String firstName) {
- this.firstName = firstName;
- }
-
- public String getLastName() {
- return lastName;
- }
-
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
-
- public String getAge() {
- return age;
- }
-
- public void setAge(String age) {
- this.age = age;
- }
-
- public String getAddress() {
- return address;
- }
-
- public void setAddress(String address) {
- this.address = address;
- }
-
-}
+package com.baeldung.customannotations;
+
+@JsonSerializable
+public class Person {
+ @JsonElement
+ private String firstName;
+ @JsonElement
+ private String lastName;
+ @JsonElement(key = "personAge")
+ private String age;
+
+ private String address;
+
+ public Person(String firstName, String lastName) {
+ super();
+ this.firstName = firstName;
+ this.lastName = lastName;
+ }
+
+ public Person(String firstName, String lastName, String age) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.age = age;
+ }
+
+ @Init
+ private void initNames() {
+ this.firstName = this.firstName.substring(0, 1)
+ .toUpperCase() + this.firstName.substring(1);
+ this.lastName = this.lastName.substring(0, 1)
+ .toUpperCase() + this.lastName.substring(1);
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public String getAge() {
+ return age;
+ }
+
+ public void setAge(String age) {
+ this.age = age;
+ }
+
+ public String getAddress() {
+ return address;
+ }
+
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/application/Application.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/application/Application.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/application/Application.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/application/Application.java
diff --git a/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Alarm.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Alarm.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Alarm.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Alarm.java
diff --git a/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Car.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Car.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Car.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Car.java
diff --git a/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Motorbike.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Motorbike.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Motorbike.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Motorbike.java
diff --git a/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/MultiAlarmCar.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/MultiAlarmCar.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/MultiAlarmCar.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/MultiAlarmCar.java
diff --git a/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Vehicle.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Vehicle.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Vehicle.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/defaultstaticinterfacemethods/model/Vehicle.java
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/Computer.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/doublecolon/Computer.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/doublecolon/Computer.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/doublecolon/Computer.java
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/doublecolon/ComputerUtils.java
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/doublecolon/MacbookPro.java
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/doublecolon/function/ComputerPredicate.java
diff --git a/core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/doublecolon/function/TriFunction.java
diff --git a/core-java-8/src/main/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappers.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappers.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappers.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappers.java
diff --git a/core-java-8/src/main/java/com/baeldung/java8/lambda/exceptions/ThrowingConsumer.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/exceptions/ThrowingConsumer.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java8/lambda/exceptions/ThrowingConsumer.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/exceptions/ThrowingConsumer.java
diff --git a/core-java-8/src/main/java/com/baeldung/Bar.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/Bar.java
similarity index 80%
rename from core-java-8/src/main/java/com/baeldung/Bar.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/Bar.java
index 6219bddf74..4cf0aa2399 100644
--- a/core-java-8/src/main/java/com/baeldung/Bar.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/Bar.java
@@ -1,4 +1,4 @@
-package com.baeldung;
+package com.baeldung.java8.lambda.tips;
@FunctionalInterface
diff --git a/core-java-8/src/main/java/com/baeldung/Baz.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/Baz.java
similarity index 80%
rename from core-java-8/src/main/java/com/baeldung/Baz.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/Baz.java
index 23180551ac..c7efe14c89 100644
--- a/core-java-8/src/main/java/com/baeldung/Baz.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/Baz.java
@@ -1,4 +1,4 @@
-package com.baeldung;
+package com.baeldung.java8.lambda.tips;
@FunctionalInterface
diff --git a/core-java-8/src/main/java/com/baeldung/Foo.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/Foo.java
similarity index 75%
rename from core-java-8/src/main/java/com/baeldung/Foo.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/Foo.java
index c8223727a1..b63ba61e7e 100644
--- a/core-java-8/src/main/java/com/baeldung/Foo.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/Foo.java
@@ -1,4 +1,4 @@
-package com.baeldung;
+package com.baeldung.java8.lambda.tips;
@FunctionalInterface
diff --git a/core-java-8/src/main/java/com/baeldung/FooExtended.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/FooExtended.java
similarity index 81%
rename from core-java-8/src/main/java/com/baeldung/FooExtended.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/FooExtended.java
index 8c9b21e397..9141cd8eb8 100644
--- a/core-java-8/src/main/java/com/baeldung/FooExtended.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/FooExtended.java
@@ -1,4 +1,4 @@
-package com.baeldung;
+package com.baeldung.java8.lambda.tips;
@FunctionalInterface
diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/Processor.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/Processor.java
new file mode 100644
index 0000000000..7931129cf5
--- /dev/null
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/Processor.java
@@ -0,0 +1,12 @@
+package com.baeldung.java8.lambda.tips;
+
+import java.util.concurrent.Callable;
+import java.util.function.Supplier;
+
+public interface Processor {
+
+ String processWithCallable(Callable c) throws Exception;
+
+ String processWithSupplier(Supplier s);
+
+}
diff --git a/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/ProcessorImpl.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/ProcessorImpl.java
new file mode 100644
index 0000000000..cb1b3dcdd2
--- /dev/null
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/ProcessorImpl.java
@@ -0,0 +1,20 @@
+package com.baeldung.java8.lambda.tips;
+
+
+import java.util.concurrent.Callable;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Supplier;
+
+public class ProcessorImpl implements Processor {
+
+ @Override
+ public String processWithCallable(Callable c) throws Exception {
+ return c.call();
+ }
+
+ @Override
+ public String processWithSupplier(Supplier s) {
+ return s.get();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/UseFoo.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/UseFoo.java
similarity index 95%
rename from core-java-8/src/main/java/com/baeldung/UseFoo.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/UseFoo.java
index 950d02062d..a64d8bb920 100644
--- a/core-java-8/src/main/java/com/baeldung/UseFoo.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/java8/lambda/tips/UseFoo.java
@@ -1,4 +1,4 @@
-package com.baeldung;
+package com.baeldung.java8.lambda.tips;
import java.util.function.Function;
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/Address.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/Address.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/CustomException.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalAddress.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/OptionalUser.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/User.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/User.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/User.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/User.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/Vehicle.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/VehicleImpl.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/BlogPost.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/java_8_features/groupingby/BlogPostType.java
diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java
diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java
diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java
diff --git a/core-java-8/src/main/java/com/baeldung/optional/Modem.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/optional/Modem.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/optional/Modem.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/optional/Modem.java
diff --git a/core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGet.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGet.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGet.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGet.java
diff --git a/core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGetBenchmarkRunner.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGetBenchmarkRunner.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGetBenchmarkRunner.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/optional/OrElseAndOrElseGetBenchmarkRunner.java
diff --git a/core-java-8/src/main/java/com/baeldung/optional/Person.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/optional/Person.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/optional/Person.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/optional/Person.java
diff --git a/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/Lookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddCommand.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddCommand.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/AddCommand.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddCommand.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddRule.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddRule.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/AddRule.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/AddRule.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Addition.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Addition.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/Addition.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Addition.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Calculator.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Calculator.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/Calculator.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Calculator.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Command.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Command.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/Command.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Command.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Division.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Division.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/Division.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Division.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Expression.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Expression.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/Expression.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Expression.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Modulo.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Modulo.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/Modulo.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Modulo.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Multiplication.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Multiplication.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/Multiplication.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Multiplication.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Operation.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Operation.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/Operation.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Operation.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Operator.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Operator.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/Operator.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Operator.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/OperatorFactory.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/OperatorFactory.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/OperatorFactory.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/OperatorFactory.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Result.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Result.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/Result.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Result.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Rule.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Rule.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/Rule.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Rule.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/RuleEngine.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/RuleEngine.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/RuleEngine.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/RuleEngine.java
diff --git a/core-java-8/src/main/java/com/baeldung/reducingIfElse/Subtraction.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Subtraction.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/reducingIfElse/Subtraction.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reducingIfElse/Subtraction.java
diff --git a/core-java-8/src/main/java/com/baeldung/reflect/Person.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/reflect/Person.java
similarity index 93%
rename from core-java-8/src/main/java/com/baeldung/reflect/Person.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/reflect/Person.java
index fba25aca8b..f15250869d 100644
--- a/core-java-8/src/main/java/com/baeldung/reflect/Person.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/reflect/Person.java
@@ -1,18 +1,18 @@
-package com.baeldung.reflect;
-
-public class Person {
-
- private String fullName;
-
- public Person(String fullName) {
- this.fullName = fullName;
- }
-
- public void setFullName(String fullName) {
- this.fullName = fullName;
- }
-
- public String getFullName() {
- return fullName;
- }
-}
+package com.baeldung.reflect;
+
+public class Person {
+
+ private String fullName;
+
+ public Person(String fullName) {
+ this.fullName = fullName;
+ }
+
+ public void setFullName(String fullName) {
+ this.fullName = fullName;
+ }
+
+ public String getFullName() {
+ return fullName;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Article.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Article.java
similarity index 94%
rename from core-java-8/src/main/java/com/baeldung/spliteratorAPI/Article.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Article.java
index 402ec6ec5f..3cd2a00da1 100644
--- a/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Article.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Article.java
@@ -1,44 +1,44 @@
-package com.baeldung.spliteratorAPI;
-
-import java.util.List;
-
-public class Article {
- private List listOfAuthors;
- private int id;
- private String name;
-
- public Article(String name) {
- this.name = name;
- }
-
- public Article(List listOfAuthors, int id) {
- super();
- this.listOfAuthors = listOfAuthors;
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public List getListOfAuthors() {
- return listOfAuthors;
- }
-
- public void setListOfAuthors(List listOfAuthors) {
- this.listOfAuthors = listOfAuthors;
- }
-
+package com.baeldung.spliteratorAPI;
+
+import java.util.List;
+
+public class Article {
+ private List listOfAuthors;
+ private int id;
+ private String name;
+
+ public Article(String name) {
+ this.name = name;
+ }
+
+ public Article(List listOfAuthors, int id) {
+ super();
+ this.listOfAuthors = listOfAuthors;
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public List getListOfAuthors() {
+ return listOfAuthors;
+ }
+
+ public void setListOfAuthors(List listOfAuthors) {
+ this.listOfAuthors = listOfAuthors;
+ }
+
}
\ No newline at end of file
diff --git a/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Author.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Author.java
similarity index 95%
rename from core-java-8/src/main/java/com/baeldung/spliteratorAPI/Author.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Author.java
index 40c381f4a6..18bbbd073e 100644
--- a/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Author.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Author.java
@@ -1,33 +1,33 @@
-package com.baeldung.spliteratorAPI;
-
-public class Author {
- private String name;
- private int relatedArticleId;
-
- public Author(String name, int relatedArticleId) {
- this.name = name;
- this.relatedArticleId = relatedArticleId;
- }
-
- public int getRelatedArticleId() {
- return relatedArticleId;
- }
-
- public void setRelatedArticleId(int relatedArticleId) {
- this.relatedArticleId = relatedArticleId;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return "[name: " + name + ", relatedId: " + relatedArticleId + "]";
- }
-}
-
+package com.baeldung.spliteratorAPI;
+
+public class Author {
+ private String name;
+ private int relatedArticleId;
+
+ public Author(String name, int relatedArticleId) {
+ this.name = name;
+ this.relatedArticleId = relatedArticleId;
+ }
+
+ public int getRelatedArticleId() {
+ return relatedArticleId;
+ }
+
+ public void setRelatedArticleId(int relatedArticleId) {
+ this.relatedArticleId = relatedArticleId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return "[name: " + name + ", relatedId: " + relatedArticleId + "]";
+ }
+}
+
diff --git a/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Executor.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Executor.java
similarity index 96%
rename from core-java-8/src/main/java/com/baeldung/spliteratorAPI/Executor.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Executor.java
index 024d5dabdb..dd124948d8 100644
--- a/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Executor.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Executor.java
@@ -1,19 +1,19 @@
-package com.baeldung.spliteratorAPI;
-
-import java.util.List;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-public class Executor {
-
- public static int countAutors(Stream stream) {
- RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true),
- RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine);
- return wordCounter.getCounter();
- }
-
- public static List generateElements() {
- return Stream.generate(() -> new Article("Java")).limit(35000).collect(Collectors.toList());
- }
-
+package com.baeldung.spliteratorAPI;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class Executor {
+
+ public static int countAutors(Stream stream) {
+ RelatedAuthorCounter wordCounter = stream.reduce(new RelatedAuthorCounter(0, true),
+ RelatedAuthorCounter::accumulate, RelatedAuthorCounter::combine);
+ return wordCounter.getCounter();
+ }
+
+ public static List generateElements() {
+ return Stream.generate(() -> new Article("Java")).limit(35000).collect(Collectors.toList());
+ }
+
}
\ No newline at end of file
diff --git a/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorCounter.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorCounter.java
similarity index 96%
rename from core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorCounter.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorCounter.java
index b7120b3af2..282c0be727 100644
--- a/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorCounter.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorCounter.java
@@ -1,27 +1,27 @@
-package com.baeldung.spliteratorAPI;
-
-public class RelatedAuthorCounter {
- private final int counter;
- private final boolean isRelated;
-
- public RelatedAuthorCounter(int counter, boolean isRelated) {
- this.counter = counter;
- this.isRelated = isRelated;
- }
-
- public RelatedAuthorCounter accumulate(Author author) {
- if (author.getRelatedArticleId() == 0) {
- return isRelated ? this : new RelatedAuthorCounter(counter, true);
- } else {
- return isRelated ? new RelatedAuthorCounter(counter + 1, false) : this;
- }
- }
-
- public RelatedAuthorCounter combine(RelatedAuthorCounter RelatedAuthorCounter) {
- return new RelatedAuthorCounter(counter + RelatedAuthorCounter.counter, RelatedAuthorCounter.isRelated);
- }
-
- public int getCounter() {
- return counter;
- }
-}
+package com.baeldung.spliteratorAPI;
+
+public class RelatedAuthorCounter {
+ private final int counter;
+ private final boolean isRelated;
+
+ public RelatedAuthorCounter(int counter, boolean isRelated) {
+ this.counter = counter;
+ this.isRelated = isRelated;
+ }
+
+ public RelatedAuthorCounter accumulate(Author author) {
+ if (author.getRelatedArticleId() == 0) {
+ return isRelated ? this : new RelatedAuthorCounter(counter, true);
+ } else {
+ return isRelated ? new RelatedAuthorCounter(counter + 1, false) : this;
+ }
+ }
+
+ public RelatedAuthorCounter combine(RelatedAuthorCounter RelatedAuthorCounter) {
+ return new RelatedAuthorCounter(counter + RelatedAuthorCounter.counter, RelatedAuthorCounter.isRelated);
+ }
+
+ public int getCounter() {
+ return counter;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorSpliterator.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorSpliterator.java
similarity index 96%
rename from core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorSpliterator.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorSpliterator.java
index 0a7190964e..094638da37 100644
--- a/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorSpliterator.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/RelatedAuthorSpliterator.java
@@ -1,49 +1,49 @@
-package com.baeldung.spliteratorAPI;
-
-import java.util.List;
-import java.util.Spliterator;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.function.Consumer;
-
-public class RelatedAuthorSpliterator implements Spliterator {
- private final List list;
- AtomicInteger current = new AtomicInteger();
-
- public RelatedAuthorSpliterator(List list) {
- this.list = list;
- }
-
- @Override
- public boolean tryAdvance(Consumer super Author> action) {
-
- action.accept(list.get(current.getAndIncrement()));
- return current.get() < list.size();
- }
-
- @Override
- public Spliterator trySplit() {
- int currentSize = list.size() - current.get();
- if (currentSize < 10) {
- return null;
- }
- for (int splitPos = currentSize / 2 + current.intValue(); splitPos < list.size(); splitPos++) {
- if (list.get(splitPos).getRelatedArticleId() == 0) {
- Spliterator spliterator = new RelatedAuthorSpliterator(list.subList(current.get(), splitPos));
- current.set(splitPos);
- return spliterator;
- }
- }
- return null;
- }
-
- @Override
- public long estimateSize() {
- return list.size() - current.get();
- }
-
- @Override
- public int characteristics() {
- return CONCURRENT;
- }
-
-}
+package com.baeldung.spliteratorAPI;
+
+import java.util.List;
+import java.util.Spliterator;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Consumer;
+
+public class RelatedAuthorSpliterator implements Spliterator {
+ private final List list;
+ AtomicInteger current = new AtomicInteger();
+
+ public RelatedAuthorSpliterator(List list) {
+ this.list = list;
+ }
+
+ @Override
+ public boolean tryAdvance(Consumer super Author> action) {
+
+ action.accept(list.get(current.getAndIncrement()));
+ return current.get() < list.size();
+ }
+
+ @Override
+ public Spliterator trySplit() {
+ int currentSize = list.size() - current.get();
+ if (currentSize < 10) {
+ return null;
+ }
+ for (int splitPos = currentSize / 2 + current.intValue(); splitPos < list.size(); splitPos++) {
+ if (list.get(splitPos).getRelatedArticleId() == 0) {
+ Spliterator spliterator = new RelatedAuthorSpliterator(list.subList(current.get(), splitPos));
+ current.set(splitPos);
+ return spliterator;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public long estimateSize() {
+ return list.size() - current.get();
+ }
+
+ @Override
+ public int characteristics() {
+ return CONCURRENT;
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Task.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Task.java
similarity index 96%
rename from core-java-8/src/main/java/com/baeldung/spliteratorAPI/Task.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Task.java
index 70435d1c75..06a124cc98 100644
--- a/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Task.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/spliteratorAPI/Task.java
@@ -1,27 +1,27 @@
-package com.baeldung.spliteratorAPI;
-
-import java.util.Spliterator;
-import java.util.concurrent.Callable;
-
-public class Task implements Callable {
- private Spliterator spliterator;
- private final static String SUFFIX = "- published by Baeldung";
-
- public Task(Spliterator spliterator) {
- this.spliterator = spliterator;
- }
-
- @Override
- public String call() {
- int current = 0;
- while (spliterator.tryAdvance(article -> {
- article.setName(article.getName()
- .concat(SUFFIX));
- })) {
- current++;
- }
- ;
- return Thread.currentThread()
- .getName() + ":" + current;
- }
-}
+package com.baeldung.spliteratorAPI;
+
+import java.util.Spliterator;
+import java.util.concurrent.Callable;
+
+public class Task implements Callable {
+ private Spliterator spliterator;
+ private final static String SUFFIX = "- published by Baeldung";
+
+ public Task(Spliterator spliterator) {
+ this.spliterator = spliterator;
+ }
+
+ @Override
+ public String call() {
+ int current = 0;
+ while (spliterator.tryAdvance(article -> {
+ article.setName(article.getName()
+ .concat(SUFFIX));
+ })) {
+ current++;
+ }
+ ;
+ return Thread.currentThread()
+ .getName() + ":" + current;
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/strategy/ChristmasDiscounter.java
diff --git a/core-java-8/src/main/java/com/baeldung/strategy/Discounter.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/strategy/Discounter.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/strategy/Discounter.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/strategy/Discounter.java
diff --git a/core-java-8/src/main/java/com/baeldung/strategy/EasterDiscounter.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/strategy/EasterDiscounter.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/strategy/EasterDiscounter.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/strategy/EasterDiscounter.java
diff --git a/core-java-8/src/main/java/com/baeldung/streamreduce/application/Application.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/application/Application.java
similarity index 97%
rename from core-java-8/src/main/java/com/baeldung/streamreduce/application/Application.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/application/Application.java
index 0b1dd952dc..00fc45ccae 100644
--- a/core-java-8/src/main/java/com/baeldung/streamreduce/application/Application.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/application/Application.java
@@ -1,62 +1,62 @@
-package com.baeldung.streamreduce.application;
-
-import com.baeldung.streamreduce.entities.User;
-import com.baeldung.streamreduce.utilities.NumberUtils;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-public class Application {
-
- public static void main(String[] args) {
- List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
- int result1 = numbers.stream().reduce(0, (a, b) -> a + b);
- System.out.println(result1);
-
- int result2 = numbers.stream().reduce(0, Integer::sum);
- System.out.println(result2);
-
- List letters = Arrays.asList("a", "b", "c", "d", "e");
- String result3 = letters.stream().reduce("", (a, b) -> a + b);
- System.out.println(result3);
-
- String result4 = letters.stream().reduce("", String::concat);
- System.out.println(result4);
-
- String result5 = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase());
- System.out.println(result5);
-
- List users = Arrays.asList(new User("John", 30), new User("Julie", 35));
- int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
- System.out.println(result6);
-
- String result7 = letters.parallelStream().reduce("", String::concat);
- System.out.println(result7);
-
- int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
- System.out.println(result8);
-
- List userList = new ArrayList<>();
- for (int i = 0; i <= 1000000; i++) {
- userList.add(new User("John" + i, i));
- }
-
- long t1 = System.currentTimeMillis();
- int result9 = userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
- long t2 = System.currentTimeMillis();
- System.out.println(result9);
- System.out.println("Sequential stream time: " + (t2 - t1) + "ms");
-
- long t3 = System.currentTimeMillis();
- int result10 = userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
- long t4 = System.currentTimeMillis();
- System.out.println(result10);
- System.out.println("Parallel stream time: " + (t4 - t3) + "ms");
-
- int result11 = NumberUtils.divideListElements(numbers, 1);
- System.out.println(result11);
-
- int result12 = NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 0);
- System.out.println(result12);
- }
-}
+package com.baeldung.streamreduce.application;
+
+import com.baeldung.streamreduce.entities.User;
+import com.baeldung.streamreduce.utilities.NumberUtils;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class Application {
+
+ public static void main(String[] args) {
+ List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
+ int result1 = numbers.stream().reduce(0, (a, b) -> a + b);
+ System.out.println(result1);
+
+ int result2 = numbers.stream().reduce(0, Integer::sum);
+ System.out.println(result2);
+
+ List letters = Arrays.asList("a", "b", "c", "d", "e");
+ String result3 = letters.stream().reduce("", (a, b) -> a + b);
+ System.out.println(result3);
+
+ String result4 = letters.stream().reduce("", String::concat);
+ System.out.println(result4);
+
+ String result5 = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase());
+ System.out.println(result5);
+
+ List users = Arrays.asList(new User("John", 30), new User("Julie", 35));
+ int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
+ System.out.println(result6);
+
+ String result7 = letters.parallelStream().reduce("", String::concat);
+ System.out.println(result7);
+
+ int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
+ System.out.println(result8);
+
+ List userList = new ArrayList<>();
+ for (int i = 0; i <= 1000000; i++) {
+ userList.add(new User("John" + i, i));
+ }
+
+ long t1 = System.currentTimeMillis();
+ int result9 = userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
+ long t2 = System.currentTimeMillis();
+ System.out.println(result9);
+ System.out.println("Sequential stream time: " + (t2 - t1) + "ms");
+
+ long t3 = System.currentTimeMillis();
+ int result10 = userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
+ long t4 = System.currentTimeMillis();
+ System.out.println(result10);
+ System.out.println("Parallel stream time: " + (t4 - t3) + "ms");
+
+ int result11 = NumberUtils.divideListElements(numbers, 1);
+ System.out.println(result11);
+
+ int result12 = NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 0);
+ System.out.println(result12);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/streamreduce/entities/User.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/User.java
similarity index 94%
rename from core-java-8/src/main/java/com/baeldung/streamreduce/entities/User.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/User.java
index bc13a8cde6..39a42beab7 100644
--- a/core-java-8/src/main/java/com/baeldung/streamreduce/entities/User.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/entities/User.java
@@ -1,25 +1,25 @@
-package com.baeldung.streamreduce.entities;
-
-public class User {
-
- private final String name;
- private final int age;
-
- public User(String name, int age) {
- this.name = name;
- this.age = age;
- }
-
- public String getName() {
- return name;
- }
-
- public int getAge() {
- return age;
- }
-
- @Override
- public String toString() {
- return "User{" + "name=" + name + ", age=" + age + '}';
- }
-}
+package com.baeldung.streamreduce.entities;
+
+public class User {
+
+ private final String name;
+ private final int age;
+
+ public User(String name, int age) {
+ this.name = name;
+ this.age = age;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getAge() {
+ return age;
+ }
+
+ @Override
+ public String toString() {
+ return "User{" + "name=" + name + ", age=" + age + '}';
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/streamreduce/utilities/NumberUtils.java b/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/utilities/NumberUtils.java
similarity index 97%
rename from core-java-8/src/main/java/com/baeldung/streamreduce/utilities/NumberUtils.java
rename to core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/utilities/NumberUtils.java
index 7a6a85e6c4..a2325cc701 100644
--- a/core-java-8/src/main/java/com/baeldung/streamreduce/utilities/NumberUtils.java
+++ b/core-java-modules/core-java-8/src/main/java/com/baeldung/streamreduce/utilities/NumberUtils.java
@@ -1,52 +1,52 @@
-package com.baeldung.streamreduce.utilities;
-
-import java.util.List;
-import java.util.function.BiFunction;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-public abstract class NumberUtils {
-
- private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName());
-
- public static int divideListElements(List values, Integer divider) {
- return values.stream()
- .reduce(0, (a, b) -> {
- try {
- return a / divider + b / divider;
- } catch (ArithmeticException e) {
- LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
- }
- return 0;
- });
- }
-
- public static int divideListElementsWithExtractedTryCatchBlock(List values, int divider) {
- return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider));
- }
-
- public static int divideListElementsWithApplyFunctionMethod(List values, int divider) {
- BiFunction division = (a, b) -> a / b;
- return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider));
- }
-
- private static int divide(int value, int factor) {
- int result = 0;
- try {
- result = value / factor;
- } catch (ArithmeticException e) {
- LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
- }
- return result;
- }
-
- private static int applyFunction(BiFunction function, int a, int b) {
- try {
- return function.apply(a, b);
- }
- catch(Exception e) {
- LOGGER.log(Level.INFO, "Exception occurred!");
- }
- return 0;
- }
-}
+package com.baeldung.streamreduce.utilities;
+
+import java.util.List;
+import java.util.function.BiFunction;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public abstract class NumberUtils {
+
+ private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName());
+
+ public static int divideListElements(List values, Integer divider) {
+ return values.stream()
+ .reduce(0, (a, b) -> {
+ try {
+ return a / divider + b / divider;
+ } catch (ArithmeticException e) {
+ LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
+ }
+ return 0;
+ });
+ }
+
+ public static int divideListElementsWithExtractedTryCatchBlock(List values, int divider) {
+ return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider));
+ }
+
+ public static int divideListElementsWithApplyFunctionMethod(List values, int divider) {
+ BiFunction division = (a, b) -> a / b;
+ return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider));
+ }
+
+ private static int divide(int value, int factor) {
+ int result = 0;
+ try {
+ result = value / factor;
+ } catch (ArithmeticException e) {
+ LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero");
+ }
+ return result;
+ }
+
+ private static int applyFunction(BiFunction function, int a, int b) {
+ try {
+ return function.apply(a, b);
+ }
+ catch(Exception e) {
+ LOGGER.log(Level.INFO, "Exception occurred!");
+ }
+ return 0;
+ }
+}
diff --git a/core-java-collections-list/src/main/resources/logback.xml b/core-java-modules/core-java-8/src/main/resources/logback.xml
similarity index 100%
rename from core-java-collections-list/src/main/resources/logback.xml
rename to core-java-modules/core-java-8/src/main/resources/logback.xml
diff --git a/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/collectors/Java8CollectorsUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/counter/CounterStatistics.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/counter/CounterStatistics.java
similarity index 97%
rename from core-java-8/src/test/java/com/baeldung/counter/CounterStatistics.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/counter/CounterStatistics.java
index 015ca3f942..e5b03bf355 100644
--- a/core-java-8/src/test/java/com/baeldung/counter/CounterStatistics.java
+++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/counter/CounterStatistics.java
@@ -1,61 +1,61 @@
-package com.baeldung.counter;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Random;
-
-import org.openjdk.jmh.annotations.Benchmark;
-import org.openjdk.jmh.annotations.BenchmarkMode;
-import org.openjdk.jmh.annotations.Fork;
-import org.openjdk.jmh.annotations.Mode;
-
-import com.baeldung.counter.CounterUtil.MutableInteger;
-
-@Fork(value = 1, warmups = 3)
-@BenchmarkMode(Mode.All)
-public class CounterStatistics {
-
- private static final Map counterMap = new HashMap<>();
- private static final Map counterWithMutableIntMap = new HashMap<>();
- private static final Map counterWithIntArrayMap = new HashMap<>();
- private static final Map counterWithLongWrapperMap = new HashMap<>();
- private static final Map counterWithLongWrapperStreamMap = new HashMap<>();
-
- static {
- CounterUtil.COUNTRY_NAMES = new String[10000];
- final String prefix = "NewString";
- Random random = new Random();
- for (int i=0; i<10000; i++) {
- CounterUtil.COUNTRY_NAMES[i] = new String(prefix + random.nextInt(1000));
- }
- }
-
- @Benchmark
- public void wrapperAsCounter() {
- CounterUtil.counterWithWrapperObject(counterMap);
- }
-
- @Benchmark
- public void lambdaExpressionWithWrapper() {
- CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
- }
-
- @Benchmark
- public void parallelStreamWithWrapper() {
- CounterUtil.counterWithParallelStreamAndWrapper(counterWithLongWrapperStreamMap);
- }
-
- @Benchmark
- public void mutableIntegerAsCounter() {
- CounterUtil.counterWithMutableInteger(counterWithMutableIntMap);
- }
-
- @Benchmark
- public void primitiveArrayAsCounter() {
- CounterUtil.counterWithPrimitiveArray(counterWithIntArrayMap);
- }
-
- public static void main(String[] args) throws Exception {
- org.openjdk.jmh.Main.main(args);
- }
-}
+package com.baeldung.counter;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Random;
+
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Mode;
+
+import com.baeldung.counter.CounterUtil.MutableInteger;
+
+@Fork(value = 1, warmups = 3)
+@BenchmarkMode(Mode.All)
+public class CounterStatistics {
+
+ private static final Map counterMap = new HashMap<>();
+ private static final Map counterWithMutableIntMap = new HashMap<>();
+ private static final Map counterWithIntArrayMap = new HashMap<>();
+ private static final Map counterWithLongWrapperMap = new HashMap<>();
+ private static final Map counterWithLongWrapperStreamMap = new HashMap<>();
+
+ static {
+ CounterUtil.COUNTRY_NAMES = new String[10000];
+ final String prefix = "NewString";
+ Random random = new Random();
+ for (int i=0; i<10000; i++) {
+ CounterUtil.COUNTRY_NAMES[i] = new String(prefix + random.nextInt(1000));
+ }
+ }
+
+ @Benchmark
+ public void wrapperAsCounter() {
+ CounterUtil.counterWithWrapperObject(counterMap);
+ }
+
+ @Benchmark
+ public void lambdaExpressionWithWrapper() {
+ CounterUtil.counterWithLambdaAndWrapper(counterWithLongWrapperMap);
+ }
+
+ @Benchmark
+ public void parallelStreamWithWrapper() {
+ CounterUtil.counterWithParallelStreamAndWrapper(counterWithLongWrapperStreamMap);
+ }
+
+ @Benchmark
+ public void mutableIntegerAsCounter() {
+ CounterUtil.counterWithMutableInteger(counterWithMutableIntMap);
+ }
+
+ @Benchmark
+ public void primitiveArrayAsCounter() {
+ CounterUtil.counterWithPrimitiveArray(counterWithIntArrayMap);
+ }
+
+ public static void main(String[] args) throws Exception {
+ org.openjdk.jmh.Main.main(args);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java
similarity index 96%
rename from core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java
index ef57fc2c6e..4f914bd289 100644
--- a/core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java
+++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/counter/CounterUnitTest.java
@@ -1,53 +1,53 @@
-package com.baeldung.counter;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-
-import com.baeldung.counter.CounterUtil.MutableInteger;
-
-public class CounterUnitTest {
-
- @Test
- public void whenMapWithWrapperAsCounter_runsSuccessfully() {
- Map counterMap = new HashMap<>();
- CounterUtil.counterWithWrapperObject(counterMap);
-
- assertEquals(3, counterMap.get("China")
- .intValue());
- assertEquals(2, counterMap.get("India")
- .intValue());
- }
-
- @Test
- public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
- Map counterMap = new HashMap<>();
- CounterUtil.counterWithLambdaAndWrapper(counterMap);
-
- assertEquals(3l, counterMap.get("China")
- .longValue());
- assertEquals(2l, counterMap.get("India")
- .longValue());
- }
-
- @Test
- public void whenMapWithMutableIntegerCounter_runsSuccessfully() {
- Map counterMap = new HashMap<>();
- CounterUtil.counterWithMutableInteger(counterMap);
- assertEquals(3, counterMap.get("China")
- .getCount());
- assertEquals(2, counterMap.get("India")
- .getCount());
- }
-
- @Test
- public void whenMapWithPrimitiveArray_runsSuccessfully() {
- Map counterMap = new HashMap<>();
- CounterUtil.counterWithPrimitiveArray(counterMap);
- assertEquals(3, counterMap.get("China")[0]);
- assertEquals(2, counterMap.get("India")[0]);
- }
-}
+package com.baeldung.counter;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+import com.baeldung.counter.CounterUtil.MutableInteger;
+
+public class CounterUnitTest {
+
+ @Test
+ public void whenMapWithWrapperAsCounter_runsSuccessfully() {
+ Map counterMap = new HashMap<>();
+ CounterUtil.counterWithWrapperObject(counterMap);
+
+ assertEquals(3, counterMap.get("China")
+ .intValue());
+ assertEquals(2, counterMap.get("India")
+ .intValue());
+ }
+
+ @Test
+ public void whenMapWithLambdaAndWrapperCounter_runsSuccessfully() {
+ Map counterMap = new HashMap<>();
+ CounterUtil.counterWithLambdaAndWrapper(counterMap);
+
+ assertEquals(3l, counterMap.get("China")
+ .longValue());
+ assertEquals(2l, counterMap.get("India")
+ .longValue());
+ }
+
+ @Test
+ public void whenMapWithMutableIntegerCounter_runsSuccessfully() {
+ Map counterMap = new HashMap<>();
+ CounterUtil.counterWithMutableInteger(counterMap);
+ assertEquals(3, counterMap.get("China")
+ .getCount());
+ assertEquals(2, counterMap.get("India")
+ .getCount());
+ }
+
+ @Test
+ public void whenMapWithPrimitiveArray_runsSuccessfully() {
+ Map counterMap = new HashMap<>();
+ CounterUtil.counterWithPrimitiveArray(counterMap);
+ assertEquals(3, counterMap.get("China")[0]);
+ assertEquals(2, counterMap.get("India")[0]);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/counter/CounterUtil.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/counter/CounterUtil.java
similarity index 96%
rename from core-java-8/src/test/java/com/baeldung/counter/CounterUtil.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/counter/CounterUtil.java
index c2bf47e213..7e15fa1356 100644
--- a/core-java-8/src/test/java/com/baeldung/counter/CounterUtil.java
+++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/counter/CounterUtil.java
@@ -1,57 +1,57 @@
-package com.baeldung.counter;
-
-import java.util.Map;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
-public class CounterUtil {
-
- public static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
-
- public static void counterWithWrapperObject(Map counterMap) {
- for (String country : COUNTRY_NAMES) {
- counterMap.compute(country, (k, v) -> v == null ? 1 : v + 1);
- }
- }
-
- public static void counterWithLambdaAndWrapper(Map counterMap) {
- Stream.of(COUNTRY_NAMES)
- .collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
- }
-
- public static void counterWithParallelStreamAndWrapper(Map counterMap) {
- Stream.of(COUNTRY_NAMES)
- .parallel()
- .collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
- }
-
- public static class MutableInteger {
- int count;
-
- public MutableInteger(int count) {
- this.count = count;
- }
-
- public void increment() {
- this.count++;
- }
-
- public int getCount() {
- return this.count;
- }
- }
-
- public static void counterWithMutableInteger(Map counterMap) {
- for (String country : COUNTRY_NAMES) {
- counterMap.compute(country, (k, v) -> v == null ? new MutableInteger(0) : v)
- .increment();
- }
- }
-
- public static void counterWithPrimitiveArray(Map counterMap) {
- for (String country : COUNTRY_NAMES) {
- counterMap.compute(country, (k, v) -> v == null ? new int[] { 0 } : v)[0]++;
- }
- }
-
+package com.baeldung.counter;
+
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class CounterUtil {
+
+ public static String[] COUNTRY_NAMES = { "China", "Australia", "India", "USA", "USSR", "UK", "China", "France", "Poland", "Austria", "India", "USA", "Egypt", "China" };
+
+ public static void counterWithWrapperObject(Map counterMap) {
+ for (String country : COUNTRY_NAMES) {
+ counterMap.compute(country, (k, v) -> v == null ? 1 : v + 1);
+ }
+ }
+
+ public static void counterWithLambdaAndWrapper(Map counterMap) {
+ Stream.of(COUNTRY_NAMES)
+ .collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
+ }
+
+ public static void counterWithParallelStreamAndWrapper(Map counterMap) {
+ Stream.of(COUNTRY_NAMES)
+ .parallel()
+ .collect(Collectors.groupingBy(k -> k, () -> counterMap, Collectors.counting()));
+ }
+
+ public static class MutableInteger {
+ int count;
+
+ public MutableInteger(int count) {
+ this.count = count;
+ }
+
+ public void increment() {
+ this.count++;
+ }
+
+ public int getCount() {
+ return this.count;
+ }
+ }
+
+ public static void counterWithMutableInteger(Map counterMap) {
+ for (String country : COUNTRY_NAMES) {
+ counterMap.compute(country, (k, v) -> v == null ? new MutableInteger(0) : v)
+ .increment();
+ }
+ }
+
+ public static void counterWithPrimitiveArray(Map counterMap) {
+ for (String country : COUNTRY_NAMES) {
+ counterMap.compute(country, (k, v) -> v == null ? new int[] { 0 } : v)[0]++;
+ }
+ }
+
}
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/customannotations/JsonSerializerUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/customannotations/JsonSerializerUnitTest.java
similarity index 97%
rename from core-java-8/src/test/java/com/baeldung/customannotations/JsonSerializerUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/customannotations/JsonSerializerUnitTest.java
index f24b37aef7..fd8f8ba8b3 100644
--- a/core-java-8/src/test/java/com/baeldung/customannotations/JsonSerializerUnitTest.java
+++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/customannotations/JsonSerializerUnitTest.java
@@ -1,26 +1,26 @@
-package com.baeldung.customannotations;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
-
-import org.junit.jupiter.api.Test;
-
-public class JsonSerializerUnitTest {
-
- @Test
- public void givenObjectNotSerializedThenExceptionThrown() throws JsonSerializationException {
- Object object = new Object();
- ObjectToJsonConverter serializer = new ObjectToJsonConverter();
- assertThrows(JsonSerializationException.class, () -> {
- serializer.convertToJson(object);
- });
- }
-
- @Test
- public void givenObjectSerializedThenTrueReturned() throws JsonSerializationException {
- Person person = new Person("soufiane", "cheouati", "34");
- ObjectToJsonConverter serializer = new ObjectToJsonConverter();
- String jsonString = serializer.convertToJson(person);
- assertEquals("{\"personAge\":\"34\",\"firstName\":\"Soufiane\",\"lastName\":\"Cheouati\"}", jsonString);
- }
-}
+package com.baeldung.customannotations;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import org.junit.jupiter.api.Test;
+
+public class JsonSerializerUnitTest {
+
+ @Test
+ public void givenObjectNotSerializedThenExceptionThrown() throws JsonSerializationException {
+ Object object = new Object();
+ ObjectToJsonConverter serializer = new ObjectToJsonConverter();
+ assertThrows(JsonSerializationException.class, () -> {
+ serializer.convertToJson(object);
+ });
+ }
+
+ @Test
+ public void givenObjectSerializedThenTrueReturned() throws JsonSerializationException {
+ Person person = new Person("soufiane", "cheouati", "34");
+ ObjectToJsonConverter serializer = new ObjectToJsonConverter();
+ String jsonString = serializer.convertToJson(person);
+ assertEquals("{\"personAge\":\"34\",\"firstName\":\"Soufiane\",\"lastName\":\"Cheouati\"}", jsonString);
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/defaultistaticinterfacemethods/test/StaticDefaulInterfaceMethodUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/defaultistaticinterfacemethods/test/StaticDefaulInterfaceMethodUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/defaultistaticinterfacemethods/test/StaticDefaulInterfaceMethodUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/defaultistaticinterfacemethods/test/StaticDefaulInterfaceMethodUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/doublecolon/ComputerUtilsUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/functionalinterface/ShortToByteFunction.java
diff --git a/core-java-8/src/test/java/com/baeldung/internationalization/DateFormatUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/internationalization/DateFormatUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/internationalization/DateFormatUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/internationalization/DateFormatUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/internationalization/NumbersCurrenciesFormattingUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/internationalization/NumbersCurrenciesFormattingUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/internationalization/NumbersCurrenciesFormattingUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/internationalization/NumbersCurrenciesFormattingUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8DefaultStaticIntefaceMethodsUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8ForEachUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8ForEachUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8ForEachUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8ForEachUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8GroupingByCollectorUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8MethodReferenceUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8OptionalUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8PredicateChainUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8PredicateChainUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8PredicateChainUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8PredicateChainUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
similarity index 74%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
index 71ec5b147f..57d9d8347b 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
+++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
@@ -124,11 +124,44 @@ public class Java8SortUnitTest {
@Test
public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
-
final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
final Comparator nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
final List sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
}
+
+ @Test
+ public final void givenStreamComparatorOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
+ final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
+
+ final List sortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName)).collect(Collectors.toList());
+ Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
+ }
+
+ @Test
+ public final void givenStreamNaturalOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
+ final List letters = Lists.newArrayList("B", "A", "C");
+
+ final List reverseSortedLetters = letters.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
+ Assert.assertThat(reverseSortedLetters.get(0), equalTo("C"));
+ }
+
+ @Test
+ public final void givenStreamCustomOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
+ final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
+ final Comparator reverseNameComparator = (h1, h2) -> h2.getName().compareTo(h1.getName());
+
+ final List reverseSortedHumans = humans.stream().sorted(reverseNameComparator).collect(Collectors.toList());
+ Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
+ }
+
+ @Test
+ public final void givenStreamComparatorOrdering_whenSortingEntitiesByNameReversed_thenCorrectlySorted() {
+ final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
+
+ final List reverseSortedHumans = humans.stream().sorted(Comparator.comparing(Human::getName, Comparator.reverseOrder())).collect(Collectors.toList());
+ Assert.assertThat(reverseSortedHumans.get(0), equalTo(new Human("Sarah", 10)));
+ }
+
}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesLongRunningUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesLongRunningUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesLongRunningUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/JavaTryWithResourcesLongRunningUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/UnsignedArithmeticUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/comparator/Employee.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/comparator/Employee.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/comparator/Employee.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/comparator/Employee.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/comparator/Java8ComparatorUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/entity/Human.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/entity/Human.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/entity/Human.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/entity/Human.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/lambda/exceptions/LambdaExceptionWrappersUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/Bicycle.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/BicycleComparator.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/BicycleComparator.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/BicycleComparator.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/BicycleComparator.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/lambda/methodreference/MethodReferenceUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/lambda/tips/Java8FunctionalInteracesLambdasUnitTest.java
similarity index 93%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/lambda/tips/Java8FunctionalInteracesLambdasUnitTest.java
index 13ddcc805f..b409f8e37f 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8FunctionalInteracesLambdasUnitTest.java
+++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/lambda/tips/Java8FunctionalInteracesLambdasUnitTest.java
@@ -1,8 +1,8 @@
-package com.baeldung.java8;
+package com.baeldung.java8.lambda.tips;
-import com.baeldung.Foo;
-import com.baeldung.FooExtended;
-import com.baeldung.UseFoo;
+import com.baeldung.java8.lambda.tips.Foo;
+import com.baeldung.java8.lambda.tips.FooExtended;
+import com.baeldung.java8.lambda.tips.UseFoo;
import org.junit.Before;
import org.junit.Test;
diff --git a/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java
new file mode 100644
index 0000000000..3e0d752bb6
--- /dev/null
+++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalChainingUnitTest.java
@@ -0,0 +1,110 @@
+package com.baeldung.java8.optional;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.Optional;
+import java.util.function.Supplier;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.*;
+
+public class OptionalChainingUnitTest {
+
+ private boolean getEmptyEvaluated;
+ private boolean getHelloEvaluated;
+ private boolean getByeEvaluated;
+
+ @Before
+ public void setUp() {
+ getEmptyEvaluated = false;
+ getHelloEvaluated = false;
+ getByeEvaluated = false;
+ }
+
+ @Test
+ public void givenThreeOptionals_whenChaining_thenFirstNonEmptyIsReturned() {
+ Optional found = Stream.of(getEmpty(), getHello(), getBye())
+ .filter(Optional::isPresent)
+ .map(Optional::get)
+ .findFirst();
+
+ assertEquals(getHello(), found);
+ }
+
+ @Test
+ public void givenTwoEmptyOptionals_whenChaining_thenEmptyOptionalIsReturned() {
+ Optional found = Stream.of(getEmpty(), getEmpty())
+ .filter(Optional::isPresent)
+ .map(Optional::get)
+ .findFirst();
+
+ assertFalse(found.isPresent());
+ }
+
+ @Test
+ public void givenTwoEmptyOptionals_whenChaining_thenDefaultIsReturned() {
+ String found = Stream.>>of(
+ () -> createOptional("empty"),
+ () -> createOptional("empty")
+ )
+ .map(Supplier::get)
+ .filter(Optional::isPresent)
+ .map(Optional::get)
+ .findFirst()
+ .orElseGet(() -> "default");
+
+ assertEquals("default", found);
+ }
+
+ @Test
+ public void givenThreeOptionals_whenChaining_thenFirstNonEmptyIsReturnedAndRestNotEvaluated() {
+ Optional found = Stream.>>of(this::getEmpty, this::getHello, this::getBye)
+ .map(Supplier::get)
+ .filter(Optional::isPresent)
+ .map(Optional::get)
+ .findFirst();
+
+ assertTrue(this.getEmptyEvaluated);
+ assertTrue(this.getHelloEvaluated);
+ assertFalse(this.getByeEvaluated);
+ assertEquals(getHello(), found);
+ }
+
+ @Test
+ public void givenTwoOptionalsReturnedByOneArgMethod_whenChaining_thenFirstNonEmptyIsReturned() {
+ Optional found = Stream.>>of(
+ () -> createOptional("empty"),
+ () -> createOptional("hello")
+ )
+ .map(Supplier::get)
+ .filter(Optional::isPresent)
+ .map(Optional::get)
+ .findFirst();
+
+ assertEquals(createOptional("hello"), found);
+ }
+
+ private Optional getEmpty() {
+ this.getEmptyEvaluated = true;
+ return Optional.empty();
+ }
+
+ private Optional getHello() {
+ this.getHelloEvaluated = true;
+ return Optional.of("hello");
+ }
+
+ private Optional getBye() {
+ this.getByeEvaluated = true;
+ return Optional.of("bye");
+ }
+
+ private Optional createOptional(String input) {
+ if (input == null || "".equals(input) || "empty".equals(input)) {
+ return Optional.empty();
+ }
+
+ return Optional.of(input);
+ }
+}
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java
similarity index 97%
rename from core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java
index 4cb2551fae..bd7943c77b 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java
+++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OptionalUnitTest.java
@@ -27,34 +27,35 @@ public class OptionalUnitTest {
@Test
public void givenNonNull_whenCreatesNonNullable_thenCorrect() {
String name = "baeldung";
- Optional.of(name);
+ Optional opt = Optional.of(name);
+ assertTrue(opt.isPresent());
}
@Test(expected = NullPointerException.class)
public void givenNull_whenThrowsErrorOnCreate_thenCorrect() {
String name = null;
- Optional opt = Optional.of(name);
+ Optional.of(name);
}
@Test
public void givenNonNull_whenCreatesOptional_thenCorrect() {
String name = "baeldung";
Optional opt = Optional.of(name);
- assertEquals("Optional[baeldung]", opt.toString());
+ assertTrue(opt.isPresent());
}
@Test
public void givenNonNull_whenCreatesNullable_thenCorrect() {
String name = "baeldung";
Optional opt = Optional.ofNullable(name);
- assertEquals("Optional[baeldung]", opt.toString());
+ assertTrue(opt.isPresent());
}
@Test
public void givenNull_whenCreatesNullable_thenCorrect() {
String name = null;
Optional opt = Optional.ofNullable(name);
- assertEquals("Optional.empty", opt.toString());
+ assertFalse(opt.isPresent());
}
// Checking Value With isPresent()
diff --git a/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/java8/optional/OrElseAndOrElseGetUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/math/MathNewMethodsUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/math/MathNewMethodsUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/math/MathNewMethodsUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/math/MathNewMethodsUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/reduceIfelse/CalculatorUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/reduceIfelse/CalculatorUnitTest.java
similarity index 80%
rename from core-java-8/src/test/java/com/baeldung/reduceIfelse/CalculatorUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/reduceIfelse/CalculatorUnitTest.java
index fa351930d8..1ff34bee89 100644
--- a/core-java-8/src/test/java/com/baeldung/reduceIfelse/CalculatorUnitTest.java
+++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/reduceIfelse/CalculatorUnitTest.java
@@ -29,4 +29,11 @@ public class CalculatorUnitTest {
int result = calculator.calculate(new AddCommand(3, 7));
assertEquals(10, result);
}
+
+ @Test
+ public void whenCalculateUsingFactory_thenReturnCorrectResult() {
+ Calculator calculator = new Calculator();
+ int result = calculator.calculateUsingFactory(3, 4, "add");
+ assertEquals(7, result);
+ }
}
diff --git a/core-java-8/src/test/java/com/baeldung/reduceIfelse/RuleEngineUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/reduceIfelse/RuleEngineUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/reduceIfelse/RuleEngineUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/reduceIfelse/RuleEngineUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java
similarity index 97%
rename from core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java
index b191c94826..dadd6d7543 100644
--- a/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java
+++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/reflect/MethodParamNameUnitTest.java
@@ -1,34 +1,34 @@
-package com.baeldung.reflect;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-import java.lang.reflect.Parameter;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Optional;
-
-import org.junit.Test;
-
-public class MethodParamNameUnitTest {
-
- @Test
- public void whenGetConstructorParams_thenOk()
- throws NoSuchMethodException, SecurityException {
- List parameters
- = Arrays.asList(Person.class.getConstructor(String.class).getParameters());
- Optional parameter
- = parameters.stream().filter(Parameter::isNamePresent).findFirst();
- assertThat(parameter.get().getName()).isEqualTo("fullName");
- }
-
- @Test
- public void whenGetMethodParams_thenOk()
- throws NoSuchMethodException, SecurityException {
- List parameters
- = Arrays.asList(
- Person.class.getMethod("setFullName", String.class).getParameters());
- Optional parameter
- = parameters.stream().filter(Parameter::isNamePresent).findFirst();
- assertThat(parameter.get().getName()).isEqualTo("fullName");
- }
-}
+package com.baeldung.reflect;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.lang.reflect.Parameter;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
+import org.junit.Test;
+
+public class MethodParamNameUnitTest {
+
+ @Test
+ public void whenGetConstructorParams_thenOk()
+ throws NoSuchMethodException, SecurityException {
+ List parameters
+ = Arrays.asList(Person.class.getConstructor(String.class).getParameters());
+ Optional parameter
+ = parameters.stream().filter(Parameter::isNamePresent).findFirst();
+ assertThat(parameter.get().getName()).isEqualTo("fullName");
+ }
+
+ @Test
+ public void whenGetMethodParams_thenOk()
+ throws NoSuchMethodException, SecurityException {
+ List parameters
+ = Arrays.asList(
+ Person.class.getMethod("setFullName", String.class).getParameters());
+ Optional parameter
+ = parameters.stream().filter(Parameter::isNamePresent).findFirst();
+ assertThat(parameter.get().getName()).isEqualTo("fullName");
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java
similarity index 97%
rename from core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java
index 81fad12eb0..6981898500 100644
--- a/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java
+++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/spliteratorAPI/ExecutorUnitTest.java
@@ -1,44 +1,44 @@
-package com.baeldung.spliteratorAPI;
-
-import java.util.Arrays;
-import java.util.Spliterator;
-import java.util.stream.Stream;
-import java.util.stream.StreamSupport;
-
-import static org.assertj.core.api.Assertions.*;
-import org.junit.Before;
-import org.junit.Test;
-
-public class ExecutorUnitTest {
- Article article;
- Stream stream;
- Spliterator spliterator;
- Spliterator split1;
- Spliterator split2;
-
- @Before
- public void init() {
- article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1),
- new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
- new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
- new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
- new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
- new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0);
- stream = article.getListOfAuthors().stream();
- split1 = Executor.generateElements().spliterator();
- split2 = split1.trySplit();
- spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors());
- }
-
- @Test
- public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() {
- Stream stream2 = StreamSupport.stream(spliterator, true);
- assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9);
- }
-
- @Test
- public void givenSpliterator_whenAppliedToAListOfArticle_thenSplittedInHalf() {
- assertThat(new Task(split1).call()).containsSequence(Executor.generateElements().size() / 2 + "");
- assertThat(new Task(split2).call()).containsSequence(Executor.generateElements().size() / 2 + "");
- }
-}
+package com.baeldung.spliteratorAPI;
+
+import java.util.Arrays;
+import java.util.Spliterator;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+
+import static org.assertj.core.api.Assertions.*;
+import org.junit.Before;
+import org.junit.Test;
+
+public class ExecutorUnitTest {
+ Article article;
+ Stream stream;
+ Spliterator spliterator;
+ Spliterator split1;
+ Spliterator split2;
+
+ @Before
+ public void init() {
+ article = new Article(Arrays.asList(new Author("Ahmad", 0), new Author("Eugen", 0), new Author("Alice", 1),
+ new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
+ new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0),
+ new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
+ new Author("Mike", 0), new Author("Alice", 1), new Author("Mike", 0), new Author("Alice", 1),
+ new Author("Mike", 0), new Author("Michał", 0), new Author("Loredana", 1)), 0);
+ stream = article.getListOfAuthors().stream();
+ split1 = Executor.generateElements().spliterator();
+ split2 = split1.trySplit();
+ spliterator = new RelatedAuthorSpliterator(article.getListOfAuthors());
+ }
+
+ @Test
+ public void givenAstreamOfAuthors_whenProcessedInParallelWithCustomSpliterator_coubtProducessRightOutput() {
+ Stream stream2 = StreamSupport.stream(spliterator, true);
+ assertThat(Executor.countAutors(stream2.parallel())).isEqualTo(9);
+ }
+
+ @Test
+ public void givenSpliterator_whenAppliedToAListOfArticle_thenSplittedInHalf() {
+ assertThat(new Task(split1).call()).containsSequence(Executor.generateElements().size() / 2 + "");
+ assertThat(new Task(split2).call()).containsSequence(Executor.generateElements().size() / 2 + "");
+ }
+}
diff --git a/core-java-8/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/strategy/StrategyDesignPatternUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/streamreduce/tests/StreamReduceManualTest.java b/core-java-modules/core-java-8/src/test/java/com/baeldung/streamreduce/tests/StreamReduceManualTest.java
similarity index 97%
rename from core-java-8/src/test/java/com/baeldung/streamreduce/tests/StreamReduceManualTest.java
rename to core-java-modules/core-java-8/src/test/java/com/baeldung/streamreduce/tests/StreamReduceManualTest.java
index 9222cbb689..0bf1a5837e 100644
--- a/core-java-8/src/test/java/com/baeldung/streamreduce/tests/StreamReduceManualTest.java
+++ b/core-java-modules/core-java-8/src/test/java/com/baeldung/streamreduce/tests/StreamReduceManualTest.java
@@ -1,126 +1,126 @@
-package com.baeldung.streamreduce.tests;
-
-import com.baeldung.streamreduce.entities.User;
-import com.baeldung.streamreduce.utilities.NumberUtils;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import static org.assertj.core.api.Assertions.assertThat;
-import org.junit.Test;
-
-public class StreamReduceManualTest {
-
- @Test
- public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
- List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
-
- int result = numbers.stream().reduce(0, (a, b) -> a + b);
-
- assertThat(result).isEqualTo(21);
- }
-
- @Test
- public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
- List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
-
- int result = numbers.stream().reduce(0, Integer::sum);
-
- assertThat(result).isEqualTo(21);
- }
-
- @Test
- public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
- List letters = Arrays.asList("a", "b", "c", "d", "e");
-
- String result = letters.stream().reduce("", (a, b) -> a + b);
-
- assertThat(result).isEqualTo("abcde");
- }
-
- @Test
- public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
- List letters = Arrays.asList("a", "b", "c", "d", "e");
-
- String result = letters.stream().reduce("", String::concat);
-
- assertThat(result).isEqualTo("abcde");
- }
-
- @Test
- public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
- List letters = Arrays.asList("a", "b", "c", "d", "e");
-
- String result = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase());
-
- assertThat(result).isEqualTo("ABCDE");
- }
-
- @Test
- public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() {
- List users = Arrays.asList(new User("John", 30), new User("Julie", 35));
-
- int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
-
- assertThat(result).isEqualTo(65);
- }
-
- @Test
- public void givenStringList_whenReduceWithParallelStream_thenCorrect() {
- List letters = Arrays.asList("a", "b", "c", "d", "e");
-
- String result = letters.parallelStream().reduce("", String::concat);
-
- assertThat(result).isEqualTo("abcde");
- }
-
- @Test
- public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() {
- List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
-
- assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21);
- }
-
- @Test
- public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() {
- List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
-
- assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
- }
-
- @Test
- public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlockAndListContainsZero_thenCorrect() {
- List numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6);
-
- assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21);
- }
-
- @Test
- public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlockAndDividerIsZero_thenCorrect() {
- List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
-
- assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 0)).isEqualTo(0);
- }
-
- @Test
- public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() {
- List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
-
- assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21);
- }
-
- @Test
- public void givenTwoStreams_whenCalledReduceOnParallelizedStream_thenFasterExecutionTime() {
- List userList = new ArrayList<>();
- for (int i = 0; i <= 1000000; i++) {
- userList.add(new User("John" + i, i));
- }
- long currentTime1 = System.currentTimeMillis();
- userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
- long sequentialExecutionTime = System.currentTimeMillis() -currentTime1;
- long currentTime2 = System.currentTimeMillis();
- userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
- long parallelizedExecutionTime = System.currentTimeMillis() - currentTime2;
-
- assertThat(parallelizedExecutionTime).isLessThan(sequentialExecutionTime);
- }
-}
+package com.baeldung.streamreduce.tests;
+
+import com.baeldung.streamreduce.entities.User;
+import com.baeldung.streamreduce.utilities.NumberUtils;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import static org.assertj.core.api.Assertions.assertThat;
+import org.junit.Test;
+
+public class StreamReduceManualTest {
+
+ @Test
+ public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() {
+ List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
+
+ int result = numbers.stream().reduce(0, (a, b) -> a + b);
+
+ assertThat(result).isEqualTo(21);
+ }
+
+ @Test
+ public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() {
+ List numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
+
+ int result = numbers.stream().reduce(0, Integer::sum);
+
+ assertThat(result).isEqualTo(21);
+ }
+
+ @Test
+ public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() {
+ List letters = Arrays.asList("a", "b", "c", "d", "e");
+
+ String result = letters.stream().reduce("", (a, b) -> a + b);
+
+ assertThat(result).isEqualTo("abcde");
+ }
+
+ @Test
+ public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() {
+ List letters = Arrays.asList("a", "b", "c", "d", "e");
+
+ String result = letters.stream().reduce("", String::concat);
+
+ assertThat(result).isEqualTo("abcde");
+ }
+
+ @Test
+ public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() {
+ List