diff --git a/.travis.yml b/.travis.yml
index 683422dc97..5e86714a89 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -4,7 +4,7 @@ before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: skip
-script: travis_wait 60 mvn -q install -Pdefault-first,default-second
+script: travis_wait 60 mvn -q install -Pdefault-first,default-second -Dgib.enabled=true
sudo: required
diff --git a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java b/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java
index cb476b9d9e..a50028a9ae 100644
--- a/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java
+++ b/JGit/src/main/java/com/baeldung/jgit/porcelain/Log.java
@@ -28,14 +28,14 @@ public class Log {
System.out.println("Had " + count + " commits overall on current branch");
logs = git.log()
- .add(repository.resolve("remotes/origin/testbranch"))
+ .add(repository.resolve(git.getRepository().getFullBranch()))
.call();
count = 0;
for (RevCommit rev : logs) {
System.out.println("Commit: " + rev /* + ", name: " + rev.getName() + ", id: " + rev.getId().getName() */);
count++;
}
- System.out.println("Had " + count + " commits overall on test-branch");
+ System.out.println("Had " + count + " commits overall on "+git.getRepository().getFullBranch());
logs = git.log()
.all()
diff --git a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
index ed7168b2c2..ad34890996 100644
--- a/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
+++ b/JGit/src/test/java/com/baeldung/jgit/JGitBugIntegrationTest.java
@@ -1,3 +1,5 @@
+package com.baeldung.jgit;
+
import com.baeldung.jgit.helper.Helper;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.ObjectReader;
diff --git a/algorithms-genetic/pom.xml b/algorithms-genetic/pom.xml
index 2a10a81980..fc6d36dac1 100644
--- a/algorithms-genetic/pom.xml
+++ b/algorithms-genetic/pom.xml
@@ -1,10 +1,10 @@
4.0.0
- com.baeldung
algorithms-genetic
0.0.1-SNAPSHOT
-
+ algorithms-genetic
+
com.baeldung
parent-modules
@@ -61,4 +61,5 @@
1.11
-
\ No newline at end of file
+
+
diff --git a/algorithms-miscellaneous-1/pom.xml b/algorithms-miscellaneous-1/pom.xml
index 16749d452e..5006670dd9 100644
--- a/algorithms-miscellaneous-1/pom.xml
+++ b/algorithms-miscellaneous-1/pom.xml
@@ -1,10 +1,10 @@
4.0.0
- com.baeldung
algorithms-miscellaneous-1
0.0.1-SNAPSHOT
-
+ algorithms-miscellaneous-1
+
com.baeldung
parent-modules
@@ -17,6 +17,11 @@
commons-math3
${commons-math3.version}
+
+ com.google.guava
+ guava
+ ${guava.version}
+
commons-codec
commons-codec
@@ -73,6 +78,7 @@
3.6.1
3.9.0
1.11
+ 25.1-jre
\ No newline at end of file
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/factorial/Factorial.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/factorial/Factorial.java
new file mode 100644
index 0000000000..43d2221773
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/factorial/Factorial.java
@@ -0,0 +1,63 @@
+package com.baeldung.algorithms.factorial;
+
+import java.math.BigInteger;
+import java.util.stream.LongStream;
+
+import org.apache.commons.math3.util.CombinatoricsUtils;
+
+import com.google.common.math.BigIntegerMath;
+
+public class Factorial {
+
+ public long factorialUsingForLoop(int n) {
+ long fact = 1;
+ for (int i = 2; i <= n; i++) {
+ fact = fact * i;
+ }
+ return fact;
+ }
+
+ public long factorialUsingStreams(int n) {
+ return LongStream.rangeClosed(1, n)
+ .reduce(1, (long x, long y) -> x * y);
+ }
+
+ public long factorialUsingRecursion(int n) {
+ if (n <= 2) {
+ return n;
+ }
+ return n * factorialUsingRecursion(n - 1);
+ }
+
+ private Long[] factorials = new Long[20];
+
+ public long factorialUsingMemoize(int n) {
+
+ if (factorials[n] != null) {
+ return factorials[n];
+ }
+
+ if (n <= 2) {
+ return n;
+ }
+ long nthValue = n * factorialUsingMemoize(n - 1);
+ factorials[n] = nthValue;
+ return nthValue;
+ }
+
+ public BigInteger factorialHavingLargeResult(int n) {
+ BigInteger result = BigInteger.ONE;
+ for (int i = 2; i <= n; i++)
+ result = result.multiply(BigInteger.valueOf(i));
+ return result;
+ }
+
+ public long factorialUsingApacheCommons(int n) {
+ return CombinatoricsUtils.factorial(n);
+ }
+
+ public BigInteger factorialUsingGuava(int n) {
+ return BigIntegerMath.factorial(n);
+ }
+
+}
diff --git a/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java
new file mode 100644
index 0000000000..cd1f3e94d5
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/main/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharacters.java
@@ -0,0 +1,54 @@
+package com.baeldung.algorithms.string;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+public class LongestSubstringNonRepeatingCharacters {
+
+ public static String getUniqueCharacterSubstringBruteForce(String input) {
+ String output = "";
+ for (int start = 0; start < input.length(); start++) {
+ Set visited = new HashSet<>();
+ int end = start;
+ for (; end < input.length(); end++) {
+ char currChar = input.charAt(end);
+ if (visited.contains(currChar)) {
+ break;
+ } else {
+ visited.add(currChar);
+ }
+ }
+ if (output.length() < end - start + 1) {
+ output = input.substring(start, end);
+ }
+ }
+ return output;
+ }
+
+ public static String getUniqueCharacterSubstring(String input) {
+ Map visited = new HashMap<>();
+ String output = "";
+ for (int start = 0, end = 0; end < input.length(); end++) {
+ char currChar = input.charAt(end);
+ if (visited.containsKey(currChar)) {
+ start = Math.max(visited.get(currChar) + 1, start);
+ }
+ if (output.length() < end - start + 1) {
+ output = input.substring(start, end + 1);
+ }
+ visited.put(currChar, end);
+ }
+ return output;
+ }
+
+ public static void main(String[] args) {
+ if(args.length > 0) {
+ System.out.println(getUniqueCharacterSubstring(args[0]));
+ } else {
+ System.err.println("This program expects command-line input. Please try again!");
+ }
+ }
+
+}
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java
new file mode 100644
index 0000000000..c185dba62b
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/factorial/FactorialUnitTest.java
@@ -0,0 +1,72 @@
+package com.baeldung.algorithms.factorial;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.math.BigInteger;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class FactorialUnitTest {
+
+ Factorial factorial;
+
+ @Before
+ public void setup() {
+ factorial = new Factorial();
+ }
+
+ @Test
+ public void whenCalculatingFactorialUsingForLoop_thenCorrect() {
+ int n = 5;
+
+ assertThat(factorial.factorialUsingForLoop(n)).isEqualTo(120);
+ }
+
+ @Test
+ public void whenCalculatingFactorialUsingStreams_thenCorrect() {
+ int n = 5;
+
+ assertThat(factorial.factorialUsingStreams(n)).isEqualTo(120);
+ }
+
+ @Test
+ public void whenCalculatingFactorialUsingRecursion_thenCorrect() {
+ int n = 5;
+
+ assertThat(factorial.factorialUsingRecursion(n)).isEqualTo(120);
+ }
+
+ @Test
+ public void whenCalculatingFactorialUsingMemoize_thenCorrect() {
+ int n = 5;
+
+ assertThat(factorial.factorialUsingMemoize(n)).isEqualTo(120);
+
+ n = 6;
+
+ assertThat(factorial.factorialUsingMemoize(n)).isEqualTo(720);
+ }
+
+ @Test
+ public void whenCalculatingFactorialHavingLargeResult_thenCorrect() {
+ int n = 22;
+
+ assertThat(factorial.factorialHavingLargeResult(n)).isEqualTo(new BigInteger("1124000727777607680000"));
+ }
+
+ @Test
+ public void whenCalculatingFactorialUsingApacheCommons_thenCorrect() {
+ int n = 5;
+
+ assertThat(factorial.factorialUsingApacheCommons(n)).isEqualTo(120);
+ }
+
+ @Test
+ public void whenCalculatingFactorialUsingGuava_thenCorrect() {
+ int n = 22;
+
+ assertThat(factorial.factorialUsingGuava(n)).isEqualTo(new BigInteger("1124000727777607680000"));
+ }
+
+}
diff --git a/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java
new file mode 100644
index 0000000000..9f1e6a2519
--- /dev/null
+++ b/algorithms-miscellaneous-1/src/test/java/com/baeldung/algorithms/string/LongestSubstringNonRepeatingCharactersUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.algorithms.string;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstring;
+import static com.baeldung.algorithms.string.LongestSubstringNonRepeatingCharacters.getUniqueCharacterSubstringBruteForce;
+
+public class LongestSubstringNonRepeatingCharactersUnitTest {
+
+ @Test
+ void givenString_whenGetUniqueCharacterSubstringBruteForceCalled_thenResultFoundAsExpectedUnitTest() {
+ assertEquals("", getUniqueCharacterSubstringBruteForce(""));
+ assertEquals("A", getUniqueCharacterSubstringBruteForce("A"));
+ assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("AABCDEF"));
+ assertEquals("ABCDEF", getUniqueCharacterSubstringBruteForce("ABCDEFF"));
+ assertEquals("NGISAWE", getUniqueCharacterSubstringBruteForce("CODINGISAWESOME"));
+ assertEquals("be coding", getUniqueCharacterSubstringBruteForce("always be coding"));
+ }
+
+ @Test
+ void givenString_whenGetUniqueCharacterSubstringCalled_thenResultFoundAsExpectedUnitTest() {
+ assertEquals("", getUniqueCharacterSubstring(""));
+ assertEquals("A", getUniqueCharacterSubstring("A"));
+ assertEquals("ABCDEF", getUniqueCharacterSubstring("AABCDEF"));
+ assertEquals("ABCDEF", getUniqueCharacterSubstring("ABCDEFF"));
+ assertEquals("NGISAWE", getUniqueCharacterSubstring("CODINGISAWESOME"));
+ assertEquals("be coding", getUniqueCharacterSubstring("always be coding"));
+ }
+
+}
diff --git a/algorithms-miscellaneous-2/README.md b/algorithms-miscellaneous-2/README.md
index 6772a94a8d..d693a44f66 100644
--- a/algorithms-miscellaneous-2/README.md
+++ b/algorithms-miscellaneous-2/README.md
@@ -17,3 +17,4 @@
- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
- [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)
diff --git a/algorithms-miscellaneous-2/pom.xml b/algorithms-miscellaneous-2/pom.xml
index eeae544612..5461f4ebe1 100644
--- a/algorithms-miscellaneous-2/pom.xml
+++ b/algorithms-miscellaneous-2/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldung
algorithms-miscellaneous-2
0.0.1-SNAPSHOT
+ algorithms-miscellaneous-2
com.baeldung
@@ -33,6 +33,11 @@
jgrapht-core
${org.jgrapht.core.version}
+
+ org.jgrapht
+ jgrapht-ext
+ ${org.jgrapht.ext.version}
+
pl.allegro.finance
tradukisto
@@ -83,6 +88,7 @@
3.6.1
1.0.1
1.0.1
+ 1.0.1
3.9.0
1.11
diff --git a/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java
new file mode 100644
index 0000000000..3b841d574a
--- /dev/null
+++ b/algorithms-miscellaneous-2/src/test/java/com/baeldung/jgrapht/GraphImageGenerationUnitTest.java
@@ -0,0 +1,47 @@
+package com.baeldung.jgrapht;
+
+import static org.junit.Assert.assertTrue;
+import java.awt.Color;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+import javax.imageio.ImageIO;
+import org.jgrapht.ext.JGraphXAdapter;
+import org.jgrapht.graph.DefaultDirectedGraph;
+import org.jgrapht.graph.DefaultEdge;
+import org.junit.Before;
+import org.junit.Test;
+import com.mxgraph.layout.mxCircleLayout;
+import com.mxgraph.layout.mxIGraphLayout;
+import com.mxgraph.util.mxCellRenderer;
+
+public class GraphImageGenerationUnitTest {
+ static DefaultDirectedGraph g;
+
+ @Before
+ public void createGraph() throws IOException {
+ File imgFile = new File("src/test/resources/graph.png");
+ imgFile.createNewFile();
+ g = new DefaultDirectedGraph(DefaultEdge.class);
+ String x1 = "x1";
+ String x2 = "x2";
+ String x3 = "x3";
+ g.addVertex(x1);
+ g.addVertex(x2);
+ g.addVertex(x3);
+ g.addEdge(x1, x2);
+ g.addEdge(x2, x3);
+ g.addEdge(x3, x1);
+ }
+
+ @Test
+ public void givenAdaptedGraph_whenWriteBufferedImage_ThenFileShouldExist() throws IOException {
+ JGraphXAdapter graphAdapter = new JGraphXAdapter(g);
+ mxIGraphLayout layout = new mxCircleLayout(graphAdapter);
+ layout.execute(graphAdapter.getDefaultParent());
+ File imgFile = new File("src/test/resources/graph.png");
+ BufferedImage image = mxCellRenderer.createBufferedImage(graphAdapter, null, 2, Color.WHITE, true, null);
+ ImageIO.write(image, "PNG", imgFile);
+ assertTrue(imgFile.exists());
+ }
+}
\ No newline at end of file
diff --git a/algorithms-miscellaneous-2/src/test/resources/graph.png b/algorithms-miscellaneous-2/src/test/resources/graph.png
new file mode 100644
index 0000000000..56995b8dd9
Binary files /dev/null and b/algorithms-miscellaneous-2/src/test/resources/graph.png differ
diff --git a/algorithms-sorting/pom.xml b/algorithms-sorting/pom.xml
index 60ae37f2a4..2aee6e9199 100644
--- a/algorithms-sorting/pom.xml
+++ b/algorithms-sorting/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldung
algorithms-sorting
0.0.1-SNAPSHOT
+ algorithms-sorting
com.baeldung
diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml
index 8e53334521..d9aca6040d 100644
--- a/annotations/annotation-processing/pom.xml
+++ b/annotations/annotation-processing/pom.xml
@@ -3,7 +3,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
annotation-processing
-
+ annotation-processing
+
com.baeldung
1.0.0-SNAPSHOT
diff --git a/annotations/annotation-user/pom.xml b/annotations/annotation-user/pom.xml
index 07ea9a5b5a..422cc7f119 100644
--- a/annotations/annotation-user/pom.xml
+++ b/annotations/annotation-user/pom.xml
@@ -3,6 +3,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
annotation-user
+ annotation-user
annotations
diff --git a/annotations/pom.xml b/annotations/pom.xml
index 2c73d3d91b..6d83f5b057 100644
--- a/annotations/pom.xml
+++ b/annotations/pom.xml
@@ -4,7 +4,8 @@
4.0.0
annotations
pom
-
+ annotations
+
parent-modules
com.baeldung
diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml
index ddf5844271..18f9c34d64 100644
--- a/apache-avro/pom.xml
+++ b/apache-avro/pom.xml
@@ -3,10 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.baeldung
apache-avro
0.0.1-SNAPSHOT
- Apache Avro
+ apache-avro
UTF-8
diff --git a/apache-bval/pom.xml b/apache-bval/pom.xml
index 5ddb1ecb59..786f587fb1 100644
--- a/apache-bval/pom.xml
+++ b/apache-bval/pom.xml
@@ -4,7 +4,8 @@
apache-bval
apache-bval
0.0.1-SNAPSHOT
-
+ apache-bval
+
com.baeldung
parent-modules
diff --git a/apache-curator/pom.xml b/apache-curator/pom.xml
index ac10811e7a..bcca38b199 100644
--- a/apache-curator/pom.xml
+++ b/apache-curator/pom.xml
@@ -4,6 +4,7 @@
apache-curator
0.0.1-SNAPSHOT
jar
+ apache-curator
com.baeldung
diff --git a/apache-cxf/cxf-aegis/pom.xml b/apache-cxf/cxf-aegis/pom.xml
index b7e9e426a2..1d36178b82 100644
--- a/apache-cxf/cxf-aegis/pom.xml
+++ b/apache-cxf/cxf-aegis/pom.xml
@@ -2,7 +2,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
cxf-aegis
-
+ cxf-aegis
+
com.baeldung
apache-cxf
diff --git a/apache-cxf/cxf-introduction/pom.xml b/apache-cxf/cxf-introduction/pom.xml
index a9e82c16b3..17f03afd25 100644
--- a/apache-cxf/cxf-introduction/pom.xml
+++ b/apache-cxf/cxf-introduction/pom.xml
@@ -4,7 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
cxf-introduction
-
+ cxf-introduction
+
com.baeldung
apache-cxf
diff --git a/apache-cxf/cxf-jaxrs-implementation/pom.xml b/apache-cxf/cxf-jaxrs-implementation/pom.xml
index 89acbdf1bd..03d0f67c90 100644
--- a/apache-cxf/cxf-jaxrs-implementation/pom.xml
+++ b/apache-cxf/cxf-jaxrs-implementation/pom.xml
@@ -4,7 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
cxf-jaxrs-implementation
-
+ cxf-jaxrs-implementation
+
com.baeldung
apache-cxf
diff --git a/apache-cxf/cxf-spring/pom.xml b/apache-cxf/cxf-spring/pom.xml
index 31e75e7cdd..97715af54c 100644
--- a/apache-cxf/cxf-spring/pom.xml
+++ b/apache-cxf/cxf-spring/pom.xml
@@ -3,6 +3,7 @@
4.0.0
cxf-spring
war
+ cxf-spring
com.baeldung
diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml
index 8918fd4450..0016f33d70 100644
--- a/apache-cxf/pom.xml
+++ b/apache-cxf/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldung
apache-cxf
0.0.1-SNAPSHOT
+ apache-cxf
pom
diff --git a/apache-cxf/sse-jaxrs/pom.xml b/apache-cxf/sse-jaxrs/pom.xml
index d4b6c19d03..cb5c96660a 100644
--- a/apache-cxf/sse-jaxrs/pom.xml
+++ b/apache-cxf/sse-jaxrs/pom.xml
@@ -3,8 +3,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
sse-jaxrs
+ sse-jaxrs
pom
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
index 0f5406fbc7..c7acf22c32 100644
--- a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
@@ -3,15 +3,15 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
+ sse-jaxrs-client
+ sse-jaxrs-client
+
com.baeldung
sse-jaxrs
0.0.1-SNAPSHOT
- sse-jaxrs-client
-
3.2.0
@@ -21,7 +21,6 @@
org.codehaus.mojo
exec-maven-plugin
- 1.6.0
singleEvent
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
index 2e82dc3829..eeb5726ee1 100644
--- a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
@@ -3,16 +3,16 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
+ sse-jaxrs-server
+ sse-jaxrs-server
+ war
+
com.baeldung
sse-jaxrs
0.0.1-SNAPSHOT
- sse-jaxrs-server
- war
-
2.4.2
false
diff --git a/apache-geode/pom.xml b/apache-geode/pom.xml
index a3f6604ac4..738accdcb8 100644
--- a/apache-geode/pom.xml
+++ b/apache-geode/pom.xml
@@ -3,11 +3,10 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
- com.baeldung
apache-geode
1.0-SNAPSHOT
-
+ apache-geode
+
com.baeldung
parent-modules
diff --git a/apache-opennlp/pom.xml b/apache-opennlp/pom.xml
index 985c9a2df2..6b2e6a9729 100644
--- a/apache-opennlp/pom.xml
+++ b/apache-opennlp/pom.xml
@@ -4,6 +4,7 @@
4.0.0
apache-opennlp
1.0-SNAPSHOT
+ apache-opennlp
jar
diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml
index a1ec626d43..54c3e8e928 100644
--- a/apache-poi/pom.xml
+++ b/apache-poi/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldung
apache-poi
0.0.1-SNAPSHOT
+ apache-poi
com.baeldung
diff --git a/apache-pulsar/pom.xml b/apache-pulsar/pom.xml
index da004a7638..a4c09586eb 100644
--- a/apache-pulsar/pom.xml
+++ b/apache-pulsar/pom.xml
@@ -1,21 +1,22 @@
- 4.0.0
- com.baeldung.pulsar
- pulsar-java
- 0.0.1
+ 4.0.0
+ com.baeldung.pulsar
+ apache-pulsar
+ 0.0.1
+ apache-pulsar
-
-
- org.apache.pulsar
- pulsar-client
- 2.1.1-incubating
- compile
-
-
-
- 1.8
- 1.8
-
+
+
+ org.apache.pulsar
+ pulsar-client
+ 2.1.1-incubating
+ compile
+
+
+
+ 1.8
+ 1.8
+
diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml
index 98d9563284..644d70b30a 100644
--- a/apache-shiro/pom.xml
+++ b/apache-shiro/pom.xml
@@ -5,7 +5,8 @@
4.0.0
apache-shiro
1.0-SNAPSHOT
-
+ apache-shiro
+
parent-boot-1
com.baeldung
diff --git a/apache-thrift/pom.xml b/apache-thrift/pom.xml
index b22364cb19..ab54fc2cef 100644
--- a/apache-thrift/pom.xml
+++ b/apache-thrift/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldung
apache-thrift
0.0.1-SNAPSHOT
+ apache-thrift
pom
diff --git a/apache-tika/pom.xml b/apache-tika/pom.xml
index 5a76fdeeda..0399914a5f 100644
--- a/apache-tika/pom.xml
+++ b/apache-tika/pom.xml
@@ -1,10 +1,10 @@
4.0.0
- com.baeldung
apache-tika
0.0.1-SNAPSHOT
-
+ apache-tika
+
com.baeldung
parent-modules
diff --git a/apache-zookeeper/pom.xml b/apache-zookeeper/pom.xml
index 0b29186ccc..53e4217358 100644
--- a/apache-zookeeper/pom.xml
+++ b/apache-zookeeper/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldung
apache-zookeeper
0.0.1-SNAPSHOT
+ apache-zookeeper
jar
diff --git a/asm/pom.xml b/asm/pom.xml
index 5aad2a0e37..e56438c808 100644
--- a/asm/pom.xml
+++ b/asm/pom.xml
@@ -5,6 +5,7 @@
com.baeldung.examples
asm
1.0
+ asm
jar
diff --git a/atomix/pom.xml b/atomix/pom.xml
index f85d2d7484..e50c1d867f 100644
--- a/atomix/pom.xml
+++ b/atomix/pom.xml
@@ -4,7 +4,8 @@
com.atomix.io
atomix
0.0.1-SNAPSHOT
-
+ atomix
+
com.baeldung
parent-modules
diff --git a/axon/pom.xml b/axon/pom.xml
index 915a04feb5..c643ea9e57 100644
--- a/axon/pom.xml
+++ b/axon/pom.xml
@@ -3,7 +3,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
axon
-
+ axon
+
parent-modules
com.baeldung
diff --git a/cas/cas-server/pom.xml b/cas/cas-server/pom.xml
index 9b61aaec3d..98f5f10493 100644
--- a/cas/cas-server/pom.xml
+++ b/cas/cas-server/pom.xml
@@ -3,8 +3,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd ">
4.0.0
cas-server
- war
1.0
+ cas-server
+ war
parent-boot-1
diff --git a/cdi/README.md b/cdi/README.md
index 0477ce85bd..bfb635be9e 100644
--- a/cdi/README.md
+++ b/cdi/README.md
@@ -1,3 +1,5 @@
### Relevant Articles:
- [CDI Interceptor vs Spring AspectJ](http://www.baeldung.com/cdi-interceptor-vs-spring-aspectj)
- [An Introduction to CDI (Contexts and Dependency Injection) in Java](http://www.baeldung.com/java-ee-cdi)
+- [Introduction to the Event Notification Model in CDI 2.0](https://www.baeldung.com/cdi-event-notification)
+
diff --git a/cdi/pom.xml b/cdi/pom.xml
index 2c719c1d7f..0cf5062ccc 100644
--- a/cdi/pom.xml
+++ b/cdi/pom.xml
@@ -2,10 +2,10 @@
4.0.0
- com.baeldung
cdi
1.0-SNAPSHOT
-
+ cdi
+
com.baeldung
parent-spring-4
@@ -14,6 +14,16 @@
+
+ javax.enterprise
+ cdi-api
+ ${cdi-api.version}
+
+
+ org.jboss.weld.se
+ weld-se-core
+ ${weld-se-core.version}
+
org.hamcrest
hamcrest-core
@@ -42,11 +52,6 @@
aspectjweaver
${aspectjweaver.version}
-
- org.jboss.weld.se
- weld-se-core
- ${weld-se-core.version}
-
org.springframework
spring-test
@@ -54,13 +59,13 @@
test
-
- 1.8.9
- 2.4.1.Final
+ 2.0.SP1
+ 3.0.5.Final
+ 1.9.2
1.3
3.10.0
4.12
+ 5.1.2.RELEASE
-
diff --git a/cdi/src/main/java/com/baeldung/cdi2observers/application/BootstrappingApplication.java b/cdi/src/main/java/com/baeldung/cdi2observers/application/BootstrappingApplication.java
new file mode 100644
index 0000000000..4896408502
--- /dev/null
+++ b/cdi/src/main/java/com/baeldung/cdi2observers/application/BootstrappingApplication.java
@@ -0,0 +1,15 @@
+package com.baeldung.cdi.cdi2observers.application;
+
+import com.baeldung.cdi.cdi2observers.events.ExampleEvent;
+import javax.enterprise.inject.se.SeContainer;
+import javax.enterprise.inject.se.SeContainerInitializer;
+
+public class BootstrappingApplication {
+
+ public static void main(String... args) {
+ SeContainerInitializer containerInitializer = SeContainerInitializer.newInstance();
+ try (SeContainer container = containerInitializer.initialize()) {
+ container.getBeanManager().fireEvent(new ExampleEvent("Welcome to Baeldung!"));
+ }
+ }
+}
diff --git a/cdi/src/main/java/com/baeldung/cdi2observers/events/ExampleEvent.java b/cdi/src/main/java/com/baeldung/cdi2observers/events/ExampleEvent.java
new file mode 100644
index 0000000000..a2329d2ef1
--- /dev/null
+++ b/cdi/src/main/java/com/baeldung/cdi2observers/events/ExampleEvent.java
@@ -0,0 +1,14 @@
+package com.baeldung.cdi.cdi2observers.events;
+
+public class ExampleEvent {
+
+ private final String eventMessage;
+
+ public ExampleEvent(String eventMessage) {
+ this.eventMessage = eventMessage;
+ }
+
+ public String getEventMessage() {
+ return eventMessage;
+ }
+}
diff --git a/cdi/src/main/java/com/baeldung/cdi2observers/events/ExampleEventSource.java b/cdi/src/main/java/com/baeldung/cdi2observers/events/ExampleEventSource.java
new file mode 100644
index 0000000000..f37030778a
--- /dev/null
+++ b/cdi/src/main/java/com/baeldung/cdi2observers/events/ExampleEventSource.java
@@ -0,0 +1,14 @@
+package com.baeldung.cdi.cdi2observers.events;
+
+import javax.enterprise.event.Event;
+import javax.inject.Inject;
+
+public class ExampleEventSource {
+
+ @Inject
+ Event exampleEvent;
+
+ public void fireEvent() {
+ exampleEvent.fireAsync(new ExampleEvent("Welcome to Baeldung!"));
+ }
+}
diff --git a/cdi/src/main/java/com/baeldung/cdi2observers/observers/AnotherExampleEventObserver.java b/cdi/src/main/java/com/baeldung/cdi2observers/observers/AnotherExampleEventObserver.java
new file mode 100644
index 0000000000..34520c2b3d
--- /dev/null
+++ b/cdi/src/main/java/com/baeldung/cdi2observers/observers/AnotherExampleEventObserver.java
@@ -0,0 +1,12 @@
+package com.baeldung.cdi.cdi2observers.observers;
+
+import com.baeldung.cdi.cdi2observers.events.ExampleEvent;
+import javax.annotation.Priority;
+import javax.enterprise.event.Observes;
+
+public class AnotherExampleEventObserver {
+
+ public String onEvent(@Observes @Priority(2) ExampleEvent event) {
+ return event.getEventMessage();
+ }
+}
diff --git a/cdi/src/main/java/com/baeldung/cdi2observers/observers/ExampleEventObserver.java b/cdi/src/main/java/com/baeldung/cdi2observers/observers/ExampleEventObserver.java
new file mode 100644
index 0000000000..b3522b2ad0
--- /dev/null
+++ b/cdi/src/main/java/com/baeldung/cdi2observers/observers/ExampleEventObserver.java
@@ -0,0 +1,13 @@
+package com.baeldung.cdi.cdi2observers.observers;
+
+import com.baeldung.cdi.cdi2observers.events.ExampleEvent;
+import com.baeldung.cdi.cdi2observers.services.TextService;
+import javax.annotation.Priority;
+import javax.enterprise.event.Observes;
+
+public class ExampleEventObserver {
+
+ public String onEvent(@Observes @Priority(1) ExampleEvent event, TextService textService) {
+ return textService.parseText(event.getEventMessage());
+ }
+}
diff --git a/cdi/src/main/java/com/baeldung/cdi2observers/services/TextService.java b/cdi/src/main/java/com/baeldung/cdi2observers/services/TextService.java
new file mode 100644
index 0000000000..47788a0657
--- /dev/null
+++ b/cdi/src/main/java/com/baeldung/cdi2observers/services/TextService.java
@@ -0,0 +1,8 @@
+package com.baeldung.cdi.cdi2observers.services;
+
+public class TextService {
+
+ public String parseText(String text) {
+ return text.toUpperCase();
+ }
+}
diff --git a/cdi/src/test/java/com/baeldung/test/cdi2observers/tests/TextServiceUnitTest.java b/cdi/src/test/java/com/baeldung/test/cdi2observers/tests/TextServiceUnitTest.java
new file mode 100644
index 0000000000..deecf13f9a
--- /dev/null
+++ b/cdi/src/test/java/com/baeldung/test/cdi2observers/tests/TextServiceUnitTest.java
@@ -0,0 +1,14 @@
+package com.baeldung.cdi.cdi2observers.tests;
+
+import com.baeldung.cdi.cdi2observers.services.TextService;
+import static org.assertj.core.api.Assertions.assertThat;
+import org.junit.Test;
+
+public class TextServiceUnitTest {
+
+ @Test
+ public void givenTextServiceInstance_whenCalledparseText_thenCorrect() {
+ TextService textService = new TextService();
+ assertThat(textService.parseText("Baeldung")).isEqualTo("BAELDUNG");
+ }
+}
diff --git a/core-groovy/pom.xml b/core-groovy/pom.xml
index 909250710e..e54c766280 100644
--- a/core-groovy/pom.xml
+++ b/core-groovy/pom.xml
@@ -4,6 +4,7 @@
4.0.0
core-groovy
1.0-SNAPSHOT
+ core-groovy
jar
diff --git a/core-java-10/README.md b/core-java-10/README.md
index 84fa381a26..f0a25712a7 100644
--- a/core-java-10/README.md
+++ b/core-java-10/README.md
@@ -4,3 +4,4 @@
- [Java 10 LocalVariable Type-Inference](http://www.baeldung.com/java-10-local-variable-type-inference)
- [Guide to Java 10](http://www.baeldung.com/java-10-overview)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
+- [Deep Dive Into the New Java JIT Compiler – Graal](https://www.baeldung.com/graal-java-jit-compiler)
diff --git a/core-java-8/README.md b/core-java-8/README.md
index ffd629a170..6786b29120 100644
--- a/core-java-8/README.md
+++ b/core-java-8/README.md
@@ -33,3 +33,4 @@
- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
- [How to Use if/else Logic in Java 8 Streams](https://www.baeldung.com/java-8-streams-if-else-logic)
+- [How to Replace Many if Statements in Java](https://www.baeldung.com/java-replace-if-statements)
diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml
index f22d0a3ed9..cd1fa74dbb 100644
--- a/core-java-9/pom.xml
+++ b/core-java-9/pom.xml
@@ -1,7 +1,6 @@
4.0.0
- com.baeldung
core-java-9
0.2-SNAPSHOT
core-java-9
diff --git a/core-java-arrays/README.md b/core-java-arrays/README.md
index bda2cf90bf..56110585ac 100644
--- a/core-java-arrays/README.md
+++ b/core-java-arrays/README.md
@@ -12,4 +12,4 @@
- [Arrays in Java: A Reference Guide](https://www.baeldung.com/java-arrays-guide)
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
- [Array Operations in Java](http://www.baeldung.com/java-common-array-operations)
-
+- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
diff --git a/core-java-arrays/src/main/java/com/baeldung/array/operations/ArrayOperations.java b/core-java-arrays/src/main/java/com/baeldung/array/operations/ArrayOperations.java
index 98155ed952..d8cc0afd61 100644
--- a/core-java-arrays/src/main/java/com/baeldung/array/operations/ArrayOperations.java
+++ b/core-java-arrays/src/main/java/com/baeldung/array/operations/ArrayOperations.java
@@ -4,11 +4,13 @@ import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
+import java.util.LinkedList;
import java.util.Random;
import java.util.Set;
import java.util.function.Function;
import java.util.function.IntPredicate;
import java.util.function.Predicate;
+import java.util.stream.Stream;
import org.apache.commons.lang3.ArrayUtils;
@@ -194,4 +196,16 @@ public class ArrayOperations {
public static T getRandomFromObjectArray(T[] array) {
return array[new Random().nextInt(array.length)];
}
+
+ public static Integer[] intersectionSimple(final Integer[] a, final Integer[] b){
+ return Stream.of(a).filter(Arrays.asList(b)::contains).toArray(Integer[]::new);
+ }
+
+ public static Integer[] intersectionSet(final Integer[] a, final Integer[] b){
+ return Stream.of(a).filter(Arrays.asList(b)::contains).distinct().toArray(Integer[]::new);
+ }
+
+ public static Integer[] intersectionMultiSet(final Integer[] a, final Integer[] b){
+ return Stream.of(a).filter(new LinkedList<>(Arrays.asList(b))::remove).toArray(Integer[]::new);
+ }
}
diff --git a/core-java-arrays/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java b/core-java-arrays/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java
new file mode 100644
index 0000000000..3c61060ea8
--- /dev/null
+++ b/core-java-arrays/src/test/java/com/baeldung/array/operations/IntersectionUnitTest.java
@@ -0,0 +1,66 @@
+package com.baeldung.array.operations;
+
+import org.junit.jupiter.api.Test;
+
+import static com.baeldung.array.operations.ArrayOperations.intersectionMultiSet;
+import static com.baeldung.array.operations.ArrayOperations.intersectionSet;
+import static com.baeldung.array.operations.ArrayOperations.intersectionSimple;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class IntersectionUnitTest {
+ private static final Integer[] a = { 1, 3, 2 };
+ private static final Integer[] b = { 4, 3, 2, 4, 2, 3, 4, 4, 3 };
+ private static final Integer[] c = { 1, 3, 2, 3, 3, 2 };
+
+ @Test
+ void whenIntersectionSimpleIsUsed_thenCommonEntriesAreInTheResult() {
+ assertThat(intersectionSimple(a, b)).isEqualTo(new Integer[] { 3, 2 });
+ assertThat(intersectionSimple(b, a)).isEqualTo(new Integer[] { 3, 2, 2, 3, 3 });
+ }
+
+ @Test
+ void whenIntersectionSimpleIsUsedWithAnArrayAndItself_thenTheResultIsTheIdentity() {
+ assertThat(intersectionSimple(b, b)).isEqualTo(b);
+ assertThat(intersectionSimple(a, a)).isEqualTo(a);
+ }
+
+ @Test
+ void whenIntersectionSetIsUsed_thenCommonEntriesAreInTheResult() {
+ assertThat(intersectionSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
+ }
+
+ @Test
+ void whenIntersectionSetIsUsed_thenTheNumberOfEntriesDoesNotChangeWithTheParameterOrder() {
+ assertThat(intersectionSet(a, b)).isEqualTo(new Integer[] { 3, 2 });
+ assertThat(intersectionSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
+ }
+
+ @Test
+ void whenIntersectionSetIsUsedWithAnArrayAndWithItself_andTheInputHasNoDuplicateEntries_ThenTheResultIsTheIdentity() {
+ assertThat(intersectionSet(a, a)).isEqualTo(a);
+ }
+
+ @Test
+ void whenIntersectionSetIsUsedWithAnArrayAndWithItself_andTheInputHasDuplicateEntries_ThenTheResultIsNotTheIdentity() {
+ assertThat(intersectionSet(b, b)).isNotEqualTo(b);
+ }
+
+ @Test
+ void whenMultiSetIsUsed_thenCommonEntriesAreInTheResult() {
+ assertThat(intersectionMultiSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
+ }
+
+ @Test
+ void whenIntersectionMultiSetIsUsed_thenTheNumberOfEntriesDoesNotChangeWithTheParameterOrder() {
+ assertThat(intersectionMultiSet(a, b)).isEqualTo(new Integer[] { 3, 2 });
+ assertThat(intersectionMultiSet(b, a)).isEqualTo(new Integer[] { 3, 2 });
+ assertThat(intersectionMultiSet(b, c)).isEqualTo(new Integer[] { 3, 2, 2, 3, 3 });
+ assertThat(intersectionMultiSet(c, b)).isEqualTo(new Integer[] { 3, 2, 3, 3, 2 });
+ }
+
+ @Test
+ void whenIntersectionMultiSetIsUsedWithAnArrayAndWithItself_ThenTheResultIsTheIdentity() {
+ assertThat(intersectionMultiSet(b, b)).isEqualTo(b);
+ assertThat(intersectionMultiSet(a, a)).isEqualTo(a);
+ }
+}
\ No newline at end of file
diff --git a/core-java-collections/README.md b/core-java-collections/README.md
index fbc8144954..4c0b24cd5d 100644
--- a/core-java-collections/README.md
+++ b/core-java-collections/README.md
@@ -43,3 +43,12 @@
- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist)
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
+- [Sorting in Java](http://www.baeldung.com/java-sorting)
+- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
+- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
+- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
+- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
+- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
+- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
+- [A Guide to EnumMap](https://www.baeldung.com/java-enum-map)
+- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml
index 31f0d7419f..2201ee8b15 100644
--- a/core-java-collections/pom.xml
+++ b/core-java-collections/pom.xml
@@ -56,6 +56,12 @@
commons-exec
1.3
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+ provided
+
@@ -67,5 +73,6 @@
1.7.0
3.11.1
7.1.0
+ 1.16.12
diff --git a/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java b/core-java-collections/src/main/java/com/baeldung/classcastexception/ClassCastException.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java
rename to core-java-collections/src/main/java/com/baeldung/classcastexception/ClassCastException.java
diff --git a/core-java-collections/src/main/java/com/baeldung/java/list/WaysToIterate.java b/core-java-collections/src/main/java/com/baeldung/java/list/WaysToIterate.java
new file mode 100644
index 0000000000..3cce08eabb
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/java/list/WaysToIterate.java
@@ -0,0 +1,67 @@
+package com.baeldung.java.list;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+
+/**
+ * Demonstrates the different ways to loop over
+ * the elements of a list.
+ */
+public class WaysToIterate {
+
+ List countries = Arrays.asList("Germany", "Panama", "Australia");
+
+ /**
+ * Iterate over a list using a basic for loop
+ */
+ public void iterateWithForLoop() {
+ for (int i = 0; i < countries.size(); i++) {
+ System.out.println(countries.get(i));
+ }
+ }
+
+ /**
+ * Iterate over a list using the enhanced for loop
+ */
+ public void iterateWithEnhancedForLoop() {
+ for (String country : countries) {
+ System.out.println(country);
+ }
+ }
+
+ /**
+ * Iterate over a list using an Iterator
+ */
+ public void iterateWithIterator() {
+ Iterator countriesIterator = countries.iterator();
+ while(countriesIterator.hasNext()) {
+ System.out.println(countriesIterator.next());
+ }
+ }
+
+ /**
+ * Iterate over a list using a ListIterator
+ */
+ public void iterateWithListIterator() {
+ ListIterator listIterator = countries.listIterator();
+ while(listIterator.hasNext()) {
+ System.out.println(listIterator.next());
+ }
+ }
+
+ /**
+ * Iterate over a list using the Iterable.forEach() method
+ */
+ public void iterateWithForEach() {
+ countries.forEach(System.out::println);
+ }
+
+ /**
+ * Iterate over a list using the Stream.forEach() method
+ */
+ public void iterateWithStreamForEach() {
+ countries.stream().forEach((c) -> System.out.println(c));
+ }
+}
\ No newline at end of file
diff --git a/core-java-collections/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java
new file mode 100644
index 0000000000..973c60b233
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/java/list/WaysToIterateUnitTest.java
@@ -0,0 +1,71 @@
+package com.baeldung.java.list;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ListIterator;
+
+import org.junit.Test;
+
+public class WaysToIterateUnitTest {
+
+ List globalCountries = new ArrayList();
+ List europeanCountries = Arrays.asList("Germany", "Panama", "Australia");
+
+ @Test
+ public void whenIteratingUsingForLoop_thenReturnThreeAsSizeOfList() {
+ for (int i = 0; i < europeanCountries.size(); i++) {
+ globalCountries.add(europeanCountries.get(i));
+ }
+ assertEquals(globalCountries.size(), 3);
+ globalCountries.clear();
+ }
+
+ @Test
+ public void whenIteratingUsingEnhancedForLoop_thenReturnThreeAsSizeOfList() {
+ for (String country : europeanCountries) {
+ globalCountries.add(country);
+ }
+ assertEquals(globalCountries.size(), 3);
+ globalCountries.clear();
+ }
+
+ @Test
+ public void whenIteratingUsingIterator_thenReturnThreeAsSizeOfList() {
+ Iterator countriesIterator = europeanCountries.iterator();
+ while (countriesIterator.hasNext()) {
+ globalCountries.add(countriesIterator.next());
+ }
+
+ assertEquals(globalCountries.size(), 3);
+ globalCountries.clear();
+ }
+
+ @Test
+ public void whenIteratingUsingListIterator_thenReturnThreeAsSizeOfList() {
+ ListIterator countriesIterator = europeanCountries.listIterator();
+ while (countriesIterator.hasNext()) {
+ globalCountries.add(countriesIterator.next());
+ }
+
+ assertEquals(globalCountries.size(), 3);
+ globalCountries.clear();
+ }
+
+ @Test
+ public void whenIteratingUsingForEach_thenReturnThreeAsSizeOfList() {
+ europeanCountries.forEach(country -> globalCountries.add(country));
+ assertEquals(globalCountries.size(), 3);
+ globalCountries.clear();
+ }
+
+ @Test
+ public void whenIteratingUsingStreamForEach_thenReturnThreeAsSizeOfList() {
+ europeanCountries.stream().forEach((country) -> globalCountries.add(country));
+ assertEquals(globalCountries.size(), 3);
+ globalCountries.clear();
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java
similarity index 100%
rename from core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java
diff --git a/core-java/src/test/java/org/baeldung/java/sorting/Employee.java b/core-java-collections/src/test/java/org/baeldung/java/sorting/Employee.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/sorting/Employee.java
rename to core-java-collections/src/test/java/org/baeldung/java/sorting/Employee.java
diff --git a/core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java b/core-java-collections/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java
similarity index 100%
rename from core-java/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java
rename to core-java-collections/src/test/java/org/baeldung/java/sorting/JavaSortingUnitTest.java
diff --git a/core-java-concurrency/README.md b/core-java-concurrency/README.md
index fbe50c2dfa..682c9b8ef0 100644
--- a/core-java-concurrency/README.md
+++ b/core-java-concurrency/README.md
@@ -31,3 +31,4 @@
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)
- [Print Even and Odd Numbers Using 2 Threads](https://www.baeldung.com/java-even-odd-numbers-with-2-threads)
+- [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch)
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java
index b77019eea5..0989195ba7 100644
--- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java
+++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/Scheduledexecutorservice/ScheduledExecutorServiceDemo.java
@@ -1,34 +1,52 @@
package com.baeldung.concurrent.Scheduledexecutorservice;
import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
public class ScheduledExecutorServiceDemo {
- public void execute() {
+ private void execute() {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
-
- ScheduledFuture> scheduledFuture = executorService.schedule(() -> {
- // Task
- }, 1, TimeUnit.SECONDS);
-
- executorService.scheduleAtFixedRate(() -> {
- // Task
- }, 1, 10, TimeUnit.SECONDS);
-
- executorService.scheduleWithFixedDelay(() -> {
- // Task
- }, 1, 10, TimeUnit.SECONDS);
-
- Future future = executorService.schedule(() -> {
- // Task
- return "Hellow world";
- }, 1, TimeUnit.SECONDS);
-
+ getTasksToRun().apply(executorService);
executorService.shutdown();
}
+ private void executeWithMultiThread() {
+ ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
+ getTasksToRun().apply(executorService);
+ executorService.shutdown();
+ }
+
+ private Function getTasksToRun() {
+ return (executorService -> {
+ ScheduledFuture> scheduledFuture1 = executorService.schedule(() -> {
+ // Task
+ }, 1, TimeUnit.SECONDS);
+
+ ScheduledFuture> scheduledFuture2 = executorService.scheduleAtFixedRate(() -> {
+ // Task
+ }, 1, 10, TimeUnit.SECONDS);
+
+ ScheduledFuture> scheduledFuture3 = executorService.scheduleWithFixedDelay(() -> {
+ // Task
+ }, 1, 10, TimeUnit.SECONDS);
+
+ ScheduledFuture scheduledFuture4 = executorService.schedule(() -> {
+ // Task
+ return "Hellow world";
+ }, 1, TimeUnit.SECONDS);
+ return null;
+ });
+ }
+
+ public static void main(String... args) {
+ ScheduledExecutorServiceDemo demo = new ScheduledExecutorServiceDemo();
+ demo.execute();
+ demo.executeWithMultiThread();
+ }
+
+
}
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExample.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExample.java
new file mode 100644
index 0000000000..08c7eeec03
--- /dev/null
+++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExample.java
@@ -0,0 +1,33 @@
+package com.baeldung.concurrent.countdownlatch;
+
+import java.util.concurrent.CountDownLatch;
+
+public class CountdownLatchCountExample {
+
+ private int count;
+
+ public CountdownLatchCountExample(int count) {
+ this.count = count;
+ }
+
+ public boolean callTwiceInSameThread() {
+ CountDownLatch countDownLatch = new CountDownLatch(count);
+ Thread t = new Thread(() -> {
+ countDownLatch.countDown();
+ countDownLatch.countDown();
+ });
+ t.start();
+
+ try {
+ countDownLatch.await();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ return countDownLatch.getCount() == 0;
+ }
+
+ public static void main(String[] args) {
+ CountdownLatchCountExample ex = new CountdownLatchCountExample(2);
+ System.out.println("Is CountDown Completed : " + ex.callTwiceInSameThread());
+ }
+}
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExample.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExample.java
new file mode 100644
index 0000000000..1828b7f91e
--- /dev/null
+++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExample.java
@@ -0,0 +1,41 @@
+package com.baeldung.concurrent.countdownlatch;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class CountdownLatchResetExample {
+
+ private int count;
+ private int threadCount;
+ private final AtomicInteger updateCount;
+
+ CountdownLatchResetExample(int count, int threadCount) {
+ updateCount = new AtomicInteger(0);
+ this.count = count;
+ this.threadCount = threadCount;
+ }
+
+ public int countWaits() {
+ CountDownLatch countDownLatch = new CountDownLatch(count);
+ ExecutorService es = Executors.newFixedThreadPool(threadCount);
+ for (int i = 0; i < threadCount; i++) {
+ es.execute(() -> {
+ long prevValue = countDownLatch.getCount();
+ countDownLatch.countDown();
+ if (countDownLatch.getCount() != prevValue) {
+ updateCount.incrementAndGet();
+ }
+ });
+ }
+
+ es.shutdown();
+ return updateCount.get();
+ }
+
+ public static void main(String[] args) {
+ CountdownLatchResetExample ex = new CountdownLatchResetExample(5, 20);
+ System.out.println("Count : " + ex.countWaits());
+ }
+}
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExample.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExample.java
new file mode 100644
index 0000000000..7c1299da62
--- /dev/null
+++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExample.java
@@ -0,0 +1,45 @@
+package com.baeldung.concurrent.cyclicbarrier;
+
+import java.util.concurrent.BrokenBarrierException;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class CyclicBarrierCompletionMethodExample {
+
+ private int count;
+ private int threadCount;
+ private final AtomicInteger updateCount;
+
+ CyclicBarrierCompletionMethodExample(int count, int threadCount) {
+ updateCount = new AtomicInteger(0);
+ this.count = count;
+ this.threadCount = threadCount;
+ }
+
+ public int countTrips() {
+
+ CyclicBarrier cyclicBarrier = new CyclicBarrier(count, () -> {
+ updateCount.incrementAndGet();
+ });
+
+ ExecutorService es = Executors.newFixedThreadPool(threadCount);
+ for (int i = 0; i < threadCount; i++) {
+ es.execute(() -> {
+ try {
+ cyclicBarrier.await();
+ } catch (InterruptedException | BrokenBarrierException e) {
+ e.printStackTrace();
+ }
+ });
+ }
+ es.shutdown();
+ return updateCount.get();
+ }
+
+ public static void main(String[] args) {
+ CyclicBarrierCompletionMethodExample ex = new CyclicBarrierCompletionMethodExample(5, 20);
+ System.out.println("Count : " + ex.countTrips());
+ }
+}
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExample.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExample.java
new file mode 100644
index 0000000000..9d637b428b
--- /dev/null
+++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExample.java
@@ -0,0 +1,32 @@
+package com.baeldung.concurrent.cyclicbarrier;
+
+import java.util.concurrent.BrokenBarrierException;
+import java.util.concurrent.CyclicBarrier;
+
+public class CyclicBarrierCountExample {
+
+ private int count;
+
+ public CyclicBarrierCountExample(int count) {
+ this.count = count;
+ }
+
+ public boolean callTwiceInSameThread() {
+ CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
+ Thread t = new Thread(() -> {
+ try {
+ cyclicBarrier.await();
+ cyclicBarrier.await();
+ } catch (InterruptedException | BrokenBarrierException e) {
+ e.printStackTrace();
+ }
+ });
+ t.start();
+ return cyclicBarrier.isBroken();
+ }
+
+ public static void main(String[] args) {
+ CyclicBarrierCountExample ex = new CyclicBarrierCountExample(7);
+ System.out.println("Count : " + ex.callTwiceInSameThread());
+ }
+}
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExample.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExample.java
new file mode 100644
index 0000000000..76b6198bc4
--- /dev/null
+++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExample.java
@@ -0,0 +1,46 @@
+package com.baeldung.concurrent.cyclicbarrier;
+
+import java.util.concurrent.BrokenBarrierException;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class CyclicBarrierResetExample {
+
+ private int count;
+ private int threadCount;
+ private final AtomicInteger updateCount;
+
+ CyclicBarrierResetExample(int count, int threadCount) {
+ updateCount = new AtomicInteger(0);
+ this.count = count;
+ this.threadCount = threadCount;
+ }
+
+ public int countWaits() {
+
+ CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
+
+ ExecutorService es = Executors.newFixedThreadPool(threadCount);
+ for (int i = 0; i < threadCount; i++) {
+ es.execute(() -> {
+ try {
+ if (cyclicBarrier.getNumberWaiting() > 0) {
+ updateCount.incrementAndGet();
+ }
+ cyclicBarrier.await();
+ } catch (InterruptedException | BrokenBarrierException e) {
+ e.printStackTrace();
+ }
+ });
+ }
+ es.shutdown();
+ return updateCount.get();
+ }
+
+ public static void main(String[] args) {
+ CyclicBarrierResetExample ex = new CyclicBarrierResetExample(7, 20);
+ System.out.println("Count : " + ex.countWaits());
+ }
+}
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/MultipleThreadsExample.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/MultipleThreadsExample.java
new file mode 100644
index 0000000000..492466e0c3
--- /dev/null
+++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/MultipleThreadsExample.java
@@ -0,0 +1,12 @@
+package com.baeldung.concurrent.daemon;
+
+public class MultipleThreadsExample {
+ public static void main(String[] args) {
+ NewThread t1 = new NewThread();
+ t1.setName("MyThread-1");
+ NewThread t2 = new NewThread();
+ t2.setName("MyThread-2");
+ t1.start();
+ t2.start();
+ }
+}
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java
index 4d87978070..370ce99c09 100644
--- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java
+++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/NewThread.java
@@ -1,14 +1,18 @@
package com.baeldung.concurrent.daemon;
public class NewThread extends Thread {
-
public void run() {
long startTime = System.currentTimeMillis();
while (true) {
for (int i = 0; i < 10; i++) {
- System.out.println("New Thread is running..." + i);
+ System.out.println(this.getName() + ": New Thread is running..." + i);
+ try {
+ //Wait for one sec so it doesn't print too fast
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
}
-
// prevent the Thread to run forever. It will finish it's execution after 2 seconds
if (System.currentTimeMillis() - startTime > 2000) {
Thread.currentThread().interrupt();
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/SingleThreadExample.java b/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/SingleThreadExample.java
new file mode 100644
index 0000000000..16d8b2be1e
--- /dev/null
+++ b/core-java-concurrency/src/main/java/com/baeldung/concurrent/daemon/SingleThreadExample.java
@@ -0,0 +1,8 @@
+package com.baeldung.concurrent.daemon;
+
+public class SingleThreadExample {
+ public static void main(String[] args) {
+ NewThread t = new NewThread();
+ t.start();
+ }
+}
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExampleUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExampleUnitTest.java
new file mode 100644
index 0000000000..835efa53f2
--- /dev/null
+++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchCountExampleUnitTest.java
@@ -0,0 +1,15 @@
+package com.baeldung.concurrent.countdownlatch;
+
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class CountdownLatchCountExampleUnitTest {
+
+ @Test
+ public void whenCountDownLatch_completed() {
+ CountdownLatchCountExample ex = new CountdownLatchCountExample(2);
+ boolean isCompleted = ex.callTwiceInSameThread();
+ assertTrue(isCompleted);
+ }
+}
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExampleUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExampleUnitTest.java
new file mode 100644
index 0000000000..d2d43f6312
--- /dev/null
+++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/countdownlatch/CountdownLatchResetExampleUnitTest.java
@@ -0,0 +1,15 @@
+package com.baeldung.concurrent.countdownlatch;
+
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class CountdownLatchResetExampleUnitTest {
+
+ @Test
+ public void whenCountDownLatch_noReset() {
+ CountdownLatchResetExample ex = new CountdownLatchResetExample(7,20);
+ int lineCount = ex.countWaits();
+ assertTrue(lineCount <= 7);
+ }
+}
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExampleUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExampleUnitTest.java
new file mode 100644
index 0000000000..310063c86c
--- /dev/null
+++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCompletionMethodExampleUnitTest.java
@@ -0,0 +1,15 @@
+package com.baeldung.concurrent.cyclicbarrier;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class CyclicBarrierCompletionMethodExampleUnitTest {
+
+ @Test
+ public void whenCyclicBarrier_countTrips() {
+ CyclicBarrierCompletionMethodExample ex = new CyclicBarrierCompletionMethodExample(7,20);
+ int lineCount = ex.countTrips();
+ assertEquals(2, lineCount);
+ }
+}
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExampleUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExampleUnitTest.java
new file mode 100644
index 0000000000..9b7f3d9945
--- /dev/null
+++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierCountExampleUnitTest.java
@@ -0,0 +1,15 @@
+package com.baeldung.concurrent.cyclicbarrier;
+
+import static org.junit.Assert.assertFalse;
+
+import org.junit.Test;
+
+public class CyclicBarrierCountExampleUnitTest {
+
+ @Test
+ public void whenCyclicBarrier_notCompleted() {
+ CyclicBarrierCountExample ex = new CyclicBarrierCountExample(2);
+ boolean isCompleted = ex.callTwiceInSameThread();
+ assertFalse(isCompleted);
+ }
+}
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExampleUnitTest.java b/core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExampleUnitTest.java
new file mode 100644
index 0000000000..8d2b148f06
--- /dev/null
+++ b/core-java-concurrency/src/test/java/com/baeldung/concurrent/cyclicbarrier/CyclicBarrierResetExampleUnitTest.java
@@ -0,0 +1,15 @@
+package com.baeldung.concurrent.cyclicbarrier;
+
+import static org.junit.Assert.assertTrue;
+
+import org.junit.Test;
+
+public class CyclicBarrierResetExampleUnitTest {
+
+ @Test
+ public void whenCyclicBarrier_reset() {
+ CyclicBarrierResetExample ex = new CyclicBarrierResetExample(7,20);
+ int lineCount = ex.countWaits();
+ assertTrue(lineCount > 7);
+ }
+}
diff --git a/core-java-io/README.md b/core-java-io/README.md
index c81e466b57..3d028783ed 100644
--- a/core-java-io/README.md
+++ b/core-java-io/README.md
@@ -34,3 +34,4 @@
- [Read a File into an ArrayList](https://www.baeldung.com/java-file-to-arraylist)
- [Guide to Java OutputStream](https://www.baeldung.com/java-outputstream)
- [Reading a CSV File into an Array](https://www.baeldung.com/java-csv-file-array)
+- [Guide to BufferedReader](https://www.baeldung.com/java-buffered-reader)
diff --git a/core-java-lang/README.md b/core-java-lang/README.md
index 85312cba68..69209bb193 100644
--- a/core-java-lang/README.md
+++ b/core-java-lang/README.md
@@ -56,4 +56,6 @@
- [How to Separate Double into Integer and Decimal Parts](https://www.baeldung.com/java-separate-double-into-integer-decimal-parts)
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
-
+- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors)
+- [Retrieving a Class Name in Java](https://www.baeldung.com/java-class-name)
+- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
diff --git a/core-java-lang/pom.xml b/core-java-lang/pom.xml
index ace39de274..2f307859f1 100644
--- a/core-java-lang/pom.xml
+++ b/core-java-lang/pom.xml
@@ -66,6 +66,12 @@
mail
${javax.mail.version}
+
+ nl.jqno.equalsverifier
+ equalsverifier
+ ${equalsverifier.version}
+ test
+
@@ -424,6 +430,7 @@
3.1.1
2.0.3.RELEASE
1.6.0
+ 3.0.3
diff --git a/core-java-lang/src/main/java/com/baeldung/className/RetrievingClassName.java b/core-java-lang/src/main/java/com/baeldung/className/RetrievingClassName.java
new file mode 100644
index 0000000000..ab6c8a51ff
--- /dev/null
+++ b/core-java-lang/src/main/java/com/baeldung/className/RetrievingClassName.java
@@ -0,0 +1,9 @@
+package com.baeldung.className;
+
+public class RetrievingClassName {
+
+ public class InnerClass {
+
+ }
+
+}
diff --git a/core-java-lang/src/main/java/com/baeldung/constructors/BankAccount.java b/core-java-lang/src/main/java/com/baeldung/constructors/BankAccount.java
new file mode 100644
index 0000000000..3d50e85245
--- /dev/null
+++ b/core-java-lang/src/main/java/com/baeldung/constructors/BankAccount.java
@@ -0,0 +1,56 @@
+package com.baeldung.constructors;
+
+import java.time.LocalDateTime;
+
+class BankAccount {
+ String name;
+ LocalDateTime opened;
+ double balance;
+
+ @Override
+ public String toString() {
+ return String.format("%s, %s, %f", this.name, this.opened.toString(), this.balance);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public LocalDateTime getOpened() {
+ return opened;
+ }
+
+ public double getBalance() {
+ return this.balance;
+ }
+}
+
+class BankAccountEmptyConstructor extends BankAccount {
+ public BankAccountEmptyConstructor() {
+ this.name = "";
+ this.opened = LocalDateTime.now();
+ this.balance = 0.0d;
+ }
+}
+
+class BankAccountParameterizedConstructor extends BankAccount {
+ public BankAccountParameterizedConstructor(String name, LocalDateTime opened, double balance) {
+ this.name = name;
+ this.opened = opened;
+ this.balance = balance;
+ }
+}
+
+class BankAccountCopyConstructor extends BankAccount {
+ public BankAccountCopyConstructor(String name, LocalDateTime opened, double balance) {
+ this.name = name;
+ this.opened = opened;
+ this.balance = balance;
+ }
+
+ public BankAccountCopyConstructor(BankAccount other) {
+ this.name = other.name;
+ this.opened = LocalDateTime.now();
+ this.balance = 0.0f;
+ }
+}
diff --git a/core-java-lang/src/main/java/com/baeldung/constructors/Transaction.java b/core-java-lang/src/main/java/com/baeldung/constructors/Transaction.java
new file mode 100644
index 0000000000..14704f507a
--- /dev/null
+++ b/core-java-lang/src/main/java/com/baeldung/constructors/Transaction.java
@@ -0,0 +1,25 @@
+package com.baeldung.constructors;
+
+import java.time.LocalDateTime;
+
+class Transaction {
+ final BankAccountEmptyConstructor bankAccount;
+ final LocalDateTime date;
+ final double amount;
+
+ public Transaction(BankAccountEmptyConstructor account, LocalDateTime date, double amount) {
+ this.bankAccount = account;
+ this.date = date;
+ this.amount = amount;
+ }
+
+ /*
+ * Compilation Error :'(, all final variables must be explicitly initialised.
+ * public Transaction() {
+ * }
+ */
+
+ public void invalidMethod() {
+ // this.amount = 102.03; // Results in a compiler error. You cannot change the value of a final variable.
+ }
+}
diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/Money.java b/core-java-lang/src/main/java/com/baeldung/equalshashcode/Money.java
new file mode 100644
index 0000000000..60c043545d
--- /dev/null
+++ b/core-java-lang/src/main/java/com/baeldung/equalshashcode/Money.java
@@ -0,0 +1,36 @@
+package com.baeldung.equalshashcode;
+
+class Money {
+
+ int amount;
+ String currencyCode;
+
+ Money(int amount, String currencyCode) {
+ this.amount = amount;
+ this.currencyCode = currencyCode;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof Money))
+ return false;
+ Money other = (Money)o;
+ boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
+ || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
+ return this.amount == other.amount
+ && currencyCodeEquals;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ result = 31 * result + amount;
+ if (currencyCode != null) {
+ result = 31 * result + currencyCode.hashCode();
+ }
+ return result;
+ }
+
+}
diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/Team.java b/core-java-lang/src/main/java/com/baeldung/equalshashcode/Team.java
new file mode 100644
index 0000000000..c2dee1de6b
--- /dev/null
+++ b/core-java-lang/src/main/java/com/baeldung/equalshashcode/Team.java
@@ -0,0 +1,39 @@
+package com.baeldung.equalshashcode;
+
+class Team {
+
+ final String city;
+ final String department;
+
+ Team(String city, String department) {
+ this.city = city;
+ this.department = department;
+ }
+
+ @Override
+ public final boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof Team))
+ return false;
+ Team otherTeam = (Team)o;
+ boolean cityEquals = (this.city == null && otherTeam.city == null)
+ || this.city != null && this.city.equals(otherTeam.city);
+ boolean departmentEquals = (this.department == null && otherTeam.department == null)
+ || this.department != null && this.department.equals(otherTeam.department);
+ return cityEquals && departmentEquals;
+ }
+
+ @Override
+ public final int hashCode() {
+ int result = 17;
+ if (city != null) {
+ result = 31 * result + city.hashCode();
+ }
+ if (department != null) {
+ result = 31 * result + department.hashCode();
+ }
+ return result;
+ }
+
+}
diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/Voucher.java b/core-java-lang/src/main/java/com/baeldung/equalshashcode/Voucher.java
new file mode 100644
index 0000000000..19f46e0358
--- /dev/null
+++ b/core-java-lang/src/main/java/com/baeldung/equalshashcode/Voucher.java
@@ -0,0 +1,38 @@
+package com.baeldung.equalshashcode;
+
+class Voucher {
+
+ private Money value;
+ private String store;
+
+ Voucher(int amount, String currencyCode, String store) {
+ this.value = new Money(amount, currencyCode);
+ this.store = store;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof Voucher))
+ return false;
+ Voucher other = (Voucher)o;
+ boolean valueEquals = (this.value == null && other.value == null)
+ || (this.value != null && this.value.equals(other.value));
+ boolean storeEquals = (this.store == null && other.store == null)
+ || (this.store != null && this.store.equals(other.store));
+ return valueEquals && storeEquals;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ if (this.value != null) {
+ result = 31 * result + value.hashCode();
+ }
+ if (this.store != null) {
+ result = 31 * result + store.hashCode();
+ }
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/WrongTeam.java b/core-java-lang/src/main/java/com/baeldung/equalshashcode/WrongTeam.java
new file mode 100644
index 0000000000..c4477aa790
--- /dev/null
+++ b/core-java-lang/src/main/java/com/baeldung/equalshashcode/WrongTeam.java
@@ -0,0 +1,30 @@
+package com.baeldung.equalshashcode;
+
+/* (non-Javadoc)
+* This class overrides equals, but it doesn't override hashCode.
+*
+* To see which problems this leads to:
+* TeamUnitTest.givenMapKeyWithoutHashCode_whenSearched_thenReturnsWrongValue
+*/
+class WrongTeam {
+
+ String city;
+ String department;
+
+ WrongTeam(String city, String department) {
+ this.city = city;
+ this.department = department;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof WrongTeam))
+ return false;
+ WrongTeam otherTeam = (WrongTeam)o;
+ return this.city == otherTeam.city
+ && this.department == otherTeam.department;
+ }
+
+}
diff --git a/core-java-lang/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java b/core-java-lang/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java
new file mode 100644
index 0000000000..97935bf8de
--- /dev/null
+++ b/core-java-lang/src/main/java/com/baeldung/equalshashcode/WrongVoucher.java
@@ -0,0 +1,47 @@
+package com.baeldung.equalshashcode;
+
+/* (non-Javadoc)
+* This class extends the Money class that has overridden the equals method and once again overrides the equals method.
+*
+* To see which problems this leads to:
+* MoneyUnitTest.givenMoneyAndVoucherInstances_whenEquals_thenReturnValuesArentSymmetric
+*/
+class WrongVoucher extends Money {
+
+ private String store;
+
+ WrongVoucher(int amount, String currencyCode, String store) {
+ super(amount, currencyCode);
+
+ this.store = store;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == this)
+ return true;
+ if (!(o instanceof WrongVoucher))
+ return false;
+ WrongVoucher other = (WrongVoucher)o;
+ boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
+ || (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
+ boolean storeEquals = (this.store == null && other.store == null)
+ || (this.store != null && this.store.equals(other.store));
+ return this.amount == other.amount
+ && currencyCodeEquals
+ && storeEquals;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = 17;
+ result = 31 * result + amount;
+ if (this.currencyCode != null) {
+ result = 31 * result + currencyCode.hashCode();
+ }
+ if (this.store != null) {
+ result = 31 * result + store.hashCode();
+ }
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/core-java-lang/src/test/java/com/baeldung/className/RetrievingClassNameUnitTest.java b/core-java-lang/src/test/java/com/baeldung/className/RetrievingClassNameUnitTest.java
new file mode 100644
index 0000000000..f9dbf91d2c
--- /dev/null
+++ b/core-java-lang/src/test/java/com/baeldung/className/RetrievingClassNameUnitTest.java
@@ -0,0 +1,156 @@
+package com.baeldung.className;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+public class RetrievingClassNameUnitTest {
+
+ // Retrieving Simple Name
+ @Test
+ public void givenRetrievingClassName_whenGetSimpleName_thenRetrievingClassName() {
+ assertEquals("RetrievingClassName", RetrievingClassName.class.getSimpleName());
+ }
+
+ @Test
+ public void givenPrimitiveInt_whenGetSimpleName_thenInt() {
+ assertEquals("int", int.class.getSimpleName());
+ }
+
+ @Test
+ public void givenRetrievingClassNameArray_whenGetSimpleName_thenRetrievingClassNameWithBrackets() {
+ assertEquals("RetrievingClassName[]", RetrievingClassName[].class.getSimpleName());
+ assertEquals("RetrievingClassName[][]", RetrievingClassName[][].class.getSimpleName());
+ }
+
+ @Test
+ public void givenAnonymousClass_whenGetSimpleName_thenEmptyString() {
+ assertEquals("", new RetrievingClassName() {}.getClass().getSimpleName());
+ }
+
+ // Retrieving Other Names
+ // - Primitive Types
+ @Test
+ public void givenPrimitiveInt_whenGetName_thenInt() {
+ assertEquals("int", int.class.getName());
+ }
+
+ @Test
+ public void givenPrimitiveInt_whenGetTypeName_thenInt() {
+ assertEquals("int", int.class.getTypeName());
+ }
+
+ @Test
+ public void givenPrimitiveInt_whenGetCanonicalName_thenInt() {
+ assertEquals("int", int.class.getCanonicalName());
+ }
+
+ // - Object Types
+ @Test
+ public void givenRetrievingClassName_whenGetName_thenCanonicalName() {
+ assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getName());
+ }
+
+ @Test
+ public void givenRetrievingClassName_whenGetTypeName_thenCanonicalName() {
+ assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getTypeName());
+ }
+
+ @Test
+ public void givenRetrievingClassName_whenGetCanonicalName_thenCanonicalName() {
+ assertEquals("com.baeldung.className.RetrievingClassName", RetrievingClassName.class.getCanonicalName());
+ }
+
+ // - Inner Classes
+ @Test
+ public void givenRetrievingClassNameInnerClass_whenGetName_thenCanonicalNameWithDollarSeparator() {
+ assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getName());
+ }
+
+ @Test
+ public void givenRetrievingClassNameInnerClass_whenGetTypeName_thenCanonicalNameWithDollarSeparator() {
+ assertEquals("com.baeldung.className.RetrievingClassName$InnerClass", RetrievingClassName.InnerClass.class.getTypeName());
+ }
+
+ @Test
+ public void givenRetrievingClassNameInnerClass_whenGetCanonicalName_thenCanonicalName() {
+ assertEquals("com.baeldung.className.RetrievingClassName.InnerClass", RetrievingClassName.InnerClass.class.getCanonicalName());
+ }
+
+ // - Anonymous Classes
+ @Test
+ public void givenAnonymousClass_whenGetName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() {
+ // These are the second and third appearences of an anonymous class in RetrievingClassNameUnitTest, hence $2 and $3 expectations
+ assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$2", new RetrievingClassName() {}.getClass().getName());
+ assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$3", new RetrievingClassName() {}.getClass().getName());
+ }
+
+ @Test
+ public void givenAnonymousClass_whenGetTypeName_thenCallingClassCanonicalNameWithDollarSeparatorAndCountNumber() {
+ // These are the fourth and fifth appearences of an anonymous class in RetrievingClassNameUnitTest, hence $4 and $5 expectations
+ assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$4", new RetrievingClassName() {}.getClass().getTypeName());
+ assertEquals("com.baeldung.className.RetrievingClassNameUnitTest$5", new RetrievingClassName() {}.getClass().getTypeName());
+ }
+
+ @Test
+ public void givenAnonymousClass_whenGetCanonicalName_thenNull() {
+ assertNull(new RetrievingClassName() {}.getClass().getCanonicalName());
+ }
+
+ // - Arrays
+ @Test
+ public void givenPrimitiveIntArray_whenGetName_thenOpeningBracketsAndPrimitiveIntLetter() {
+ assertEquals("[I", int[].class.getName());
+ assertEquals("[[I", int[][].class.getName());
+ }
+
+ @Test
+ public void givenRetrievingClassNameArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameGetName() {
+ assertEquals("[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[].class.getName());
+ assertEquals("[[Lcom.baeldung.className.RetrievingClassName;", RetrievingClassName[][].class.getName());
+ }
+
+ @Test
+ public void givenRetrievingClassNameInnerClassArray_whenGetName_thenOpeningBracketsLetterLAndRetrievingClassNameInnerClassGetName() {
+ assertEquals("[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[].class.getName());
+ assertEquals("[[Lcom.baeldung.className.RetrievingClassName$InnerClass;", RetrievingClassName.InnerClass[][].class.getName());
+ }
+
+ @Test
+ public void givenPrimitiveIntArray_whenGetTypeName_thenPrimitiveIntGetTypeNameWithBrackets() {
+ assertEquals("int[]", int[].class.getTypeName());
+ assertEquals("int[][]", int[][].class.getTypeName());
+ }
+
+ @Test
+ public void givenRetrievingClassNameArray_whenGetTypeName_thenRetrievingClassNameGetTypeNameWithBrackets() {
+ assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getTypeName());
+ assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getTypeName());
+ }
+
+ @Test
+ public void givenRetrievingClassNameInnerClassArray_whenGetTypeName_thenRetrievingClassNameInnerClassGetTypeNameWithBrackets() {
+ assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[]", RetrievingClassName.InnerClass[].class.getTypeName());
+ assertEquals("com.baeldung.className.RetrievingClassName$InnerClass[][]", RetrievingClassName.InnerClass[][].class.getTypeName());
+ }
+
+ @Test
+ public void givenPrimitiveIntArray_whenGetCanonicalName_thenPrimitiveIntGetCanonicalNameWithBrackets() {
+ assertEquals("int[]", int[].class.getCanonicalName());
+ assertEquals("int[][]", int[][].class.getCanonicalName());
+ }
+
+ @Test
+ public void givenRetrievingClassNameArray_whenGetCanonicalName_thenRetrievingClassNameGetCanonicalNameWithBrackets() {
+ assertEquals("com.baeldung.className.RetrievingClassName[]", RetrievingClassName[].class.getCanonicalName());
+ assertEquals("com.baeldung.className.RetrievingClassName[][]", RetrievingClassName[][].class.getCanonicalName());
+ }
+
+ @Test
+ public void givenRetrievingClassNameInnerClassArray_whenGetCanonicalName_thenRetrievingClassNameInnerClassGetCanonicalNameWithBrackets() {
+ assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[]", RetrievingClassName.InnerClass[].class.getCanonicalName());
+ assertEquals("com.baeldung.className.RetrievingClassName.InnerClass[][]", RetrievingClassName.InnerClass[][].class.getCanonicalName());
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-lang/src/test/java/com/baeldung/compoundoperators/CompoundOperatorsUnitTest.java b/core-java-lang/src/test/java/com/baeldung/compoundoperators/CompoundOperatorsUnitTest.java
new file mode 100644
index 0000000000..532776edd4
--- /dev/null
+++ b/core-java-lang/src/test/java/com/baeldung/compoundoperators/CompoundOperatorsUnitTest.java
@@ -0,0 +1,111 @@
+package com.baeldung.compoundoperators;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class CompoundOperatorsUnitTest {
+
+ @Test
+ public void whenAssignmentOperatorIsUsed_thenValueIsAssigned() {
+ int x = 5;
+
+ assertEquals(5, x);
+ }
+
+ @Test
+ public void whenCompoundAssignmentUsed_thenSameAsSimpleAssignment() {
+ int a = 3, b = 3, c = -2;
+ a = a * c; // Simple assignment operator
+ b *= c; // Compound assignment operator
+
+ assertEquals(a, b);
+ }
+
+ @Test
+ public void whenAssignmentOperatorIsUsed_thenValueIsReturned() {
+ long x = 1;
+ long y = (x+=2);
+
+ assertEquals(3, y);
+ assertEquals(y, x);
+ }
+
+ @Test
+ public void whenCompoundOperatorsAreUsed_thenOperationsArePerformedAndAssigned() {
+ //Simple assignment
+ int x = 5; //x is 5
+
+ //Incrementation
+ x += 5; //x is 10
+ assertEquals(10, x);
+
+ //Decrementation
+ x -= 2; //x is 8
+ assertEquals(8, x);
+
+ //Multiplication
+ x *= 2; //x is 16
+ assertEquals(16, x);
+
+ //Division
+ x /= 4; //x is 4
+ assertEquals(4, x);
+
+ //Modulus
+ x %= 3; //x is 1
+ assertEquals(1, x);
+
+
+ //Binary AND
+ x &= 4; //x is 0
+ assertEquals(0, x);
+
+ //Binary exclusive OR
+ x ^= 4; //x is 4
+ assertEquals(4, x);
+
+ //Binary inclusive OR
+ x |= 8; //x is 12
+ assertEquals(12, x);
+
+
+ //Binary Left Shift
+ x <<= 2; //x is 48
+ assertEquals(48, x);
+
+ //Binary Right Shift
+ x >>= 2; //x is 12
+ assertEquals(12, x);
+
+ //Shift right zero fill
+ x >>>= 1; //x is 6
+ assertEquals(6, x);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void whenArrayIsNull_thenThrowNullException() {
+ int[] numbers = null;
+
+ //Trying Incrementation
+ numbers[2] += 5;
+ }
+
+ @Test(expected = ArrayIndexOutOfBoundsException.class)
+ public void whenArrayIndexNotCorrect_thenThrowArrayIndexException() {
+ int[] numbers = {0, 1};
+
+ //Trying Incrementation
+ numbers[2] += 5;
+ }
+
+ @Test
+ public void whenArrayIndexIsCorrect_thenPerformOperation() {
+ int[] numbers = {0, 1};
+
+ //Incrementation
+ numbers[1] += 5;
+ assertEquals(6, numbers[1]);
+ }
+
+}
diff --git a/core-java-lang/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java b/core-java-lang/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java
new file mode 100644
index 0000000000..2cd8832fbf
--- /dev/null
+++ b/core-java-lang/src/test/java/com/baeldung/constructors/ConstructorUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.constructors;
+
+import com.baeldung.constructors.*;
+
+import java.util.logging.Logger;
+import java.time.LocalDateTime;
+import java.time.Month;
+
+import org.junit.Test;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+public class ConstructorUnitTest {
+ final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
+
+ @Test
+ public void givenNoExplicitContructor_whenUsed_thenFails() {
+ BankAccount account = new BankAccount();
+ assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class);
+ }
+
+ @Test
+ public void givenNoArgumentConstructor_whenUsed_thenSucceeds() {
+ BankAccountEmptyConstructor account = new BankAccountEmptyConstructor();
+ assertThatCode(() -> {
+ account.toString();
+ }).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void givenParameterisedConstructor_whenUsed_thenSucceeds() {
+ LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
+ BankAccountParameterizedConstructor account =
+ new BankAccountParameterizedConstructor("Tom", opened, 1000.0f);
+
+ assertThatCode(() -> {
+ account.toString();
+ }).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void givenCopyContructor_whenUser_thenMaintainsLogic() {
+ LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
+ BankAccountCopyConstructor account = new BankAccountCopyConstructor("Tim", opened, 1000.0f);
+ BankAccountCopyConstructor newAccount = new BankAccountCopyConstructor(account);
+
+ assertThat(account.getName()).isEqualTo(newAccount.getName());
+ assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened());
+
+ assertThat(newAccount.getBalance()).isEqualTo(0.0f);
+ }
+}
diff --git a/core-java-lang/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java b/core-java-lang/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java
new file mode 100644
index 0000000000..60584fdb53
--- /dev/null
+++ b/core-java-lang/src/test/java/com/baeldung/equalshashcode/MoneyUnitTest.java
@@ -0,0 +1,27 @@
+package com.baeldung.equalshashcode;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+
+import org.junit.Test;
+
+public class MoneyUnitTest {
+
+ @Test
+ public void givenMoneyInstancesWithSameAmountAndCurrency_whenEquals_thenReturnsTrue() {
+ Money income = new Money(55, "USD");
+ Money expenses = new Money(55, "USD");
+
+ assertTrue(income.equals(expenses));
+ }
+
+ @Test
+ public void givenMoneyAndVoucherInstances_whenEquals_thenReturnValuesArentSymmetric() {
+ Money cash = new Money(42, "USD");
+ WrongVoucher voucher = new WrongVoucher(42, "USD", "Amazon");
+
+ assertFalse(voucher.equals(cash));
+ assertTrue(cash.equals(voucher));
+ }
+
+}
diff --git a/core-java-lang/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java b/core-java-lang/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java
new file mode 100644
index 0000000000..a2de408796
--- /dev/null
+++ b/core-java-lang/src/test/java/com/baeldung/equalshashcode/TeamUnitTest.java
@@ -0,0 +1,46 @@
+package com.baeldung.equalshashcode;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.Test;
+
+import nl.jqno.equalsverifier.EqualsVerifier;
+
+public class TeamUnitTest {
+
+ @Test
+ public void givenMapKeyWithHashCode_whenSearched_thenReturnsCorrectValue() {
+ Map leaders = new HashMap<>();
+ leaders.put(new Team("New York", "development"), "Anne");
+ leaders.put(new Team("Boston", "development"), "Brian");
+ leaders.put(new Team("Boston", "marketing"), "Charlie");
+
+ Team myTeam = new Team("New York", "development");
+ String myTeamleader = leaders.get(myTeam);
+
+ assertEquals("Anne", myTeamleader);
+ }
+
+ @Test
+ public void givenMapKeyWithoutHashCode_whenSearched_thenReturnsWrongValue() {
+ Map leaders = new HashMap<>();
+ leaders.put(new WrongTeam("New York", "development"), "Anne");
+ leaders.put(new WrongTeam("Boston", "development"), "Brian");
+ leaders.put(new WrongTeam("Boston", "marketing"), "Charlie");
+
+ WrongTeam myTeam = new WrongTeam("New York", "development");
+ String myTeamleader = leaders.get(myTeam);
+
+ assertFalse("Anne".equals(myTeamleader));
+ }
+
+ @Test
+ public void equalsContract() {
+ EqualsVerifier.forClass(Team.class).verify();
+ }
+
+}
diff --git a/core-java-networking/.gitignore b/core-java-networking/.gitignore
new file mode 100644
index 0000000000..374c8bf907
--- /dev/null
+++ b/core-java-networking/.gitignore
@@ -0,0 +1,25 @@
+*.class
+
+0.*
+
+#folders#
+/target
+/neoDb*
+/data
+/src/main/webapp/WEB-INF/classes
+*/META-INF/*
+.resourceCache
+
+# Packaged files #
+*.jar
+*.war
+*.ear
+
+# Files generated by integration tests
+backup-pom.xml
+/bin/
+/temp
+
+#IntelliJ specific
+.idea/
+*.iml
\ No newline at end of file
diff --git a/core-java-networking/README.md b/core-java-networking/README.md
new file mode 100644
index 0000000000..626ea794e6
--- /dev/null
+++ b/core-java-networking/README.md
@@ -0,0 +1,7 @@
+=========
+
+## Core Java Networking
+
+### Relevant Articles
+
+- [Connecting Through Proxy Servers in Core Java](https://www.baeldung.com/java-connect-via-proxy-server)
diff --git a/core-java-networking/pom.xml b/core-java-networking/pom.xml
new file mode 100644
index 0000000000..178295e1ec
--- /dev/null
+++ b/core-java-networking/pom.xml
@@ -0,0 +1,19 @@
+
+ 4.0.0
+ core-java-networking
+ 0.1.0-SNAPSHOT
+ jar
+ core-java-networking
+
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-java
+
+
+
+ core-java-networking
+
+
diff --git a/core-java-networking/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java
new file mode 100644
index 0000000000..bbc8a81c98
--- /dev/null
+++ b/core-java-networking/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java
@@ -0,0 +1,17 @@
+package com.baeldung.networking.proxies;
+
+import java.net.URL;
+import java.net.URLConnection;
+
+public class CommandLineProxyDemo {
+
+ public static final String RESOURCE_URL = "http://www.google.com";
+
+ public static void main(String[] args) throws Exception {
+
+ URL url = new URL(RESOURCE_URL);
+ URLConnection con = url.openConnection();
+ System.out.println(UrlConnectionUtils.contentAsString(con));
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-networking/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java
new file mode 100644
index 0000000000..07a7880886
--- /dev/null
+++ b/core-java-networking/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java
@@ -0,0 +1,20 @@
+package com.baeldung.networking.proxies;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.Proxy;
+import java.net.URL;
+
+public class DirectProxyDemo {
+
+ private static final String URL_STRING = "http://www.google.com";
+
+ public static void main(String... args) throws IOException {
+
+ URL weburl = new URL(URL_STRING);
+ HttpURLConnection directConnection
+ = (HttpURLConnection) weburl.openConnection(Proxy.NO_PROXY);
+ System.out.println(UrlConnectionUtils.contentAsString(directConnection));
+ }
+
+}
diff --git a/core-java-networking/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java
new file mode 100644
index 0000000000..e7ac3c0264
--- /dev/null
+++ b/core-java-networking/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java
@@ -0,0 +1,32 @@
+package com.baeldung.networking.proxies;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.Socket;
+import java.net.URL;
+
+public class SocksProxyDemo {
+
+ private static final String URL_STRING = "http://www.google.com";
+ private static final String SOCKET_SERVER_HOST = "someserver.baeldung.com";
+ private static final int SOCKET_SERVER_PORT = 1111;
+
+ public static void main(String... args) throws IOException {
+
+ URL weburl = new URL(URL_STRING);
+ Proxy socksProxy
+ = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 1080));
+ HttpURLConnection socksConnection
+ = (HttpURLConnection) weburl.openConnection(socksProxy);
+ System.out.println(UrlConnectionUtils.contentAsString(socksConnection));
+
+ Socket proxySocket = new Socket(socksProxy);
+ InetSocketAddress socketHost
+ = new InetSocketAddress(SOCKET_SERVER_HOST, SOCKET_SERVER_PORT);
+ proxySocket.connect(socketHost);
+ // do stuff with the socket
+ }
+
+}
diff --git a/core-java-networking/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java
new file mode 100644
index 0000000000..1f589eac58
--- /dev/null
+++ b/core-java-networking/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java
@@ -0,0 +1,23 @@
+package com.baeldung.networking.proxies;
+
+import java.net.URL;
+import java.net.URLConnection;
+
+public class SystemPropertyProxyDemo {
+
+ public static final String RESOURCE_URL = "http://www.google.com";
+
+ public static void main(String[] args) throws Exception {
+
+ System.setProperty("http.proxyHost", "127.0.0.1");
+ System.setProperty("http.proxyPort", "3128");
+
+ URL url = new URL(RESOURCE_URL);
+ URLConnection con = url.openConnection();
+ System.out.println(UrlConnectionUtils.contentAsString(con));
+
+ System.setProperty("http.proxyHost", null);
+ // proxy will no longer be used for http connections
+ }
+
+}
diff --git a/core-java-networking/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java
new file mode 100644
index 0000000000..aa12824a90
--- /dev/null
+++ b/core-java-networking/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java
@@ -0,0 +1,21 @@
+package com.baeldung.networking.proxies;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.URLConnection;
+
+class UrlConnectionUtils {
+
+ public static String contentAsString(URLConnection con) throws IOException {
+ StringBuilder builder = new StringBuilder();
+ try (BufferedReader reader
+ = new BufferedReader(new InputStreamReader(con.getInputStream()))){
+ while (reader.ready()) {
+ builder.append(reader.readLine());
+ }
+ }
+ return builder.toString();
+ }
+
+}
diff --git a/core-java-networking/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java b/core-java-networking/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java
new file mode 100644
index 0000000000..41caaf3439
--- /dev/null
+++ b/core-java-networking/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java
@@ -0,0 +1,23 @@
+package com.baeldung.networking.proxies;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.URL;
+
+public class WebProxyDemo {
+
+ private static final String URL_STRING = "http://www.google.com";
+
+ public static void main(String... args) throws IOException {
+
+ URL weburl = new URL(URL_STRING);
+ Proxy webProxy
+ = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128));
+ HttpURLConnection webProxyConnection
+ = (HttpURLConnection) weburl.openConnection(webProxy);
+ System.out.println(UrlConnectionUtils.contentAsString(webProxyConnection));
+ }
+
+}
diff --git a/core-java-networking/src/test/resources/.gitignore b/core-java-networking/src/test/resources/.gitignore
new file mode 100644
index 0000000000..83c05e60c8
--- /dev/null
+++ b/core-java-networking/src/test/resources/.gitignore
@@ -0,0 +1,13 @@
+*.class
+
+#folders#
+/target
+/neoDb*
+/data
+/src/main/webapp/WEB-INF/classes
+*/META-INF/*
+
+# Packaged files #
+*.jar
+*.war
+*.ear
\ No newline at end of file
diff --git a/core-java/README.md b/core-java/README.md
index 2be137add6..20f6ef5ea7 100644
--- a/core-java/README.md
+++ b/core-java/README.md
@@ -10,7 +10,6 @@
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
- [How to Print Screen in Java](http://www.baeldung.com/print-screen-in-java)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
-- [Sorting in Java](http://www.baeldung.com/java-sorting)
- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
- [Pattern Search with Grep in Java](http://www.baeldung.com/grep-in-java)
- [URL Encoding and Decoding in Java](http://www.baeldung.com/java-url-encoding-decoding)
@@ -39,7 +38,6 @@
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class)
-- [Implementing a Binary Tree in Java](http://www.baeldung.com/java-binary-tree)
- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
@@ -49,15 +47,10 @@
- [A Practical Guide to DecimalFormat](http://www.baeldung.com/java-decimalformat)
- [How to Detect the OS Using Java](http://www.baeldung.com/java-detect-os)
- [ASCII Art in Java](http://www.baeldung.com/ascii-art-in-java)
-- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [What is the serialVersionUID?](http://www.baeldung.com/java-serial-version-uid)
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
-- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
- [Class Loaders in Java](http://www.baeldung.com/java-classloaders)
-- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
-- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
-- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Sending Emails with Java](http://www.baeldung.com/java-email)
- [Introduction to SSL in Java](http://www.baeldung.com/java-ssl)
- [Java KeyStore API](http://www.baeldung.com/java-keystore)
@@ -80,8 +73,6 @@
- [Getting a File’s Mime Type in Java](http://www.baeldung.com/java-file-mime-type)
- [Common Java Exceptions](http://www.baeldung.com/java-common-exceptions)
- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods)
-- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
-- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [Throw Exception in Optional in Java 8](https://www.baeldung.com/java-optional-throw-exception)
- [Add a Character to a String at a Given Position](https://www.baeldung.com/java-add-character-to-string)
- [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root)
@@ -93,3 +84,11 @@
- [Understanding Memory Leaks in Java](https://www.baeldung.com/java-memory-leaks)
- [A Guide to SimpleDateFormat](https://www.baeldung.com/java-simple-date-format)
- [SSL Handshake Failures](https://www.baeldung.com/java-ssl-handshake-failures)
+- [Implementing a Binary Tree in Java](https://www.baeldung.com/java-binary-tree)
+- [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order)
+- [Java – Try with Resources](https://www.baeldung.com/java-try-with-resources)
+- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)
+- [Guide to Character Encoding](https://www.baeldung.com/java-char-encoding)
+- [Calculate the Area of a Circle in Java](https://www.baeldung.com/java-calculate-circle-area)
+- [A Guide to the Java Math Class](https://www.baeldung.com/java-lang-math)
+- [Graphs in Java](https://www.baeldung.com/java-graphs)
diff --git a/core-java/pom.xml b/core-java/pom.xml
index 9fbc8f6810..64345ab14c 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -3,8 +3,8 @@
4.0.0
core-java
0.1.0-SNAPSHOT
- jar
core-java
+ jar
com.baeldung
diff --git a/core-java/src/main/java/com/baeldung/abstractclasses/application/Application.java b/core-java/src/main/java/com/baeldung/abstractclasses/application/Application.java
index fe30c66484..3180762227 100644
--- a/core-java/src/main/java/com/baeldung/abstractclasses/application/Application.java
+++ b/core-java/src/main/java/com/baeldung/abstractclasses/application/Application.java
@@ -2,29 +2,28 @@ package com.baeldung.abstractclasses.application;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
-import com.baeldung.abstractclasses.filereaders.StandardFileReader;
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
public class Application {
- public static void main(String[] args) throws IOException {
-
+ public static void main(String[] args) throws IOException, URISyntaxException {
+
Application application = new Application();
- String filePath = application.getFilePathFromResourcesFolder("files/test.txt");
-
- BaseFileReader lowercaseFileReader = new LowercaseFileReader(filePath);
+ Path path = application.getPathFromResourcesFile("files/test.txt");
+ BaseFileReader lowercaseFileReader = new LowercaseFileReader(path);
lowercaseFileReader.readFile().forEach(line -> System.out.println(line));
+
+ BaseFileReader uppercaseFileReader = new UppercaseFileReader(path);
+ uppercaseFileReader.readFile().forEach(line -> System.out.println(line));
- BaseFileReader upperCaseFileReader = new UppercaseFileReader(filePath);
- upperCaseFileReader.readFile().forEach(line -> System.out.println(line));
-
- BaseFileReader standardFileReader = new StandardFileReader(filePath);
- standardFileReader.readFile().forEach(line -> System.out.println(line));
-
}
- private String getFilePathFromResourcesFolder(String fileName) {
- return getClass().getClassLoader().getResource(fileName).getPath().substring(1);
+ private Path getPathFromResourcesFile(String filePath) throws URISyntaxException {
+ return Paths.get(getClass().getClassLoader().getResource(filePath).toURI());
+
}
}
diff --git a/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/BaseFileReader.java b/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/BaseFileReader.java
index 659913f046..97452a9eca 100644
--- a/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/BaseFileReader.java
+++ b/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/BaseFileReader.java
@@ -1,19 +1,27 @@
package com.baeldung.abstractclasses.filereaders;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.List;
+import java.util.stream.Collectors;
public abstract class BaseFileReader {
- protected String filePath;
+ protected Path filePath;
- protected BaseFileReader(String filePath) {
+ protected BaseFileReader(Path filePath) {
this.filePath = filePath;
}
- public String getFilePath() {
+ public Path getFilePath() {
return filePath;
}
- public abstract List readFile() throws IOException;
+ public List readFile() throws IOException {
+ return Files.lines(filePath)
+ .map(this::mapFileLine).collect(Collectors.toList());
+ }
+
+ protected abstract String mapFileLine(String line);
}
diff --git a/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/LowercaseFileReader.java b/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/LowercaseFileReader.java
index 0bbef45eb8..53820d393c 100644
--- a/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/LowercaseFileReader.java
+++ b/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/LowercaseFileReader.java
@@ -1,21 +1,15 @@
package com.baeldung.abstractclasses.filereaders;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.stream.Collectors;
+import java.nio.file.Path;
public class LowercaseFileReader extends BaseFileReader {
- public LowercaseFileReader(String filePath) {
+ public LowercaseFileReader(Path filePath) {
super(filePath);
}
-
+
@Override
- public List readFile() throws IOException {
- return Files.lines(Paths.get(filePath))
- .map(String::toLowerCase)
- .collect(Collectors.toList());
- }
+ public String mapFileLine(String line) {
+ return line.toLowerCase();
+ }
}
diff --git a/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/StandardFileReader.java b/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/StandardFileReader.java
deleted file mode 100644
index 0a90d53c38..0000000000
--- a/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/StandardFileReader.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.baeldung.abstractclasses.filereaders;
-
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.stream.Collectors;
-
-public class StandardFileReader extends BaseFileReader {
-
- public StandardFileReader(String filePath) {
- super(filePath);
- }
-
- @Override
- public List readFile() throws IOException {
- return Files.lines(Paths.get(filePath)).collect(Collectors.toList());
- }
-}
diff --git a/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/UppercaseFileReader.java b/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/UppercaseFileReader.java
index 4e8f150964..3144a4f27f 100644
--- a/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/UppercaseFileReader.java
+++ b/core-java/src/main/java/com/baeldung/abstractclasses/filereaders/UppercaseFileReader.java
@@ -1,21 +1,15 @@
package com.baeldung.abstractclasses.filereaders;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
-import java.util.List;
-import java.util.stream.Collectors;
+import java.nio.file.Path;
public class UppercaseFileReader extends BaseFileReader {
-
- public UppercaseFileReader(String filePath) {
+
+ public UppercaseFileReader(Path filePath) {
super(filePath);
}
-
+
@Override
- public List readFile() throws IOException {
- return Files.lines(Paths.get(filePath))
- .map(String::toUpperCase)
- .collect(Collectors.toList());
+ public String mapFileLine(String line) {
+ return line.toUpperCase();
}
}
diff --git a/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java b/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java
new file mode 100644
index 0000000000..20a13178cc
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/basicsyntax/SimpleAddition.java
@@ -0,0 +1,11 @@
+package com.baeldung.basicsyntax;
+
+public class SimpleAddition {
+
+ public static void main(String[] args) {
+ int a = 10;
+ int b = 5;
+ double c = a + b;
+ System.out.println( a + " + " + b + " = " + c);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/graph/Graph.java b/core-java/src/main/java/com/baeldung/graph/Graph.java
new file mode 100644
index 0000000000..43b5c0aa08
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/graph/Graph.java
@@ -0,0 +1,76 @@
+package com.baeldung.graph;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+public class Graph {
+ private Map> adjVertices;
+
+ Graph() {
+ this.adjVertices = new HashMap>();
+ }
+
+ void addVertex(String label) {
+ adjVertices.putIfAbsent(new Vertex(label), new ArrayList<>());
+ }
+
+ void removeVertex(String label) {
+ Vertex v = new Vertex(label);
+ adjVertices.values().stream().map(e -> e.remove(v)).collect(Collectors.toList());
+ adjVertices.remove(new Vertex(label));
+ }
+
+ void addEdge(String label1, String label2) {
+ Vertex v1 = new Vertex(label1);
+ Vertex v2 = new Vertex(label2);
+ adjVertices.get(v1).add(v2);
+ adjVertices.get(v2).add(v1);
+ }
+
+ void removeEdge(String label1, String label2) {
+ Vertex v1 = new Vertex(label1);
+ Vertex v2 = new Vertex(label2);
+ List eV1 = adjVertices.get(v1);
+ List eV2 = adjVertices.get(v2);
+ if (eV1 != null)
+ eV1.remove(v2);
+ if (eV2 != null)
+ eV2.remove(v1);
+ }
+
+ List getAdjVertices(String label) {
+ return adjVertices.get(new Vertex(label));
+ }
+
+ String printGraph() {
+ StringBuffer sb = new StringBuffer();
+ for(Vertex v : adjVertices.keySet()) {
+ sb.append(v);
+ sb.append(adjVertices.get(v));
+ }
+ return sb.toString();
+ }
+
+ class Vertex {
+ String label;
+ Vertex(String label) {
+ this.label = label;
+ }
+ @Override
+ public boolean equals(Object obj) {
+ Vertex vertex = (Vertex) obj;
+ return vertex.label == label;
+ }
+ @Override
+ public int hashCode() {
+ return label.hashCode();
+ }
+ @Override
+ public String toString() {
+ return label;
+ }
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/graph/GraphTraversal.java b/core-java/src/main/java/com/baeldung/graph/GraphTraversal.java
new file mode 100644
index 0000000000..479e653a5c
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/graph/GraphTraversal.java
@@ -0,0 +1,44 @@
+package com.baeldung.graph;
+
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.Queue;
+import java.util.Set;
+import java.util.Stack;
+
+import com.baeldung.graph.Graph.Vertex;
+
+public class GraphTraversal {
+ static Set depthFirstTraversal(Graph graph, String root) {
+ Set visited = new LinkedHashSet();
+ Stack stack = new Stack();
+ stack.push(root);
+ while (!stack.isEmpty()) {
+ String vertex = stack.pop();
+ if (!visited.contains(vertex)) {
+ visited.add(vertex);
+ for (Vertex v : graph.getAdjVertices(vertex)) {
+ stack.push(v.label);
+ }
+ }
+ }
+ return visited;
+ }
+
+ static Set breadthFirstTraversal(Graph graph, String root) {
+ Set visited = new LinkedHashSet();
+ Queue queue = new LinkedList();
+ queue.add(root);
+ visited.add(root);
+ while (!queue.isEmpty()) {
+ String vertex = queue.poll();
+ for (Vertex v : graph.getAdjVertices(vertex)) {
+ if (!visited.contains(v.label)) {
+ visited.add(v.label);
+ queue.add(v.label);
+ }
+ }
+ }
+ return visited;
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/printf/PrintfExamples.java b/core-java/src/main/java/com/baeldung/printf/PrintfExamples.java
new file mode 100644
index 0000000000..3d451f6f50
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/printf/PrintfExamples.java
@@ -0,0 +1,61 @@
+package com.baeldung.printf;
+
+import java.util.Date;
+import java.util.Locale;
+
+public class PrintfExamples {
+
+ public static void main(String[] args) {
+
+ printfNewLine();
+ printfChar();
+ printfString();
+ printfNumber();
+ printfDateTime();
+ printfBoolean();
+ }
+
+ private static void printfNewLine() {
+ System.out.printf("baeldung%nline%nterminator");
+ }
+
+ private static void printfString() {
+ System.out.printf("'%s' %n", "baeldung");
+ System.out.printf("'%S' %n", "baeldung");
+ System.out.printf("'%15s' %n", "baeldung");
+ System.out.printf("'%-10s' %n", "baeldung");
+ }
+
+ private static void printfChar() {
+ System.out.printf("%c%n", 's');
+ System.out.printf("%C%n", 's');
+ }
+
+ private static void printfNumber() {
+ System.out.printf("simple integer: %d%n", 10000L);
+
+ System.out.printf(Locale.US, "%,d %n", 10000);
+ System.out.printf(Locale.ITALY, "%,d %n", 10000);
+
+ System.out.printf("%f%n", 5.1473);
+ System.out.printf("'%5.2f'%n", 5.1473);
+ System.out.printf("'%5.2e'%n", 5.1473);
+ }
+
+ private static void printfBoolean() {
+ System.out.printf("%b%n", null);
+ System.out.printf("%B%n", false);
+ System.out.printf("%B%n", 5.3);
+ System.out.printf("%b%n", "random text");
+ }
+
+ private static void printfDateTime() {
+ Date date = new Date();
+ System.out.printf("%tT%n", date);
+ System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);
+ System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);
+
+ System.out.printf("%1$tA %1$tB %1$tY %n", date);
+ System.out.printf("%1$td.%1$tm.%1$ty %n", date);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/abstractclasses/StandardFileReaderUnitTest.java b/core-java/src/test/java/com/baeldung/abstractclasses/StandardFileReaderUnitTest.java
deleted file mode 100644
index 348b0f0366..0000000000
--- a/core-java/src/test/java/com/baeldung/abstractclasses/StandardFileReaderUnitTest.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.baeldung.abstractclasses;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-import java.net.URL;
-import java.nio.file.Paths;
-import java.util.List;
-
-import org.junit.Test;
-
-import com.baeldung.abstractclasses.filereaders.BaseFileReader;
-import com.baeldung.abstractclasses.filereaders.StandardFileReader;
-
-public class StandardFileReaderUnitTest {
-
- @Test
- public void givenStandardFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
- // We'll transform the resource URL path to URI to load the file correctly in Windows
- URL url = getClass().getClassLoader().getResource("files/test.txt");
- String filePath = Paths.get(url.toURI()).toString();
- BaseFileReader standardFileReader = new StandardFileReader(filePath);
-
- assertThat(standardFileReader.readFile()).isInstanceOf(List.class);
- }
-}
diff --git a/core-java/src/test/java/com/baeldung/abstractclasses/LowercaseFileReaderUnitTest.java b/core-java/src/test/java/com/baeldung/abstractclasses/test/LowercaseFileReaderUnitTest.java
similarity index 63%
rename from core-java/src/test/java/com/baeldung/abstractclasses/LowercaseFileReaderUnitTest.java
rename to core-java/src/test/java/com/baeldung/abstractclasses/test/LowercaseFileReaderUnitTest.java
index a97a68e0bd..4f0d3a7cd5 100644
--- a/core-java/src/test/java/com/baeldung/abstractclasses/LowercaseFileReaderUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/abstractclasses/test/LowercaseFileReaderUnitTest.java
@@ -1,23 +1,20 @@
-package com.baeldung.abstractclasses;
+package com.baeldung.abstractclasses.test;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
-
-import java.net.URL;
+import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class LowercaseFileReaderUnitTest {
-
+
@Test
public void givenLowercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
- // We'll transform the resource URL path to URI to load the file correctly in Windows
- URL url = getClass().getClassLoader().getResource("files/test.txt");
- String filePath = Paths.get(url.toURI()).toString();
- BaseFileReader lowercaseFileReader = new LowercaseFileReader(filePath);
-
+ Path path = Paths.get(getClass().getClassLoader().getResource("files/test.txt").toURI());
+ BaseFileReader lowercaseFileReader = new LowercaseFileReader(path);
+
assertThat(lowercaseFileReader.readFile()).isInstanceOf(List.class);
}
}
diff --git a/core-java/src/test/java/com/baeldung/abstractclasses/UppercaseFileReaderUnitTest.java b/core-java/src/test/java/com/baeldung/abstractclasses/test/UppercaseFileReaderUnitTest.java
similarity index 62%
rename from core-java/src/test/java/com/baeldung/abstractclasses/UppercaseFileReaderUnitTest.java
rename to core-java/src/test/java/com/baeldung/abstractclasses/test/UppercaseFileReaderUnitTest.java
index d698cfe038..e11db57000 100644
--- a/core-java/src/test/java/com/baeldung/abstractclasses/UppercaseFileReaderUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/abstractclasses/test/UppercaseFileReaderUnitTest.java
@@ -1,9 +1,8 @@
-package com.baeldung.abstractclasses;
+package com.baeldung.abstractclasses.test;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
-
-import java.net.URL;
+import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@@ -13,11 +12,9 @@ public class UppercaseFileReaderUnitTest {
@Test
public void givenUppercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
- // We'll transform the resource URL path to URI to load the file correctly in Windows
- URL url = getClass().getClassLoader().getResource("files/test.txt");
- String filePath = Paths.get(url.toURI()).toString();
- BaseFileReader uppercaseFileReader = new UppercaseFileReader(filePath);
+ Path path = Paths.get(getClass().getClassLoader().getResource("files/test.txt").toURI());
+ BaseFileReader uppercaseFileReader = new UppercaseFileReader(path);
assertThat(uppercaseFileReader.readFile()).isInstanceOf(List.class);
- }
+ }
}
diff --git a/core-java/src/test/java/com/baeldung/graph/GraphTraversalUnitTest.java b/core-java/src/test/java/com/baeldung/graph/GraphTraversalUnitTest.java
new file mode 100644
index 0000000000..d955d56d95
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/graph/GraphTraversalUnitTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.graph;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class GraphTraversalUnitTest {
+ @Test
+ public void givenAGraph_whenTraversingDepthFirst_thenExpectedResult() {
+ Graph graph = createGraph();
+ Assert.assertEquals("[Bob, Rob, Maria, Alice, Mark]",
+ GraphTraversal.depthFirstTraversal(graph, "Bob").toString());
+ }
+
+ @Test
+ public void givenAGraph_whenTraversingBreadthFirst_thenExpectedResult() {
+ Graph graph = createGraph();
+ Assert.assertEquals("[Bob, Alice, Rob, Mark, Maria]",
+ GraphTraversal.breadthFirstTraversal(graph, "Bob").toString());
+ }
+
+ Graph createGraph() {
+ Graph graph = new Graph();
+ graph.addVertex("Bob");
+ graph.addVertex("Alice");
+ graph.addVertex("Mark");
+ graph.addVertex("Rob");
+ graph.addVertex("Maria");
+ graph.addEdge("Bob", "Alice");
+ graph.addEdge("Bob", "Rob");
+ graph.addEdge("Alice", "Mark");
+ graph.addEdge("Rob", "Mark");
+ graph.addEdge("Alice", "Maria");
+ graph.addEdge("Rob", "Maria");
+ return graph;
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java b/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java
new file mode 100644
index 0000000000..b669947d9c
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java
@@ -0,0 +1,171 @@
+package com.baeldung.java.properties;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.Enumeration;
+import java.util.Properties;
+
+import org.junit.Test;
+
+public class PropertiesUnitTest {
+
+ @Test
+ public void givenPropertyValue_whenPropertiesFileLoaded_thenCorrect() throws IOException {
+
+ String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
+ String appConfigPath = rootPath + "app.properties";
+ String catalogConfigPath = rootPath + "catalog";
+
+ Properties appProps = new Properties();
+ appProps.load(new FileInputStream(appConfigPath));
+
+ Properties catalogProps = new Properties();
+ catalogProps.load(new FileInputStream(catalogConfigPath));
+
+ String appVersion = appProps.getProperty("version");
+ assertEquals("1.0", appVersion);
+
+ assertEquals("files", catalogProps.getProperty("c1"));
+ }
+
+ @Test
+ public void givenPropertyValue_whenXMLPropertiesFileLoaded_thenCorrect() throws IOException {
+
+ String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
+ String iconConfigPath = rootPath + "icons.xml";
+ Properties iconProps = new Properties();
+ iconProps.loadFromXML(new FileInputStream(iconConfigPath));
+
+ assertEquals("icon1.jpg", iconProps.getProperty("fileIcon"));
+ }
+
+ @Test
+ public void givenAbsentProperty_whenPropertiesFileLoaded_thenReturnsDefault() throws IOException {
+
+ String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
+ String appConfigPath = rootPath + "app.properties";
+ Properties appProps = new Properties();
+ appProps.load(new FileInputStream(appConfigPath));
+
+ String appVersion = appProps.getProperty("version");
+ String appName = appProps.getProperty("name", "defaultName");
+ String appGroup = appProps.getProperty("group", "baeldung");
+ String appDownloadAddr = appProps.getProperty("downloadAddr");
+
+ assertEquals("1.0", appVersion);
+ assertEquals("TestApp", appName);
+ assertEquals("baeldung", appGroup);
+ assertNull(appDownloadAddr);
+ }
+
+ @Test(expected = Exception.class)
+ public void givenImproperObjectCasting_whenPropertiesFileLoaded_thenThrowsException() throws IOException {
+
+ String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
+ String appConfigPath = rootPath + "app.properties";
+ Properties appProps = new Properties();
+ appProps.load(new FileInputStream(appConfigPath));
+
+ float appVerFloat = (float) appProps.get("version");
+ }
+
+ @Test
+ public void givenPropertyValue_whenPropertiesSet_thenCorrect() throws IOException {
+
+ String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
+ String appConfigPath = rootPath + "app.properties";
+ Properties appProps = new Properties();
+ appProps.load(new FileInputStream(appConfigPath));
+
+ appProps.setProperty("name", "NewAppName");
+ appProps.setProperty("downloadAddr", "www.baeldung.com/downloads");
+
+ String newAppName = appProps.getProperty("name");
+ assertEquals("NewAppName", newAppName);
+
+ String newAppDownloadAddr = appProps.getProperty("downloadAddr");
+ assertEquals("www.baeldung.com/downloads", newAppDownloadAddr);
+ }
+
+ @Test
+ public void givenPropertyValueNull_whenPropertiesRemoved_thenCorrect() throws IOException {
+
+ String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
+ String appConfigPath = rootPath + "app.properties";
+ Properties appProps = new Properties();
+ appProps.load(new FileInputStream(appConfigPath));
+
+ String versionBeforeRemoval = appProps.getProperty("version");
+ assertEquals("1.0", versionBeforeRemoval);
+
+ appProps.remove("version");
+ String versionAfterRemoval = appProps.getProperty("version");
+ assertNull(versionAfterRemoval);
+ }
+
+ @Test
+ public void whenPropertiesStoredInFile_thenCorrect() throws IOException {
+
+ String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
+ String appConfigPath = rootPath + "app.properties";
+ Properties appProps = new Properties();
+ appProps.load(new FileInputStream(appConfigPath));
+
+ String newAppConfigPropertiesFile = rootPath + "newApp.properties";
+ appProps.store(new FileWriter(newAppConfigPropertiesFile), "store to properties file");
+
+ String newAppConfigXmlFile = rootPath + "newApp.xml";
+ appProps.storeToXML(new FileOutputStream(newAppConfigXmlFile), "store to xml file");
+ }
+
+ @Test
+ public void givenPropertyValueAbsent_LoadsValuesFromDefaultProperties() throws IOException {
+
+ String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
+
+ String defaultConfigPath = rootPath + "default.properties";
+ Properties defaultProps = new Properties();
+ defaultProps.load(new FileInputStream(defaultConfigPath));
+
+ String appConfigPath = rootPath + "app.properties";
+ Properties appProps = new Properties(defaultProps);
+ appProps.load(new FileInputStream(appConfigPath));
+
+ String appName = appProps.getProperty("name");
+ String appVersion = appProps.getProperty("version");
+ String defaultSite = appProps.getProperty("site");
+
+ assertEquals("1.0", appVersion);
+ assertEquals("TestApp", appName);
+ assertEquals("www.google.com", defaultSite);
+ }
+
+ @Test
+ public void givenPropertiesSize_whenPropertyFileLoaded_thenCorrect() throws IOException {
+
+ String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
+ String appPropsPath = rootPath + "app.properties";
+ Properties appProps = new Properties();
+ appProps.load(new FileInputStream(appPropsPath));
+
+ appProps.list(System.out); // list all key-value pairs
+
+ Enumeration
- 1.5.0
- 1.5.0.Final
- 0.5.0
+ 1.16.1
+ 1.6.1
+ 0.6.1
-
diff --git a/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java b/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java
index 1a1809387f..f653e17910 100644
--- a/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java
+++ b/grpc/src/main/java/org/baeldung/grpc/client/GrpcClient.java
@@ -10,7 +10,7 @@ import io.grpc.ManagedChannelBuilder;
public class GrpcClient {
public static void main(String[] args) throws InterruptedException {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080)
- .usePlaintext(true)
+ .usePlaintext()
.build();
HelloServiceGrpc.HelloServiceBlockingStub stub
diff --git a/guava-collections/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java b/guava-collections/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java
index 81ba72373c..c0c5efea23 100644
--- a/guava-collections/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java
+++ b/guava-collections/src/test/java/org/baeldung/guava/GuavaRangeMapUnitTest.java
@@ -2,6 +2,9 @@ package org.baeldung.guava;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
import java.util.Map;
import org.junit.Test;
import com.google.common.collect.ImmutableRangeMap;
@@ -98,8 +101,9 @@ public class GuavaRangeMapUnitTest {
final RangeMap experiencedSubRangeDesignationMap = experienceRangeDesignationMap.subRangeMap(Range.closed(4, 14));
assertNull(experiencedSubRangeDesignationMap.get(3));
- assertEquals("Executive Director", experiencedSubRangeDesignationMap.get(14));
- assertEquals("Vice President", experiencedSubRangeDesignationMap.get(7));
+ assertTrue(experiencedSubRangeDesignationMap.asMapOfRanges().values()
+ .containsAll(Arrays.asList("Executive Director", "Vice President", "Executive Director")));
+
}
@Test
diff --git a/guava-modules/guava-18/pom.xml b/guava-modules/guava-18/pom.xml
index ce9395fbf4..d55aa9ce82 100644
--- a/guava-modules/guava-18/pom.xml
+++ b/guava-modules/guava-18/pom.xml
@@ -2,10 +2,10 @@
4.0.0
- com.baeldung
guava-18
0.1.0-SNAPSHOT
-
+ guava-18
+
com.baeldung
parent-java
diff --git a/guava-modules/guava-19/pom.xml b/guava-modules/guava-19/pom.xml
index 5dfb4d2cec..0548bb0c1f 100644
--- a/guava-modules/guava-19/pom.xml
+++ b/guava-modules/guava-19/pom.xml
@@ -2,10 +2,10 @@
4.0.0
- com.baeldung
guava-19
0.1.0-SNAPSHOT
-
+ guava-19
+
com.baeldung
parent-java
diff --git a/guava-modules/guava-21/pom.xml b/guava-modules/guava-21/pom.xml
index 945b7c27c1..bdb1058a48 100644
--- a/guava-modules/guava-21/pom.xml
+++ b/guava-modules/guava-21/pom.xml
@@ -4,7 +4,8 @@
4.0.0
guava-21
1.0-SNAPSHOT
-
+ guava-21
+
com.baeldung
parent-java
diff --git a/guest/core-java-9/pom.xml b/guest/core-java-9/pom.xml
index e9271b42ff..3847c19d16 100644
--- a/guest/core-java-9/pom.xml
+++ b/guest/core-java-9/pom.xml
@@ -4,7 +4,8 @@
com.stackify
core-java-9
0.0.1-SNAPSHOT
-
+ core-java-9
+
com.baeldung
parent-modules
diff --git a/guest/core-java/pom.xml b/guest/core-java/pom.xml
index 787dd764a1..5057f7eaed 100644
--- a/guest/core-java/pom.xml
+++ b/guest/core-java/pom.xml
@@ -4,6 +4,7 @@
com.stackify
core-java
0.0.1-SNAPSHOT
+ core-java
com.baeldung
diff --git a/guest/core-kotlin/pom.xml b/guest/core-kotlin/pom.xml
index 6b189143a4..a57dd28ffd 100644
--- a/guest/core-kotlin/pom.xml
+++ b/guest/core-kotlin/pom.xml
@@ -6,7 +6,8 @@
1.0-SNAPSHOT
com.stackify
jar
-
+ core-kotlin
+
jcenter
diff --git a/guest/deep-jsf/pom.xml b/guest/deep-jsf/pom.xml
index e09b5e0606..12426a8833 100644
--- a/guest/deep-jsf/pom.xml
+++ b/guest/deep-jsf/pom.xml
@@ -4,6 +4,7 @@
com.stackify
deep-jsf
0.0.1-SNAPSHOT
+ deep-jsf
war
diff --git a/guest/junit5-example/pom.xml b/guest/junit5-example/pom.xml
index 457fb1fcaa..7c0cc3e776 100644
--- a/guest/junit5-example/pom.xml
+++ b/guest/junit5-example/pom.xml
@@ -4,7 +4,8 @@
junit5-example
junit5-example
0.0.1-SNAPSHOT
-
+ junit5-example
+
com.baeldung
parent-modules
diff --git a/guest/log4j2-example/pom.xml b/guest/log4j2-example/pom.xml
index f64869879f..ab55e0b60e 100644
--- a/guest/log4j2-example/pom.xml
+++ b/guest/log4j2-example/pom.xml
@@ -4,7 +4,8 @@
log4j2-example
log4j2-example
0.0.1-SNAPSHOT
-
+ log4j2-example
+
com.baeldung
parent-modules
diff --git a/guest/logback-example/pom.xml b/guest/logback-example/pom.xml
index 04de6a00a2..6e9fe0ddea 100644
--- a/guest/logback-example/pom.xml
+++ b/guest/logback-example/pom.xml
@@ -4,6 +4,7 @@
com.stackify
logback-example
0.0.1-SNAPSHOT
+ logback-example
com.baeldung
diff --git a/guest/memory-leaks/pom.xml b/guest/memory-leaks/pom.xml
index 956ae9c408..f1d411acbc 100644
--- a/guest/memory-leaks/pom.xml
+++ b/guest/memory-leaks/pom.xml
@@ -1,10 +1,10 @@
4.0.0
- com.baeldung
memory-leaks
0.0.1-SNAPSHOT
-
+ memory-leaks
+
com.baeldung
parent-modules
diff --git a/guest/remote-debugging/pom.xml b/guest/remote-debugging/pom.xml
index 974421de97..07b9cc49d8 100644
--- a/guest/remote-debugging/pom.xml
+++ b/guest/remote-debugging/pom.xml
@@ -5,8 +5,8 @@
com.stackify
remote-debugging
0.0.1-SNAPSHOT
+ remote-debugging
war
- remote-debugging
org.springframework.boot
diff --git a/guest/slf4j/guide/pom.xml b/guest/slf4j/guide/pom.xml
index 0db9b46247..657ede73b6 100644
--- a/guest/slf4j/guide/pom.xml
+++ b/guest/slf4j/guide/pom.xml
@@ -2,13 +2,12 @@
4.0.0
-
com.stackify.slf4j.guide
slf4j-parent-module
1.0.0-SNAPSHOT
+ slf4j-parent-module
pom
-
org.springframework.boot
spring-boot-starter-parent
diff --git a/guest/slf4j/guide/slf4j-log4j/pom.xml b/guest/slf4j/guide/slf4j-log4j/pom.xml
index 0d08fa6191..bca5392f4d 100644
--- a/guest/slf4j/guide/slf4j-log4j/pom.xml
+++ b/guest/slf4j/guide/slf4j-log4j/pom.xml
@@ -2,9 +2,9 @@
4.0.0
-
slf4j-log4j
0.0.1-SNAPSHOT
+ slf4j-log4j
jar
diff --git a/guest/slf4j/guide/slf4j-log4j2/pom.xml b/guest/slf4j/guide/slf4j-log4j2/pom.xml
index 643649335f..9473362cb8 100644
--- a/guest/slf4j/guide/slf4j-log4j2/pom.xml
+++ b/guest/slf4j/guide/slf4j-log4j2/pom.xml
@@ -2,9 +2,9 @@
4.0.0
-
slf4j-log4j2
0.0.1-SNAPSHOT
+ slf4j-log4j2
jar
diff --git a/guest/slf4j/guide/slf4j-logback/pom.xml b/guest/slf4j/guide/slf4j-logback/pom.xml
index e8aebf0ef6..0327e79732 100644
--- a/guest/slf4j/guide/slf4j-logback/pom.xml
+++ b/guest/slf4j/guide/slf4j-logback/pom.xml
@@ -2,9 +2,9 @@
4.0.0
-
slf4j-logback
0.0.1-SNAPSHOT
+ slf4j-logback
jar
diff --git a/guest/spring-boot-app/pom.xml b/guest/spring-boot-app/pom.xml
index 7daa8f668e..423dadbb99 100644
--- a/guest/spring-boot-app/pom.xml
+++ b/guest/spring-boot-app/pom.xml
@@ -4,6 +4,7 @@
spring-boot-app
spring-boot-app
0.0.1-SNAPSHOT
+ spring-boot-app
war
diff --git a/guest/spring-mvc/pom.xml b/guest/spring-mvc/pom.xml
index c0ef451605..3bffb1530d 100644
--- a/guest/spring-mvc/pom.xml
+++ b/guest/spring-mvc/pom.xml
@@ -5,8 +5,8 @@
com.stackify.guest
spring-mvc
0.0.1-SNAPSHOT
- jar
spring-mvc
+ jar
Spring MVC sample project
diff --git a/guest/thread-pools/pom.xml b/guest/thread-pools/pom.xml
index db9a5ac89f..2591cb2746 100644
--- a/guest/thread-pools/pom.xml
+++ b/guest/thread-pools/pom.xml
@@ -4,7 +4,8 @@
com.stackify
thread-pools
0.0.1-SNAPSHOT
-
+ thread-pools
+
com.baeldung
parent-modules
diff --git a/guest/tomcat-app/pom.xml b/guest/tomcat-app/pom.xml
index 7fd27e869b..9ce77c758a 100644
--- a/guest/tomcat-app/pom.xml
+++ b/guest/tomcat-app/pom.xml
@@ -4,6 +4,7 @@
com.stackify
tomcat-app
0.0.1-SNAPSHOT
+ tomcat-app
war
diff --git a/guest/webservices/rest-client/pom.xml b/guest/webservices/rest-client/pom.xml
index 5e52b7161c..8508186e86 100644
--- a/guest/webservices/rest-client/pom.xml
+++ b/guest/webservices/rest-client/pom.xml
@@ -3,6 +3,7 @@
com.stackify
rest-client
0.0.1-SNAPSHOT
+ rest-client
war
diff --git a/guest/webservices/rest-server/pom.xml b/guest/webservices/rest-server/pom.xml
index 4b3d241293..c576924215 100644
--- a/guest/webservices/rest-server/pom.xml
+++ b/guest/webservices/rest-server/pom.xml
@@ -4,6 +4,7 @@
com.stackify
rest-server
0.0.1-SNAPSHOT
+ rest-server
war
diff --git a/guest/webservices/spring-rest-service/pom.xml b/guest/webservices/spring-rest-service/pom.xml
index 49d35766e8..fcec8a3e12 100644
--- a/guest/webservices/spring-rest-service/pom.xml
+++ b/guest/webservices/spring-rest-service/pom.xml
@@ -4,6 +4,7 @@
com.stackify
spring-rest-service
0.0.1-SNAPSHOT
+ spring-rest-service
war
diff --git a/helidon/helidon-mp/pom.xml b/helidon/helidon-mp/pom.xml
index 1ec1131a67..1f39431886 100644
--- a/helidon/helidon-mp/pom.xml
+++ b/helidon/helidon-mp/pom.xml
@@ -2,9 +2,9 @@
4.0.0
-
helidon-mp
-
+ helidon-mp
+
com.baeldung.helidon
helidon
diff --git a/helidon/helidon-se/pom.xml b/helidon/helidon-se/pom.xml
index 5e14ecb81c..8982bf048e 100644
--- a/helidon/helidon-se/pom.xml
+++ b/helidon/helidon-se/pom.xml
@@ -3,9 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
helidon-se
-
+ helidon-se
+
com.baeldung.helidon
helidon
diff --git a/helidon/pom.xml b/helidon/pom.xml
index ea8cc52ee0..85bab4db42 100644
--- a/helidon/pom.xml
+++ b/helidon/pom.xml
@@ -2,10 +2,9 @@
4.0.0
-
com.baeldung.helidon
helidon
- 1.0.0-SNAPSHOT
+ helidon
pom
diff --git a/image-processing/pom.xml b/image-processing/pom.xml
index fe8001ae3a..ce75145dc7 100644
--- a/image-processing/pom.xml
+++ b/image-processing/pom.xml
@@ -2,10 +2,10 @@
4.0.0
- com.baeldung
image-processing
1.0-SNAPSHOT
-
+ image-processing
+
com.baeldung
parent-modules
diff --git a/immutables/pom.xml b/immutables/pom.xml
index 17510690b0..efb21e584a 100644
--- a/immutables/pom.xml
+++ b/immutables/pom.xml
@@ -3,8 +3,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
immutables
- 1.0.0-SNAPSHOT
-
+ immutables
+
com.baeldung
parent-modules
diff --git a/java-collections-conversions/README.md b/java-collections-conversions/README.md
index 761a78d7b0..0f89e07d63 100644
--- a/java-collections-conversions/README.md
+++ b/java-collections-conversions/README.md
@@ -8,4 +8,5 @@
- [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list)
- [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set)
- [Converting a List to String in Java](http://www.baeldung.com/java-list-to-string)
-- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
\ No newline at end of file
+- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
+- [Array to String Conversions](https://www.baeldung.com/java-array-to-string)
diff --git a/java-collections-conversions/src/test/java/org/baeldung/convertarraytostring/ArrayToStringUnitTest.java b/java-collections-conversions/src/test/java/org/baeldung/convertarraytostring/ArrayToStringUnitTest.java
new file mode 100644
index 0000000000..b563475997
--- /dev/null
+++ b/java-collections-conversions/src/test/java/org/baeldung/convertarraytostring/ArrayToStringUnitTest.java
@@ -0,0 +1,136 @@
+package org.baeldung.convertarraytostring;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.apache.commons.lang3.StringUtils;
+import org.junit.Test;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Splitter;
+
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertEquals;
+
+public class ArrayToStringUnitTest {
+
+ // convert with Java
+
+ @Test
+ public void givenAStringArray_whenConvertBeforeJava8_thenReturnString() {
+
+ String[] strArray = { "Convert", "Array", "With", "Java" };
+ StringBuilder stringBuilder = new StringBuilder();
+
+ for (int i = 0; i < strArray.length; i++) {
+ stringBuilder.append(strArray[i]);
+ }
+ String joinedString = stringBuilder.toString();
+
+ assertThat(joinedString, instanceOf(String.class));
+ assertEquals("ConvertArrayWithJava", joinedString);
+ }
+
+ @Test
+ public void givenAString_whenConvertBeforeJava8_thenReturnStringArray() {
+
+ String input = "lorem ipsum dolor sit amet";
+ String[] strArray = input.split(" ");
+
+ assertThat(strArray, instanceOf(String[].class));
+ assertEquals(5, strArray.length);
+
+ input = "loremipsum";
+ strArray = input.split("");
+ assertThat(strArray, instanceOf(String[].class));
+ assertEquals(10, strArray.length);
+ }
+
+ @Test
+ public void givenAnIntArray_whenConvertBeforeJava8_thenReturnString() {
+
+ int[] strArray = { 1, 2, 3, 4, 5 };
+ StringBuilder stringBuilder = new StringBuilder();
+
+ for (int i = 0; i < strArray.length; i++) {
+ stringBuilder.append(Integer.valueOf(strArray[i]));
+ }
+ String joinedString = stringBuilder.toString();
+
+ assertThat(joinedString, instanceOf(String.class));
+ assertEquals("12345", joinedString);
+ }
+
+ // convert with Java Stream API
+
+ @Test
+ public void givenAStringArray_whenConvertWithJavaStream_thenReturnString() {
+
+ String[] strArray = { "Convert", "With", "Java", "Streams" };
+ String joinedString = Arrays.stream(strArray)
+ .collect(Collectors.joining());
+ assertThat(joinedString, instanceOf(String.class));
+ assertEquals("ConvertWithJavaStreams", joinedString);
+
+ joinedString = Arrays.stream(strArray)
+ .collect(Collectors.joining(","));
+ assertThat(joinedString, instanceOf(String.class));
+ assertEquals("Convert,With,Java,Streams", joinedString);
+ }
+
+
+ // convert with Apache Commons
+
+ @Test
+ public void givenAStringArray_whenConvertWithApacheCommons_thenReturnString() {
+
+ String[] strArray = { "Convert", "With", "Apache", "Commons" };
+ String joinedString = StringUtils.join(strArray);
+
+ assertThat(joinedString, instanceOf(String.class));
+ assertEquals("ConvertWithApacheCommons", joinedString);
+ }
+
+ @Test
+ public void givenAString_whenConvertWithApacheCommons_thenReturnStringArray() {
+
+ String input = "lorem ipsum dolor sit amet";
+ String[] strArray = StringUtils.split(input, " ");
+
+ assertThat(strArray, instanceOf(String[].class));
+ assertEquals(5, strArray.length);
+ }
+
+
+ // convert with Guava
+
+ @Test
+ public void givenAStringArray_whenConvertWithGuava_thenReturnString() {
+
+ String[] strArray = { "Convert", "With", "Guava", null };
+ String joinedString = Joiner.on("")
+ .skipNulls()
+ .join(strArray);
+
+ assertThat(joinedString, instanceOf(String.class));
+ assertEquals("ConvertWithGuava", joinedString);
+ }
+
+
+ @Test
+ public void givenAString_whenConvertWithGuava_thenReturnStringArray() {
+
+ String input = "lorem ipsum dolor sit amet";
+
+ List resultList = Splitter.on(' ')
+ .trimResults()
+ .omitEmptyStrings()
+ .splitToList(input);
+ String[] strArray = resultList.toArray(new String[0]);
+
+ assertThat(strArray, instanceOf(String[].class));
+ assertEquals(5, strArray.length);
+ }
+}
diff --git a/java-collections-maps/src/test/java/com/baeldung/java/map/ImmutableMapUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/java/map/ImmutableMapUnitTest.java
new file mode 100644
index 0000000000..b239ae07d8
--- /dev/null
+++ b/java-collections-maps/src/test/java/com/baeldung/java/map/ImmutableMapUnitTest.java
@@ -0,0 +1,87 @@
+package com.baeldung.java.map;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+
+import com.google.common.collect.ImmutableMap;
+
+
+public class ImmutableMapUnitTest {
+
+ @Test
+ public void whenCollectionsUnModifiableMapMethod_thenOriginalCollectionChangesReflectInUnmodifiableMap() {
+
+ Map mutableMap = new HashMap<>();
+ mutableMap.put("USA", "North America");
+
+ Map unmodifiableMap = Collections.unmodifiableMap(mutableMap);
+ assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("Canada", "North America"));
+
+ mutableMap.remove("USA");
+ assertFalse(unmodifiableMap.containsKey("USA"));
+
+ mutableMap.put("Mexico", "North America");
+ assertTrue(unmodifiableMap.containsKey("Mexico"));
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ public void whenGuavaImmutableMapFromCopyOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
+
+ Map mutableMap = new HashMap<>();
+ mutableMap.put("USA", "North America");
+
+ ImmutableMap immutableMap = ImmutableMap.copyOf(mutableMap);
+ assertTrue(immutableMap.containsKey("USA"));
+
+ assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
+
+ mutableMap.remove("USA");
+ assertTrue(immutableMap.containsKey("USA"));
+
+ mutableMap.put("Mexico", "North America");
+ assertFalse(immutableMap.containsKey("Mexico"));
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ public void whenGuavaImmutableMapFromBuilderMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
+
+ Map mutableMap = new HashMap<>();
+ mutableMap.put("USA", "North America");
+
+ ImmutableMap immutableMap = ImmutableMap.builder()
+ .putAll(mutableMap)
+ .put("Costa Rica", "North America")
+ .build();
+ assertTrue(immutableMap.containsKey("USA"));
+ assertTrue(immutableMap.containsKey("Costa Rica"));
+
+ assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
+
+ mutableMap.remove("USA");
+ assertTrue(immutableMap.containsKey("USA"));
+
+ mutableMap.put("Mexico", "North America");
+ assertFalse(immutableMap.containsKey("Mexico"));
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ public void whenGuavaImmutableMapFromOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
+
+ ImmutableMap immutableMap = ImmutableMap.of("USA", "North America", "Costa Rica", "North America");
+ assertTrue(immutableMap.containsKey("USA"));
+ assertTrue(immutableMap.containsKey("Costa Rica"));
+
+ assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
+ }
+
+}
diff --git a/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java b/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java
new file mode 100644
index 0000000000..e8aa12d4bd
--- /dev/null
+++ b/java-collections-maps/src/test/java/com/baeldung/java/map/compare/HashMapComparisonUnitTest.java
@@ -0,0 +1,228 @@
+package com.baeldung.java.map.compare;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsMapContaining.hasEntry;
+import static org.hamcrest.collection.IsMapContaining.hasKey;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.junit.Before;
+import org.junit.Test;
+
+import com.google.common.base.Equivalence;
+import com.google.common.collect.MapDifference;
+import com.google.common.collect.MapDifference.ValueDifference;
+import com.google.common.collect.Maps;
+
+public class HashMapComparisonUnitTest {
+
+ Map asiaCapital1;
+ Map asiaCapital2;
+ Map asiaCapital3;
+
+ Map asiaCity1;
+ Map asiaCity2;
+ Map asiaCity3;
+
+ @Before
+ public void setup(){
+ asiaCapital1 = new HashMap();
+ asiaCapital1.put("Japan", "Tokyo");
+ asiaCapital1.put("South Korea", "Seoul");
+
+ asiaCapital2 = new HashMap();
+ asiaCapital2.put("South Korea", "Seoul");
+ asiaCapital2.put("Japan", "Tokyo");
+
+ asiaCapital3 = new HashMap();
+ asiaCapital3.put("Japan", "Tokyo");
+ asiaCapital3.put("China", "Beijing");
+
+ asiaCity1 = new HashMap();
+ asiaCity1.put("Japan", new String[] { "Tokyo", "Osaka" });
+ asiaCity1.put("South Korea", new String[] { "Seoul", "Busan" });
+
+ asiaCity2 = new HashMap();
+ asiaCity2.put("South Korea", new String[] { "Seoul", "Busan" });
+ asiaCity2.put("Japan", new String[] { "Tokyo", "Osaka" });
+
+ asiaCity3 = new HashMap();
+ asiaCity3.put("Japan", new String[] { "Tokyo", "Osaka" });
+ asiaCity3.put("China", new String[] { "Beijing", "Hong Kong" });
+ }
+
+ @Test
+ public void whenCompareTwoHashMapsUsingEquals_thenSuccess() {
+ assertTrue(asiaCapital1.equals(asiaCapital2));
+ assertFalse(asiaCapital1.equals(asiaCapital3));
+ }
+
+ @Test
+ public void whenCompareTwoHashMapsWithArrayValuesUsingEquals_thenFail() {
+ assertFalse(asiaCity1.equals(asiaCity2));
+ }
+
+ @Test
+ public void whenCompareTwoHashMapsUsingStreamAPI_thenSuccess() {
+ assertTrue(areEqual(asiaCapital1, asiaCapital2));
+ assertFalse(areEqual(asiaCapital1, asiaCapital3));
+ }
+
+ @Test
+ public void whenCompareTwoHashMapsWithArrayValuesUsingStreamAPI_thenSuccess() {
+ assertTrue(areEqualWithArrayValue(asiaCity1, asiaCity2));
+ assertFalse(areEqualWithArrayValue(asiaCity1, asiaCity3));
+ }
+
+ @Test
+ public void whenCompareTwoHashMapKeys_thenSuccess() {
+ assertTrue(asiaCapital1.keySet().equals(asiaCapital2.keySet()));
+ assertFalse(asiaCapital1.keySet().equals(asiaCapital3.keySet()));
+ }
+
+ @Test
+ public void whenCompareTwoHashMapKeyValuesUsingStreamAPI_thenSuccess() {
+ Map asiaCapital3 = new HashMap();
+ asiaCapital3.put("Japan", "Tokyo");
+ asiaCapital3.put("South Korea", "Seoul");
+ asiaCapital3.put("China", "Beijing");
+
+ Map asiaCapital4 = new HashMap();
+ asiaCapital4.put("South Korea", "Seoul");
+ asiaCapital4.put("Japan", "Osaka");
+ asiaCapital4.put("China", "Beijing");
+
+ Map result = areEqualKeyValues(asiaCapital3, asiaCapital4);
+
+ assertEquals(3, result.size());
+ assertThat(result, hasEntry("Japan", false));
+ assertThat(result, hasEntry("South Korea", true));
+ assertThat(result, hasEntry("China", true));
+ }
+
+ @Test
+ public void givenDifferentMaps_whenGetDiffUsingGuava_thenSuccess() {
+ Map asia1 = new HashMap();
+ asia1.put("Japan", "Tokyo");
+ asia1.put("South Korea", "Seoul");
+ asia1.put("India", "New Delhi");
+
+ Map asia2 = new HashMap();
+ asia2.put("Japan", "Tokyo");
+ asia2.put("China", "Beijing");
+ asia2.put("India", "Delhi");
+
+ MapDifference diff = Maps.difference(asia1, asia2);
+ Map> entriesDiffering = diff.entriesDiffering();
+
+ assertFalse(diff.areEqual());
+ assertEquals(1, entriesDiffering.size());
+ assertThat(entriesDiffering, hasKey("India"));
+ assertEquals("New Delhi", entriesDiffering.get("India").leftValue());
+ assertEquals("Delhi", entriesDiffering.get("India").rightValue());
+ }
+
+ @Test
+ public void givenDifferentMaps_whenGetEntriesOnOneSideUsingGuava_thenSuccess() {
+ Map asia1 = new HashMap();
+ asia1.put("Japan", "Tokyo");
+ asia1.put("South Korea", "Seoul");
+ asia1.put("India", "New Delhi");
+
+ Map asia2 = new HashMap();
+ asia2.put("Japan", "Tokyo");
+ asia2.put("China", "Beijing");
+ asia2.put("India", "Delhi");
+
+ MapDifference diff = Maps.difference(asia1, asia2);
+ Map entriesOnlyOnRight = diff.entriesOnlyOnRight();
+ Map entriesOnlyOnLeft = diff.entriesOnlyOnLeft();
+
+ assertEquals(1, entriesOnlyOnRight.size());
+ assertThat(entriesOnlyOnRight, hasEntry("China", "Beijing"));
+ assertEquals(1, entriesOnlyOnLeft.size());
+ assertThat(entriesOnlyOnLeft, hasEntry("South Korea", "Seoul"));
+ }
+
+ @Test
+ public void givenDifferentMaps_whenGetCommonEntriesUsingGuava_thenSuccess() {
+ Map asia1 = new HashMap();
+ asia1.put("Japan", "Tokyo");
+ asia1.put("South Korea", "Seoul");
+ asia1.put("India", "New Delhi");
+
+ Map asia2 = new HashMap();
+ asia2.put("Japan", "Tokyo");
+ asia2.put("China", "Beijing");
+ asia2.put("India", "Delhi");
+
+ MapDifference diff = Maps.difference(asia1, asia2);
+ Map entriesInCommon = diff.entriesInCommon();
+
+ assertEquals(1, entriesInCommon.size());
+ assertThat(entriesInCommon, hasEntry("Japan", "Tokyo"));
+ }
+
+ @Test
+ public void givenSimilarMapsWithArrayValue_whenCompareUsingGuava_thenFail() {
+ MapDifference diff = Maps.difference(asiaCity1, asiaCity2);
+ assertFalse(diff.areEqual());
+ }
+
+ @Test
+ public void givenSimilarMapsWithArrayValue_whenCompareUsingGuavaEquivalence_thenSuccess() {
+ Equivalence eq = new Equivalence() {
+ @Override
+ protected boolean doEquivalent(String[] a, String[] b) {
+ return Arrays.equals(a, b);
+ }
+
+ @Override
+ protected int doHash(String[] value) {
+ return value.hashCode();
+ }
+ };
+
+ MapDifference diff = Maps.difference(asiaCity1, asiaCity2, eq);
+ assertTrue(diff.areEqual());
+
+ diff = Maps.difference(asiaCity1, asiaCity3, eq);
+ assertFalse(diff.areEqual());
+ }
+
+ // ===========================================================================
+
+ private boolean areEqual(Map first, Map second) {
+ if (first.size() != second.size()) {
+ return false;
+ }
+
+ return first.entrySet()
+ .stream()
+ .allMatch(e -> e.getValue()
+ .equals(second.get(e.getKey())));
+ }
+
+ private boolean areEqualWithArrayValue(Map first, Map second) {
+ if (first.size() != second.size()) {
+ return false;
+ }
+
+ return first.entrySet()
+ .stream()
+ .allMatch(e -> Arrays.equals(e.getValue(), second.get(e.getKey())));
+ }
+
+ private Map areEqualKeyValues(Map first, Map second) {
+ return first.entrySet()
+ .stream()
+ .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().equals(second.get(e.getKey()))));
+ }
+
+}
diff --git a/java-dates/README.md b/java-dates/README.md
index 66046b16a6..21e54082f4 100644
--- a/java-dates/README.md
+++ b/java-dates/README.md
@@ -24,3 +24,5 @@
- [Add Hours To a Date In Java](http://www.baeldung.com/java-add-hours-date)
- [Guide to DateTimeFormatter](https://www.baeldung.com/java-datetimeformatter)
- [Format ZonedDateTime to String](https://www.baeldung.com/java-format-zoned-datetime-string)
+- [Convert Between java.time.Instant and java.sql.Timestamp](https://www.baeldung.com/java-time-instant-to-java-sql-timestamp)
+- [Convert between String and Timestamp](https://www.baeldung.com/java-string-to-timestamp)
diff --git a/java-dates/src/test/java/com/baeldung/timestamp/StringToTimestampConverterUnitTest.java b/java-dates/src/test/java/com/baeldung/timestamp/StringToTimestampConverterUnitTest.java
new file mode 100644
index 0000000000..2be646eb51
--- /dev/null
+++ b/java-dates/src/test/java/com/baeldung/timestamp/StringToTimestampConverterUnitTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.timestamp;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.sql.Timestamp;
+import java.time.LocalDateTime;
+import java.time.format.DateTimeFormatter;
+
+public class StringToTimestampConverterUnitTest {
+
+ @Test
+ public void givenDatePattern_whenParsing_thenTimestampIsCorrect() {
+ String pattern = "MMM dd, yyyy HH:mm:ss.SSSSSSSS";
+ String timestampAsString = "Nov 12, 2018 13:02:56.12345678";
+ DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
+ LocalDateTime localDateTime = LocalDateTime.from(formatter.parse(timestampAsString));
+
+ Timestamp timestamp = Timestamp.valueOf(localDateTime);
+ Assert.assertEquals("2018-11-12 13:02:56.12345678", timestamp.toString());
+ }
+}
\ No newline at end of file
diff --git a/java-dates/src/test/java/com/baeldung/timestamp/TimestampToStringConverterTest.java b/java-dates/src/test/java/com/baeldung/timestamp/TimestampToStringConverterTest.java
new file mode 100644
index 0000000000..b25ff2edb3
--- /dev/null
+++ b/java-dates/src/test/java/com/baeldung/timestamp/TimestampToStringConverterTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.timestamp;
+
+import org.junit.Assert;
+import org.junit.jupiter.api.Test;
+
+import java.sql.Timestamp;
+import java.time.format.DateTimeFormatter;
+
+public class TimestampToStringConverterTest {
+
+ @Test
+ public void givenDatePattern_whenFormatting_thenResultingStringIsCorrect() {
+ Timestamp timestamp = Timestamp.valueOf("2018-12-12 01:02:03.123456789");
+ DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
+
+ String timestampAsString = formatter.format(timestamp.toLocalDateTime());
+ Assert.assertEquals("2018-12-12T01:02:03.123456789", timestampAsString);
+ }
+}
\ No newline at end of file
diff --git a/java-ee-8-security-api/app-auth-basic-store-db/pom.xml b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml
index 6ecc9f7e80..cf92fe2ecd 100644
--- a/java-ee-8-security-api/app-auth-basic-store-db/pom.xml
+++ b/java-ee-8-security-api/app-auth-basic-store-db/pom.xml
@@ -2,8 +2,8 @@
4.0.0
-
app-auth-basic-store-db
+ app-auth-basic-store-db
war
diff --git a/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml
index bf5315e993..43809f1cd5 100644
--- a/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml
+++ b/java-ee-8-security-api/app-auth-custom-form-store-custom/pom.xml
@@ -2,8 +2,8 @@
4.0.0
-
app-auth-custom-form-store-custom
+ app-auth-custom-form-store-custom
war
diff --git a/java-ee-8-security-api/app-auth-custom-no-store/pom.xml b/java-ee-8-security-api/app-auth-custom-no-store/pom.xml
index c05c0f19be..f9d63f8623 100644
--- a/java-ee-8-security-api/app-auth-custom-no-store/pom.xml
+++ b/java-ee-8-security-api/app-auth-custom-no-store/pom.xml
@@ -2,8 +2,8 @@
4.0.0
-
app-auth-custom-no-store
+ app-auth-custom-no-store
war
diff --git a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml
index 570b36add5..6a7b97b2d7 100644
--- a/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml
+++ b/java-ee-8-security-api/app-auth-form-store-ldap/pom.xml
@@ -3,8 +3,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
app-auth-form-store-ldap
+ app-auth-form-store-ldap
war
diff --git a/java-ee-8-security-api/pom.xml b/java-ee-8-security-api/pom.xml
index 3d235e10a8..ad33c74ad3 100644
--- a/java-ee-8-security-api/pom.xml
+++ b/java-ee-8-security-api/pom.xml
@@ -5,6 +5,7 @@
4.0.0
java-ee-8-security-api
1.0-SNAPSHOT
+ java-ee-8-security-api
pom
@@ -41,7 +42,7 @@
- https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/nightly/2018-05-25_1422/openliberty-all-20180525-1300.zip
+ https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/release/2018-09-05_2337/openliberty-18.0.0.3.zip
true
diff --git a/java-lite/pom.xml b/java-lite/pom.xml
index 5111cd2e7f..03f4e29f4e 100644
--- a/java-lite/pom.xml
+++ b/java-lite/pom.xml
@@ -5,6 +5,7 @@
org.baeldung
java-lite
1.0-SNAPSHOT
+ java-lite
war
diff --git a/java-rmi/pom.xml b/java-rmi/pom.xml
index 33931baedf..ad413b66ab 100644
--- a/java-rmi/pom.xml
+++ b/java-rmi/pom.xml
@@ -4,6 +4,7 @@
com.baeldung.rmi
java-rmi
1.0-SNAPSHOT
+ java-rmi
jar
diff --git a/java-spi/exchange-rate-api/pom.xml b/java-spi/exchange-rate-api/pom.xml
index b626916b56..fd3a7ae0a7 100644
--- a/java-spi/exchange-rate-api/pom.xml
+++ b/java-spi/exchange-rate-api/pom.xml
@@ -2,6 +2,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
exchange-rate-api
+ exchange-rate-api
jar
diff --git a/java-spi/exchange-rate-app/pom.xml b/java-spi/exchange-rate-app/pom.xml
index a42a30ceda..7a076d560c 100644
--- a/java-spi/exchange-rate-app/pom.xml
+++ b/java-spi/exchange-rate-app/pom.xml
@@ -2,6 +2,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
exchange-rate-app
+ exchange-rate-app
jar
diff --git a/java-spi/exchange-rate-impl/pom.xml b/java-spi/exchange-rate-impl/pom.xml
index 41c874c659..8a77b51793 100644
--- a/java-spi/exchange-rate-impl/pom.xml
+++ b/java-spi/exchange-rate-impl/pom.xml
@@ -2,6 +2,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
exchange-rate-impl
+ exchange-rate-impl
jar
diff --git a/java-spi/pom.xml b/java-spi/pom.xml
index 9ac87bf960..97a22024bd 100644
--- a/java-spi/pom.xml
+++ b/java-spi/pom.xml
@@ -2,6 +2,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
java-spi
+ java-spi
pom
diff --git a/java-streams/pom.xml b/java-streams/pom.xml
index e4670c268d..2b52ebb4b3 100644
--- a/java-streams/pom.xml
+++ b/java-streams/pom.xml
@@ -1,5 +1,5 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
java-streams
0.1.0-SNAPSHOT
@@ -74,6 +74,11 @@
aspectjweaver
${asspectj.version}
+
+ pl.touk
+ throwing-function
+ ${throwing-function.version}
+
@@ -108,8 +113,9 @@
1.15
0.6.5
2.10
+ 1.3
- 3.6.1
+ 3.11.1
1.8.9
diff --git a/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java b/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java
new file mode 100644
index 0000000000..49da6e7175
--- /dev/null
+++ b/java-streams/src/main/java/com/baeldung/stream/filter/Customer.java
@@ -0,0 +1,55 @@
+package com.baeldung.stream.filter;
+
+import javax.net.ssl.HttpsURLConnection;
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.URL;
+
+public class Customer {
+ private String name;
+ private int points;
+ private String profilePhotoUrl;
+
+ public Customer(String name, int points) {
+ this(name, points, "");
+ }
+
+ public Customer(String name, int points, String profilePhotoUrl) {
+ this.name = name;
+ this.points = points;
+ this.profilePhotoUrl = profilePhotoUrl;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getPoints() {
+ return points;
+ }
+
+ public boolean hasOver(int points) {
+ return this.points > points;
+ }
+
+ public boolean hasOverThousandPoints() {
+ return this.points > 100;
+ }
+
+ public boolean hasValidProfilePhoto() throws IOException {
+ URL url = new URL(this.profilePhotoUrl);
+ HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
+ return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
+ }
+
+ public boolean hasValidProfilePhotoWithoutCheckedException() {
+ try {
+ URL url = new URL(this.profilePhotoUrl);
+ HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
+ return connection.getResponseCode() == HttpURLConnection.HTTP_OK;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+}
diff --git a/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java
new file mode 100644
index 0000000000..cf82802940
--- /dev/null
+++ b/java-streams/src/test/java/com/baeldung/stream/filter/StreamFilterUnitTest.java
@@ -0,0 +1,159 @@
+package com.baeldung.stream.filter;
+
+import org.junit.jupiter.api.Test;
+import pl.touk.throwing.ThrowingPredicate;
+import pl.touk.throwing.exception.WrappedException;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
+
+public class StreamFilterUnitTest {
+
+ @Test
+ public void givenListOfCustomers_whenFilterByPoints_thenGetTwo() {
+ Customer john = new Customer("John P.", 15);
+ Customer sarah = new Customer("Sarah M.", 200);
+ Customer charles = new Customer("Charles B.", 150);
+ Customer mary = new Customer("Mary T.", 1);
+ List customers = Arrays.asList(john, sarah, charles, mary);
+
+ List customersWithMoreThan100Points = customers
+ .stream()
+ .filter(c -> c.getPoints() > 100)
+ .collect(Collectors.toList());
+
+ assertThat(customersWithMoreThan100Points).hasSize(2);
+ assertThat(customersWithMoreThan100Points).contains(sarah, charles);
+ }
+
+ @Test
+ public void givenListOfCustomers_whenFilterByPointsAndName_thenGetOne() {
+ Customer john = new Customer("John P.", 15);
+ Customer sarah = new Customer("Sarah M.", 200);
+ Customer charles = new Customer("Charles B.", 150);
+ Customer mary = new Customer("Mary T.", 1);
+ List customers = Arrays.asList(john, sarah, charles, mary);
+
+ List charlesWithMoreThan100Points = customers
+ .stream()
+ .filter(c -> c.getPoints() > 100 && c
+ .getName()
+ .startsWith("Charles"))
+ .collect(Collectors.toList());
+
+ assertThat(charlesWithMoreThan100Points).hasSize(1);
+ assertThat(charlesWithMoreThan100Points).contains(charles);
+ }
+
+ @Test
+ public void givenListOfCustomers_whenFilterByMethodReference_thenGetTwo() {
+ Customer john = new Customer("John P.", 15);
+ Customer sarah = new Customer("Sarah M.", 200);
+ Customer charles = new Customer("Charles B.", 150);
+ Customer mary = new Customer("Mary T.", 1);
+ List customers = Arrays.asList(john, sarah, charles, mary);
+
+ List customersWithMoreThan100Points = customers
+ .stream()
+ .filter(Customer::hasOverThousandPoints)
+ .collect(Collectors.toList());
+
+ assertThat(customersWithMoreThan100Points).hasSize(2);
+ assertThat(customersWithMoreThan100Points).contains(sarah, charles);
+ }
+
+ @Test
+ public void givenListOfCustomersWithOptional_whenFilterBy100Points_thenGetTwo() {
+ Optional john = Optional.of(new Customer("John P.", 15));
+ Optional sarah = Optional.of(new Customer("Sarah M.", 200));
+ Optional mary = Optional.of(new Customer("Mary T.", 300));
+ List> customers = Arrays.asList(john, sarah, Optional.empty(), mary, Optional.empty());
+
+ List customersWithMoreThan100Points = customers
+ .stream()
+ .flatMap(c -> c
+ .map(Stream::of)
+ .orElseGet(Stream::empty))
+ .filter(Customer::hasOverThousandPoints)
+ .collect(Collectors.toList());
+
+ assertThat(customersWithMoreThan100Points).hasSize(2);
+ assertThat(customersWithMoreThan100Points).contains(sarah.get(), mary.get());
+ }
+
+ @Test
+ public void givenListOfCustomers_whenFilterWithCustomHandling_thenThrowException() {
+ Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
+ Customer sarah = new Customer("Sarah M.", 200);
+ Customer charles = new Customer("Charles B.", 150);
+ Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
+ List customers = Arrays.asList(john, sarah, charles, mary);
+
+ assertThatThrownBy(() -> customers
+ .stream()
+ .filter(Customer::hasValidProfilePhotoWithoutCheckedException)
+ .count()).isInstanceOf(RuntimeException.class);
+ }
+
+ @Test
+ public void givenListOfCustomers_whenFilterWithThrowingFunction_thenThrowException() {
+ Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
+ Customer sarah = new Customer("Sarah M.", 200);
+ Customer charles = new Customer("Charles B.", 150);
+ Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
+ List customers = Arrays.asList(john, sarah, charles, mary);
+
+ assertThatThrownBy(() -> customers
+ .stream()
+ .filter((ThrowingPredicate.unchecked(Customer::hasValidProfilePhoto)))
+ .collect(Collectors.toList())).isInstanceOf(WrappedException.class);
+ }
+
+ @Test
+ public void givenListOfCustomers_whenFilterWithTryCatch_thenGetTwo() {
+ Customer john = new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e");
+ Customer sarah = new Customer("Sarah M.", 200);
+ Customer charles = new Customer("Charles B.", 150);
+ Customer mary = new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e");
+ List customers = Arrays.asList(john, sarah, charles, mary);
+
+ List customersWithValidProfilePhoto = customers
+ .stream()
+ .filter(c -> {
+ try {
+ return c.hasValidProfilePhoto();
+ } catch (IOException e) {
+ //handle exception
+ }
+ return false;
+ })
+ .collect(Collectors.toList());
+
+ assertThat(customersWithValidProfilePhoto).hasSize(2);
+ assertThat(customersWithValidProfilePhoto).contains(john, mary);
+ }
+
+ @Test
+ public void givenListOfCustomers_whenFilterWithTryCatchAndRuntime_thenThrowException() {
+ List customers = Arrays.asList(new Customer("John P.", 15, "https://images.unsplash.com/photo-1543320485-d0d5a49c2b2e"), new Customer("Sarah M.", 200), new Customer("Charles B.", 150),
+ new Customer("Mary T.", 1, "https://images.unsplash.com/photo-1543297057-25167dfc180e"));
+
+ assertThatThrownBy(() -> customers
+ .stream()
+ .filter(c -> {
+ try {
+ return c.hasValidProfilePhoto();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ })
+ .collect(Collectors.toList())).isInstanceOf(RuntimeException.class);
+ }
+}
diff --git a/java-strings/README.md b/java-strings/README.md
index 1b24a2b821..240acd663b 100644
--- a/java-strings/README.md
+++ b/java-strings/README.md
@@ -36,3 +36,10 @@
- [String Performance Hints](https://www.baeldung.com/java-string-performance)
- [Using indexOf to Find All Occurrences of a Word in a String](https://www.baeldung.com/java-indexOf-find-string-occurrences)
- [Java Base64 Encoding and Decoding](https://www.baeldung.com/java-base64-encode-and-decode)
+- [Generate a Secure Random Password in Java](https://www.baeldung.com/java-generate-secure-password)
+- [Removing Repeated Characters from a String](https://www.baeldung.com/java-remove-repeated-char)
+- [Join Array of Primitives with Separator in Java](https://www.baeldung.com/java-join-primitive-array)
+- [Convert String to Byte Array and Reverse in Java](https://www.baeldung.com/java-string-to-byte-array)
+- [Pad a String with Zeros or Spaces in Java](https://www.baeldung.com/java-pad-string)
+- [Adding a Newline Character to a String in Java](https://www.baeldung.com/java-string-newline)
+- [Remove or Replace part of a String in Java](https://www.baeldung.com/java-remove-replace-string-part)
diff --git a/java-strings/pom.xml b/java-strings/pom.xml
index ab94c28d4d..f4fb1c0865 100755
--- a/java-strings/pom.xml
+++ b/java-strings/pom.xml
@@ -122,13 +122,13 @@
- 3.5
+ 3.8.1
1.10
3.6.1
1.19
61.1
- 26.0-jre
+ 27.0.1-jre
diff --git a/java-strings/src/main/java/com/baeldung/string/AddingNewLineToString.java b/java-strings/src/main/java/com/baeldung/string/AddingNewLineToString.java
new file mode 100644
index 0000000000..b522f7337b
--- /dev/null
+++ b/java-strings/src/main/java/com/baeldung/string/AddingNewLineToString.java
@@ -0,0 +1,69 @@
+package com.baeldung.string;
+
+public class AddingNewLineToString {
+
+ public static void main(String[] args) {
+ String line1 = "Humpty Dumpty sat on a wall.";
+ String line2 = "Humpty Dumpty had a great fall.";
+ String rhyme = "";
+
+ System.out.println("***New Line in a String in Java***");
+ //1. Using "\n"
+ System.out.println("1. Using \\n");
+ rhyme = line1 + "\n" + line2;
+ System.out.println(rhyme);
+
+ //2. Using "\r\n"
+ System.out.println("2. Using \\r\\n");
+ rhyme = line1 + "\r\n" + line2;
+ System.out.println(rhyme);
+
+ //3. Using "\r"
+ System.out.println("3. Using \\r");
+ rhyme = line1 + "\r" + line2;
+ System.out.println(rhyme);
+
+ //4. Using "\n\r" Note that this is not same as "\r\n"
+ // Using "\n\r" is equivalent to adding two lines
+ System.out.println("4. Using \\n\\r");
+ rhyme = line1 + "\n\r" + line2;
+ System.out.println(rhyme);
+
+ //5. Using System.lineSeparator()
+ System.out.println("5. Using System.lineSeparator()");
+ rhyme = line1 + System.lineSeparator() + line2;
+ System.out.println(rhyme);
+
+ //6. Using System.getProperty("line.separator")
+ System.out.println("6. Using System.getProperty(\"line.separator\")");
+ rhyme = line1 + System.getProperty("line.separator") + line2;
+ System.out.println(rhyme);
+
+ System.out.println("***HTML to rendered in a browser***");
+ //1. Line break for HTML using
+ System.out.println("1. Line break for HTML using
");
+ rhyme = line1 + "
" + line2;
+ System.out.println(rhyme);
+
+ //2. Line break for HTML using “
”
+ System.out.println("2. Line break for HTML using
");
+ rhyme = line1 + "
" + line2;
+ System.out.println(rhyme);
+
+ //3. Line break for HTML using “
”
+ System.out.println("3. Line break for HTML using
");
+ rhyme = line1 + "
" + line2;
+ System.out.println(rhyme);
+
+ //4. Line break for HTML using “
;”
+ System.out.println("4. Line break for HTML using
");
+ rhyme = line1 + "
" + line2;
+ System.out.println(rhyme);
+
+ //5. Line break for HTML using \n”
+ System.out.println("5. Line break for HTML using \\n");
+ rhyme = line1 + "\n" + line2;
+ System.out.println(rhyme);
+ }
+
+}
\ No newline at end of file
diff --git a/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java b/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java
new file mode 100644
index 0000000000..688bf43b3c
--- /dev/null
+++ b/java-strings/src/main/java/com/baeldung/string/SubstringPalindrome.java
@@ -0,0 +1,90 @@
+package com.baeldung.string;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class SubstringPalindrome {
+
+ public Set findAllPalindromesUsingCenter(String input) {
+ final Set palindromes = new HashSet<>();
+ if (input == null || input.isEmpty()) {
+ return palindromes;
+ }
+ if (input.length() == 1) {
+ palindromes.add(input);
+ return palindromes;
+ }
+ for (int i = 0; i < input.length(); i++) {
+ palindromes.addAll(findPalindromes(input, i, i + 1));
+ palindromes.addAll(findPalindromes(input, i, i));
+ }
+ return palindromes;
+ }
+
+ private Set findPalindromes(String input, int low, int high) {
+ Set result = new HashSet<>();
+ while (low >= 0 && high < input.length() && input.charAt(low) == input.charAt(high)) {
+ result.add(input.substring(low, high + 1));
+ low--;
+ high++;
+ }
+ return result;
+ }
+
+ public Set findAllPalindromesUsingBruteForceApproach(String input) {
+ Set palindromes = new HashSet<>();
+ if (input == null || input.isEmpty()) {
+ return palindromes;
+ }
+ if (input.length() == 1) {
+ palindromes.add(input);
+ return palindromes;
+ }
+ for (int i = 0; i < input.length(); i++) {
+ for (int j = i + 1; j <= input.length(); j++)
+ if (isPalindrome(input.substring(i, j))) {
+ palindromes.add(input.substring(i, j));
+ }
+ }
+ return palindromes;
+ }
+
+ private boolean isPalindrome(String input) {
+ StringBuilder plain = new StringBuilder(input);
+ StringBuilder reverse = plain.reverse();
+ return (reverse.toString()).equals(input);
+ }
+
+ public Set findAllPalindromesUsingManachersAlgorithm(String input) {
+ Set palindromes = new HashSet<>();
+ String formattedInput = "@" + input + "#";
+ char inputCharArr[] = formattedInput.toCharArray();
+ int max;
+ int radius[][] = new int[2][input.length() + 1];
+ for (int j = 0; j <= 1; j++) {
+ radius[j][0] = max = 0;
+ int i = 1;
+ while (i <= input.length()) {
+ palindromes.add(Character.toString(inputCharArr[i]));
+ while (inputCharArr[i - max - 1] == inputCharArr[i + j + max])
+ max++;
+ radius[j][i] = max;
+ int k = 1;
+ while ((radius[j][i - k] != max - k) && (k < max)) {
+ radius[j][i + k] = Math.min(radius[j][i - k], max - k);
+ k++;
+ }
+ max = Math.max(max - k, 0);
+ i += k;
+ }
+ }
+ for (int i = 1; i <= input.length(); i++) {
+ for (int j = 0; j <= 1; j++) {
+ for (max = radius[j][i]; max > 0; max--) {
+ palindromes.add(input.substring(i - max - 1, max + j + i - 1));
+ }
+ }
+ }
+ return palindromes;
+ }
+}
diff --git a/java-strings/src/main/java/com/baeldung/string/checkinputs/CheckIntegerInput.java b/java-strings/src/main/java/com/baeldung/string/checkinputs/CheckIntegerInput.java
new file mode 100644
index 0000000000..9462244bbb
--- /dev/null
+++ b/java-strings/src/main/java/com/baeldung/string/checkinputs/CheckIntegerInput.java
@@ -0,0 +1,19 @@
+package com.baeldung.string.checkinputs;
+
+import java.util.Scanner;
+
+public class CheckIntegerInput {
+
+ public static void main(String[] args) {
+
+ try (Scanner scanner = new Scanner(System.in)) {
+ System.out.println("Enter an integer : ");
+
+ if (scanner.hasNextInt()) {
+ System.out.println("You entered : " + scanner.nextInt());
+ } else {
+ System.out.println("The input is not an integer");
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java b/java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java
new file mode 100644
index 0000000000..c9d748e897
--- /dev/null
+++ b/java-strings/src/main/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroes.java
@@ -0,0 +1,103 @@
+package com.baeldung.string.removeleadingtrailingchar;
+
+
+import org.apache.commons.lang3.StringUtils;
+
+import com.google.common.base.CharMatcher;
+
+public class RemoveLeadingAndTrailingZeroes {
+
+ public static String removeLeadingZeroesWithStringBuilder(String s) {
+ StringBuilder sb = new StringBuilder(s);
+
+ while (sb.length() > 1 && sb.charAt(0) == '0') {
+ sb.deleteCharAt(0);
+ }
+
+ return sb.toString();
+ }
+
+ public static String removeTrailingZeroesWithStringBuilder(String s) {
+ StringBuilder sb = new StringBuilder(s);
+
+ while (sb.length() > 1 && sb.charAt(sb.length() - 1) == '0') {
+ sb.setLength(sb.length() - 1);
+ }
+
+ return sb.toString();
+ }
+
+ public static String removeLeadingZeroesWithSubstring(String s) {
+ int index = 0;
+
+ for (; index < s.length() - 1; index++) {
+ if (s.charAt(index) != '0') {
+ break;
+ }
+ }
+
+ return s.substring(index);
+ }
+
+ public static String removeTrailingZeroesWithSubstring(String s) {
+ int index = s.length() - 1;
+
+ for (; index > 0; index--) {
+ if (s.charAt(index) != '0') {
+ break;
+ }
+ }
+
+ return s.substring(0, index + 1);
+ }
+
+ public static String removeLeadingZeroesWithApacheCommonsStripStart(String s) {
+ String stripped = StringUtils.stripStart(s, "0");
+
+ if (stripped.isEmpty() && !s.isEmpty()) {
+ return "0";
+ }
+
+ return stripped;
+ }
+
+ public static String removeTrailingZeroesWithApacheCommonsStripEnd(String s) {
+ String stripped = StringUtils.stripEnd(s, "0");
+
+ if (stripped.isEmpty() && !s.isEmpty()) {
+ return "0";
+ }
+
+ return stripped;
+ }
+
+ public static String removeLeadingZeroesWithGuavaTrimLeadingFrom(String s) {
+ String stripped = CharMatcher.is('0')
+ .trimLeadingFrom(s);
+
+ if (stripped.isEmpty() && !s.isEmpty()) {
+ return "0";
+ }
+
+ return stripped;
+ }
+
+ public static String removeTrailingZeroesWithGuavaTrimTrailingFrom(String s) {
+ String stripped = CharMatcher.is('0')
+ .trimTrailingFrom(s);
+
+ if (stripped.isEmpty() && !s.isEmpty()) {
+ return "0";
+ }
+
+ return stripped;
+ }
+
+ public static String removeLeadingZeroesWithRegex(String s) {
+ return s.replaceAll("^0+(?!$)", "");
+ }
+
+ public static String removeTrailingZeroesWithRegex(String s) {
+ return s.replaceAll("(?!^)0+$", "");
+ }
+}
diff --git a/java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java b/java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java
new file mode 100644
index 0000000000..d8fd9c4b14
--- /dev/null
+++ b/java-strings/src/main/java/com/baeldung/stringduplicates/RemoveDuplicateFromString.java
@@ -0,0 +1,102 @@
+package com.baeldung.stringduplicates;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.LinkedHashSet;
+import java.util.Set;
+
+public class RemoveDuplicateFromString {
+
+
+ String removeDuplicatesUsingCharArray(String str) {
+
+ char[] chars = str.toCharArray();
+ StringBuilder sb = new StringBuilder();
+ int repeatedCtr;
+ for (int i = 0; i < chars.length; i++) {
+ repeatedCtr = 0;
+ for (int j = i + 1; j < chars.length; j++) {
+ if (chars[i] == chars[j]) {
+ repeatedCtr++;
+ }
+ }
+ if (repeatedCtr == 0) {
+ sb.append(chars[i]);
+ }
+ }
+ return sb.toString();
+ }
+
+ String removeDuplicatesUsinglinkedHashSet(String str) {
+
+ StringBuilder sb = new StringBuilder();
+ Set linkedHashSet = new LinkedHashSet<>();
+
+ for (int i = 0; i < str.length(); i++) {
+ linkedHashSet.add(str.charAt(i));
+ }
+
+ for (Character c : linkedHashSet) {
+ sb.append(c);
+ }
+
+ return sb.toString();
+ }
+
+ String removeDuplicatesUsingSorting(String str) {
+ StringBuilder sb = new StringBuilder();
+ if(!str.isEmpty()) {
+ char[] chars = str.toCharArray();
+ Arrays.sort(chars);
+
+ sb.append(chars[0]);
+ for (int i = 1; i < chars.length; i++) {
+ if (chars[i] != chars[i - 1]) {
+ sb.append(chars[i]);
+ }
+ }
+ }
+
+ return sb.toString();
+ }
+
+ String removeDuplicatesUsingHashSet(String str) {
+
+ StringBuilder sb = new StringBuilder();
+ Set hashSet = new HashSet<>();
+
+ for (int i = 0; i < str.length(); i++) {
+ hashSet.add(str.charAt(i));
+ }
+
+ for (Character c : hashSet) {
+ sb.append(c);
+ }
+
+ return sb.toString();
+ }
+
+ String removeDuplicatesUsingIndexOf(String str) {
+
+ StringBuilder sb = new StringBuilder();
+ int idx;
+ for (int i = 0; i < str.length(); i++) {
+ char c = str.charAt(i);
+ idx = str.indexOf(c, i + 1);
+ if (idx == -1) {
+ sb.append(c);
+ }
+ }
+ return sb.toString();
+ }
+
+
+ String removeDuplicatesUsingDistinct(String str) {
+ StringBuilder sb = new StringBuilder();
+ str.chars().distinct().forEach(c -> sb.append((char) c));
+ return sb.toString();
+ }
+
+}
+
+
diff --git a/java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java
new file mode 100644
index 0000000000..c93089e543
--- /dev/null
+++ b/java-strings/src/test/java/com/baeldung/string/StringFromPrimitiveArrayUnitTest.java
@@ -0,0 +1,129 @@
+package com.baeldung.string;
+
+import com.google.common.base.Joiner;
+import com.google.common.primitives.Chars;
+import com.google.common.primitives.Ints;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.junit.Test;
+
+import java.nio.CharBuffer;
+import java.util.Arrays;
+import java.util.StringJoiner;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+
+public class StringFromPrimitiveArrayUnitTest {
+
+ private int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};
+
+ private char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f'};
+
+ private char separatorChar = '-';
+
+ private String separator = String.valueOf(separatorChar);
+
+ private String expectedIntString = "1-2-3-4-5-6-7-8-9";
+
+ private String expectedCharString = "a-b-c-d-e-f";
+
+ @Test
+ public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_Java8CollectorsJoining() {
+ assertThat(Arrays.stream(intArray)
+ .mapToObj(String::valueOf)
+ .collect(Collectors.joining(separator)))
+ .isEqualTo(expectedIntString);
+ }
+
+ @Test
+ public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_Java8CollectorsJoining() {
+ assertThat(CharBuffer.wrap(charArray).chars()
+ .mapToObj(intChar -> String.valueOf((char) intChar))
+ .collect(Collectors.joining(separator)))
+ .isEqualTo(expectedCharString);
+ }
+
+
+ @Test
+ public void giveIntArray_whenJoinBySeparator_thenReturnsString_through_Java8StringJoiner() {
+ StringJoiner intStringJoiner = new StringJoiner(separator);
+
+ Arrays.stream(intArray)
+ .mapToObj(String::valueOf)
+ .forEach(intStringJoiner::add);
+
+ assertThat(intStringJoiner.toString()).isEqualTo(expectedIntString);
+ }
+
+ @Test
+ public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_Java8StringJoiner() {
+ StringJoiner charStringJoiner = new StringJoiner(separator);
+
+ CharBuffer.wrap(charArray).chars()
+ .mapToObj(intChar -> String.valueOf((char) intChar))
+ .forEach(charStringJoiner::add);
+
+ assertThat(charStringJoiner.toString()).isEqualTo(expectedCharString);
+ }
+
+ @Test
+ public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_CommonsLang() {
+ assertThat(StringUtils.join(intArray, separatorChar)).isEqualTo(expectedIntString);
+ assertThat(StringUtils.join(ArrayUtils.toObject(intArray), separator)).isEqualTo(expectedIntString);
+ }
+
+ @Test
+ public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_CommonsLang() {
+ assertThat(StringUtils.join(charArray, separatorChar)).isEqualTo(expectedCharString);
+ assertThat(StringUtils.join(ArrayUtils.toObject(charArray), separator)).isEqualTo(expectedCharString);
+ }
+
+ @Test
+ public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_GuavaJoiner() {
+ assertThat(Joiner.on(separator).join(Ints.asList(intArray))).isEqualTo(expectedIntString);
+ }
+
+ @Test
+ public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_GuavaJoiner() {
+ assertThat(Joiner.on(separator).join(Chars.asList(charArray))).isEqualTo(expectedCharString);
+ }
+
+ @Test
+ public void givenIntArray_whenJoinBySeparator_thenReturnsString_through_Java7StringBuilder() {
+ assertThat(joinIntArrayWithStringBuilder(intArray, separator)).isEqualTo(expectedIntString);
+ }
+
+ @Test
+ public void givenCharArray_whenJoinBySeparator_thenReturnsString_through_Java7StringBuilder() {
+ assertThat(joinCharArrayWithStringBuilder(charArray, separator)).isEqualTo(expectedCharString);
+ }
+
+ private String joinIntArrayWithStringBuilder(int[] array, String separator) {
+ if (array.length == 0) {
+ return "";
+ }
+ StringBuilder stringBuilder = new StringBuilder();
+ for (int i = 0; i < array.length - 1; i++) {
+ stringBuilder.append(array[i]);
+ stringBuilder.append(separator);
+ }
+ stringBuilder.append(array[array.length - 1]);
+ return stringBuilder.toString();
+ }
+
+ private String joinCharArrayWithStringBuilder(char[] array, String separator) {
+ if (array.length == 0) {
+ return "";
+ }
+ StringBuilder stringBuilder = new StringBuilder();
+ for (int i = 0; i < array.length - 1; i++) {
+ stringBuilder.append(array[i]);
+ stringBuilder.append(separator);
+ }
+ stringBuilder.append(array[array.length - 1]);
+ return stringBuilder.toString();
+ }
+
+}
diff --git a/java-strings/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java b/java-strings/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java
new file mode 100644
index 0000000000..d952d2383b
--- /dev/null
+++ b/java-strings/src/test/java/com/baeldung/string/StringReplaceAndRemoveUnitTest.java
@@ -0,0 +1,83 @@
+package com.baeldung.string;
+
+
+import org.apache.commons.lang3.StringUtils;
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class StringReplaceAndRemoveUnitTest {
+
+
+ @Test
+ public void givenTestStrings_whenReplace_thenProcessedString() {
+
+ String master = "Hello World Baeldung!";
+ String target = "Baeldung";
+ String replacement = "Java";
+ String processed = master.replace(target, replacement);
+ assertTrue(processed.contains(replacement));
+ assertFalse(processed.contains(target));
+
+ }
+
+ @Test
+ public void givenTestStrings_whenReplaceAll_thenProcessedString() {
+
+ String master2 = "Welcome to Baeldung, Hello World Baeldung";
+ String regexTarget= "(Baeldung)$";
+ String replacement = "Java";
+ String processed2 = master2.replaceAll(regexTarget, replacement);
+ assertTrue(processed2.endsWith("Java"));
+
+ }
+
+ @Test
+ public void givenTestStrings_whenStringBuilderMethods_thenProcessedString() {
+
+ String master = "Hello World Baeldung!";
+ String target = "Baeldung";
+ String replacement = "Java";
+
+ int startIndex = master.indexOf(target);
+ int stopIndex = startIndex + target.length();
+
+ StringBuilder builder = new StringBuilder(master);
+
+
+ builder.delete(startIndex, stopIndex);
+ assertFalse(builder.toString().contains(target));
+
+
+ builder.replace(startIndex, stopIndex, replacement);
+ assertTrue(builder.toString().contains(replacement));
+
+
+ }
+
+
+ @Test
+ public void givenTestStrings_whenStringUtilsMethods_thenProcessedStrings() {
+
+ String master = "Hello World Baeldung!";
+ String target = "Baeldung";
+ String replacement = "Java";
+
+ String processed = StringUtils.replace(master, target, replacement);
+ assertTrue(processed.contains(replacement));
+
+ String master2 = "Hello World Baeldung!";
+ String target2 = "baeldung";
+ String processed2 = StringUtils.replaceIgnoreCase(master2, target2, replacement);
+ assertFalse(processed2.contains(target));
+
+ }
+
+
+
+
+
+
+
+}
diff --git a/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java b/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java
new file mode 100644
index 0000000000..b18a8d4a5f
--- /dev/null
+++ b/java-strings/src/test/java/com/baeldung/string/SubstringPalindromeUnitTest.java
@@ -0,0 +1,83 @@
+package com.baeldung.string;
+
+import static org.junit.Assert.assertEquals;
+import java.util.HashSet;
+import java.util.Set;
+import org.junit.Test;
+
+public class SubstringPalindromeUnitTest {
+
+ private static final String INPUT_BUBBLE = "bubble";
+ private static final String INPUT_CIVIC = "civic";
+ private static final String INPUT_INDEED = "indeed";
+ private static final String INPUT_ABABAC = "ababac";
+
+ Set EXPECTED_PALINDROME_BUBBLE = new HashSet() {
+ {
+ add("b");
+ add("u");
+ add("l");
+ add("e");
+ add("bb");
+ add("bub");
+ }
+ };
+
+ Set EXPECTED_PALINDROME_CIVIC = new HashSet() {
+ {
+ add("civic");
+ add("ivi");
+ add("i");
+ add("c");
+ add("v");
+ }
+ };
+
+ Set EXPECTED_PALINDROME_INDEED = new HashSet() {
+ {
+ add("i");
+ add("n");
+ add("d");
+ add("e");
+ add("ee");
+ add("deed");
+ }
+ };
+
+ Set EXPECTED_PALINDROME_ABABAC = new HashSet() {
+ {
+ add("a");
+ add("b");
+ add("c");
+ add("aba");
+ add("bab");
+ add("ababa");
+ }
+ };
+
+ private SubstringPalindrome palindrome = new SubstringPalindrome();
+
+ @Test
+ public void whenUsingManachersAlgorithm_thenFindsAllPalindromes() {
+ assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_BUBBLE));
+ assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_INDEED));
+ assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_CIVIC));
+ assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingManachersAlgorithm(INPUT_ABABAC));
+ }
+
+ @Test
+ public void whenUsingCenterApproach_thenFindsAllPalindromes() {
+ assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingCenter(INPUT_BUBBLE));
+ assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingCenter(INPUT_INDEED));
+ assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingCenter(INPUT_CIVIC));
+ assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingCenter(INPUT_ABABAC));
+ }
+
+ @Test
+ public void whenUsingBruteForceApproach_thenFindsAllPalindromes() {
+ assertEquals(EXPECTED_PALINDROME_BUBBLE, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_BUBBLE));
+ assertEquals(EXPECTED_PALINDROME_INDEED, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_INDEED));
+ assertEquals(EXPECTED_PALINDROME_CIVIC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_CIVIC));
+ assertEquals(EXPECTED_PALINDROME_ABABAC, palindrome.findAllPalindromesUsingBruteForceApproach(INPUT_ABABAC));
+ }
+}
diff --git a/java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java b/java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java
new file mode 100644
index 0000000000..55f932fea1
--- /dev/null
+++ b/java-strings/src/test/java/com/baeldung/string/removeleadingtrailingchar/RemoveLeadingAndTrailingZeroesUnitTest.java
@@ -0,0 +1,143 @@
+package com.baeldung.string.removeleadingtrailingchar;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.stream.Stream;
+
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class RemoveLeadingAndTrailingZeroesUnitTest {
+
+ public static Stream leadingZeroTestProvider() {
+ return Stream.of(Arguments.of("", ""), Arguments.of("abc", "abc"), Arguments.of("123", "123"), Arguments.of("0abc", "abc"), Arguments.of("0123", "123"), Arguments.of("0000123", "123"), Arguments.of("1230", "1230"), Arguments.of("01230", "1230"), Arguments.of("01", "1"),
+ Arguments.of("0001", "1"), Arguments.of("0", "0"), Arguments.of("00", "0"), Arguments.of("0000", "0"), Arguments.of("12034", "12034"), Arguments.of("1200034", "1200034"), Arguments.of("0012034", "12034"), Arguments.of("1203400", "1203400"));
+ }
+
+ public static Stream trailingZeroTestProvider() {
+ return Stream.of(Arguments.of("", ""), Arguments.of("abc", "abc"), Arguments.of("123", "123"), Arguments.of("abc0", "abc"), Arguments.of("1230", "123"), Arguments.of("1230000", "123"), Arguments.of("0123", "0123"), Arguments.of("01230", "0123"), Arguments.of("10", "1"),
+ Arguments.of("1000", "1"), Arguments.of("0", "0"), Arguments.of("00", "0"), Arguments.of("0000", "0"), Arguments.of("12034", "12034"), Arguments.of("1200034", "1200034"), Arguments.of("0012034", "0012034"), Arguments.of("1203400", "12034"));
+ }
+
+ @ParameterizedTest
+ @MethodSource("leadingZeroTestProvider")
+ public void givenTestStrings_whenRemoveLeadingZeroesWithStringBuilder_thenReturnWithoutLeadingZeroes(String input, String expected) {
+ // given
+
+ // when
+ String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithStringBuilder(input);
+
+ // then
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @ParameterizedTest
+ @MethodSource("trailingZeroTestProvider")
+ public void givenTestStrings_whenRemoveTrailingZeroesWithStringBuilder_thenReturnWithoutTrailingZeroes(String input, String expected) {
+ // given
+
+ // when
+ String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithStringBuilder(input);
+
+ // then
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @ParameterizedTest
+ @MethodSource("leadingZeroTestProvider")
+ public void givenTestStrings_whenRemoveLeadingZeroesWithSubstring_thenReturnWithoutLeadingZeroes(String input, String expected) {
+ // given
+
+ // when
+ String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithSubstring(input);
+
+ // then
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @ParameterizedTest
+ @MethodSource("trailingZeroTestProvider")
+ public void givenTestStrings_whenRemoveTrailingZeroesWithSubstring_thenReturnWithoutTrailingZeroes(String input, String expected) {
+ // given
+
+ // when
+ String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithSubstring(input);
+
+ // then
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @ParameterizedTest
+ @MethodSource("leadingZeroTestProvider")
+ public void givenTestStrings_whenRemoveLeadingZeroesWithApacheCommonsStripStart_thenReturnWithoutLeadingZeroes(String input, String expected) {
+ // given
+
+ // when
+ String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithApacheCommonsStripStart(input);
+
+ // then
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @ParameterizedTest
+ @MethodSource("trailingZeroTestProvider")
+ public void givenTestStrings_whenRemoveTrailingZeroesWithApacheCommonsStripEnd_thenReturnWithoutTrailingZeroes(String input, String expected) {
+ // given
+
+ // when
+ String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithApacheCommonsStripEnd(input);
+
+ // then
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @ParameterizedTest
+ @MethodSource("leadingZeroTestProvider")
+ public void givenTestStrings_whenRemoveLeadingZeroesWithGuavaTrimLeadingFrom_thenReturnWithoutLeadingZeroes(String input, String expected) {
+ // given
+
+ // when
+ String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithGuavaTrimLeadingFrom(input);
+
+ // then
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @ParameterizedTest
+ @MethodSource("trailingZeroTestProvider")
+ public void givenTestStrings_whenRemoveTrailingZeroesWithGuavaTrimTrailingFrom_thenReturnWithoutTrailingZeroes(String input, String expected) {
+ // given
+
+ // when
+ String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithGuavaTrimTrailingFrom(input);
+
+ // then
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @ParameterizedTest
+ @MethodSource("leadingZeroTestProvider")
+ public void givenTestStrings_whenRemoveLeadingZeroesWithRegex_thenReturnWithoutLeadingZeroes(String input, String expected) {
+ // given
+
+ // when
+ String result = RemoveLeadingAndTrailingZeroes.removeLeadingZeroesWithRegex(input);
+
+ // then
+ assertThat(result).isEqualTo(expected);
+ }
+
+ @ParameterizedTest
+ @MethodSource("trailingZeroTestProvider")
+ public void givenTestStrings_whenRemoveTrailingZeroesWithRegex_thenReturnWithoutTrailingZeroes(String input, String expected) {
+ // given
+
+ // when
+ String result = RemoveLeadingAndTrailingZeroes.removeTrailingZeroesWithRegex(input);
+
+ // then
+ assertThat(result).isEqualTo(expected);
+ }
+
+}
diff --git a/java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java b/java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java
new file mode 100644
index 0000000000..895ecc4a3b
--- /dev/null
+++ b/java-strings/src/test/java/com/baeldung/stringduplicates/RemoveDuplicateFromStringUnitTest.java
@@ -0,0 +1,82 @@
+package com.baeldung.stringduplicates;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class RemoveDuplicateFromStringUnitTest {
+
+ private final static String STR1 = "racecar";
+ private final static String STR2 = "J2ee programming";
+ private final static String STR_EMPTY = "";
+
+ private RemoveDuplicateFromString removeDuplicateFromString;
+
+ @Before
+ public void executedBeforeEach() {
+ removeDuplicateFromString = new RemoveDuplicateFromString();
+ }
+
+
+ @Test
+ public void whenUsingCharArray_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
+ String str1 = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR1);
+ String str2 = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR2);
+ String strEmpty = removeDuplicateFromString.removeDuplicatesUsingCharArray(STR_EMPTY);
+ Assert.assertEquals("", strEmpty);
+ Assert.assertEquals("ecar", str1);
+ Assert.assertEquals("J2e poraming", str2);
+ }
+
+ @Test
+ public void whenUsingLinkedHashSet_DuplicatesShouldBeRemovedAndItKeepStringOrder() {
+ String str1 = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR1);
+ String str2 = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR2);
+
+ String strEmpty = removeDuplicateFromString.removeDuplicatesUsinglinkedHashSet(STR_EMPTY);
+ Assert.assertEquals("", strEmpty);
+ Assert.assertEquals("race", str1);
+ Assert.assertEquals("J2e progamin", str2);
+ }
+
+ @Test
+ public void whenUsingSorting_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
+ String str1 = removeDuplicateFromString.removeDuplicatesUsingSorting(STR1);
+ String str2 = removeDuplicateFromString.removeDuplicatesUsingSorting(STR2);
+
+ String strEmpty = removeDuplicateFromString.removeDuplicatesUsingSorting(STR_EMPTY);
+ Assert.assertEquals("", strEmpty);
+ Assert.assertEquals("acer", str1);
+ Assert.assertEquals(" 2Jaegimnopr", str2);
+ }
+
+ @Test
+ public void whenUsingHashSet_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
+ String str1 = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR1);
+ String str2 = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR2);
+ String strEmpty = removeDuplicateFromString.removeDuplicatesUsingHashSet(STR_EMPTY);
+ Assert.assertEquals("", strEmpty);
+ Assert.assertEquals("arce", str1);
+ Assert.assertEquals(" pa2regiJmno", str2);
+ }
+
+ @Test
+ public void whenUsingIndexOf_DuplicatesShouldBeRemovedWithoutKeepingStringOrder() {
+ String str1 = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR1);
+ String str2 = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR2);
+ String strEmpty = removeDuplicateFromString.removeDuplicatesUsingIndexOf(STR_EMPTY);
+ Assert.assertEquals("", strEmpty);
+ Assert.assertEquals("ecar", str1);
+ Assert.assertEquals("J2e poraming", str2);
+ }
+
+ @Test
+ public void whenUsingJava8_DuplicatesShouldBeRemovedAndItKeepStringOrder() {
+ String str1 = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR1);
+ String str2 = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR2);
+ String strEmpty = removeDuplicateFromString.removeDuplicatesUsingDistinct(STR_EMPTY);
+ Assert.assertEquals("", strEmpty);
+ Assert.assertEquals("race", str1);
+ Assert.assertEquals("J2e progamin", str2);
+ }
+}
diff --git a/java-vavr-stream/pom.xml b/java-vavr-stream/pom.xml
index 395d2c81ba..c92f3c8742 100644
--- a/java-vavr-stream/pom.xml
+++ b/java-vavr-stream/pom.xml
@@ -5,6 +5,7 @@
com.baeldung.samples
java-vavr-stream
1.0
+ java-vavr-stream
jar
diff --git a/java-websocket/pom.xml b/java-websocket/pom.xml
index e8ff8dfc36..7ba3ca61d0 100644
--- a/java-websocket/pom.xml
+++ b/java-websocket/pom.xml
@@ -1,10 +1,10 @@
4.0.0
- com.baeldung
java-websocket
- war
0.0.1-SNAPSHOT
+ java-websocket
+ war
com.baeldung
diff --git a/javafx/pom.xml b/javafx/pom.xml
index c9c5bc294e..44e6f7e8da 100644
--- a/javafx/pom.xml
+++ b/javafx/pom.xml
@@ -3,7 +3,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
javafx
-
+ javafx
+
parent-modules
com.baeldung
diff --git a/javax-servlets/pom.xml b/javax-servlets/pom.xml
index 7b4eecd880..f00dd0ebe8 100644
--- a/javax-servlets/pom.xml
+++ b/javax-servlets/pom.xml
@@ -5,6 +5,7 @@
com.baeldung.javax-servlets
javax-servlets
1.0-SNAPSHOT
+ javax-servlets
war
diff --git a/javaxval/pom.xml b/javaxval/pom.xml
index 22f1827213..5f2690b5b4 100644
--- a/javaxval/pom.xml
+++ b/javaxval/pom.xml
@@ -1,10 +1,10 @@
4.0.0
- com.baeldung
javaxval
0.1-SNAPSHOT
-
+ javaxval
+
com.baeldung
parent-modules
diff --git a/jee-7/pom.xml b/jee-7/pom.xml
index 4f6e6a20fb..97ed2cc51d 100644
--- a/jee-7/pom.xml
+++ b/jee-7/pom.xml
@@ -1,430 +1,538 @@
-
- 4.0.0
- jee-7
- 1.0-SNAPSHOT
- war
- JavaEE 7 Arquillian Archetype Sample
+
+ 4.0.0
+ jee-7
+ 1.0-SNAPSHOT
+ jee-7
+ war
+ JavaEE 7 Arquillian Archetype Sample
-
- com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
-
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
-
-
- javax
- javaee-api
- ${javaee_api.version}
- provided
-
+
+
+ javax
+ javaee-api
+ ${javaee_api.version}
+ provided
+
-
- org.jboss.arquillian.junit
- arquillian-junit-container
- test
-
-
- org.jboss.arquillian.graphene
- graphene-webdriver
- ${graphene-webdriver.version}
- pom
- test
-
-
- com.jayway.awaitility
- awaitility
- ${awaitility.version}
- test
-
+
+ org.jboss.arquillian.junit
+ arquillian-junit-container
+ test
+
+
+ org.jboss.arquillian.graphene
+ graphene-webdriver
+ ${graphene-webdriver.version}
+ pom
+ test
+
+
+ com.jayway.awaitility
+ awaitility
+ ${awaitility.version}
+ test
+
-
- org.jboss.shrinkwrap.resolver
- shrinkwrap-resolver-impl-maven
- test
- jar
-
+
+ org.jboss.shrinkwrap.resolver
+ shrinkwrap-resolver-impl-maven
+ test
+ jar
+
-
- org.jboss.shrinkwrap.resolver
- shrinkwrap-resolver-impl-maven-archive
- test
-
-
- org.apache.httpcomponents
- httpclient
- ${httpclient.version}
-
-
- commons-io
- commons-io
- ${commons-io.version}
-
-
- com.sun.faces
- jsf-api
- ${com.sun.faces.jsf.version}
-
-
- com.sun.faces
- jsf-impl
- ${com.sun.faces.jsf.version}
-
-
- javax.servlet
- jstl
- ${jstl.version}
-
-
- javax.servlet
- javax.servlet-api
- ${javax.servlet-api.version}
-
-
- javax.servlet.jsp
- jsp-api
- ${jsp-api.version}
- provided
-
-
- taglibs
- standard
- ${taglibs.standard.version}
-
+
+ org.jboss.shrinkwrap.resolver
+ shrinkwrap-resolver-impl-maven-archive
+ test
+
+
+ org.apache.httpcomponents
+ httpclient
+ ${httpclient.version}
+
+
+ commons-io
+ commons-io
+ ${commons-io.version}
+
+
+ com.sun.faces
+ jsf-api
+ ${com.sun.faces.jsf.version}
+
+
+ com.sun.faces
+ jsf-impl
+ ${com.sun.faces.jsf.version}
+
+
+ javax.servlet
+ jstl
+ ${jstl.version}
+
+
+ javax.servlet
+ javax.servlet-api
+ ${javax.servlet-api.version}
+
+
+ javax.servlet.jsp
+ jsp-api
+ ${jsp-api.version}
+ provided
+
+
+ taglibs
+ standard
+ ${taglibs.standard.version}
+
-
- javax.mvc
- javax.mvc-api
- 20160715
-
-
- org.glassfish.ozark
- ozark
- ${ozark.version}
-
+
+ javax.mvc
+ javax.mvc-api
+ 20160715
+
+
+ org.glassfish.ozark
+ ozark
+ ${ozark.version}
+
-
- org.springframework.security
- spring-security-web
- ${org.springframework.security.version}
-
+
+ org.springframework.security
+ spring-security-web
+ ${org.springframework.security.version}
+
-
- org.springframework.security
- spring-security-config
- ${org.springframework.security.version}
-
-
- org.springframework.security
- spring-security-taglibs
- ${org.springframework.security.version}
-
-
+
+ org.springframework.security
+ spring-security-config
+ ${org.springframework.security.version}
+
+
+ org.springframework.security
+ spring-security-taglibs
+ ${org.springframework.security.version}
+
+
-
-
-
- org.apache.maven.plugins
- maven-war-plugin
- ${maven-war-plugin.version}
-
- src/main/webapp
- false
-
-
-
-
+
+ org.jboss.spec.javax.batch
+ jboss-batch-api_1.0_spec
+ 1.0.0.Final
+
+
+ org.jberet
+ jberet-core
+ 1.0.2.Final
+
+
+ org.jberet
+ jberet-support
+ 1.0.2.Final
+
+
+ org.jboss.spec.javax.transaction
+ jboss-transaction-api_1.2_spec
+ 1.0.0.Final
+
+
+ org.jboss.marshalling
+ jboss-marshalling
+ 1.4.2.Final
+
+
+ org.jboss.weld
+ weld-core
+ 2.1.1.Final
+
+
+ org.jboss.weld.se
+ weld-se
+ 2.1.1.Final
+
+
+ org.jberet
+ jberet-se
+ 1.0.2.Final
+
+
+ com.h2database
+ h2
+ 1.4.178
+
+
+ org.glassfish.jersey.containers
+ jersey-container-jetty-servlet
+ 2.22.1
+
+
-
-
-
- org.jboss.arquillian
- arquillian-bom
- ${arquillian_core.version}
- import
- pom
-
-
- org.jboss.arquillian.extension
- arquillian-drone-bom
- ${arquillian-drone-bom.version}
- pom
- import
-
-
-
+
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+ src/main/webapp
+ false
+
+
+
+
+
+
+
+ org.eclipse.m2e
+ lifecycle-mapping
+ 1.0.0
+
+
+
+
+
+
+ org.apache.maven.plugins
+
+
+ maven-pmd-plugin
+
+
+ [3.8,)
+
+
+ check
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
- wildfly-managed-arquillian
-
- true
-
-
- standalone-full.xml
- ${project.build.directory}/wildfly-${version.wildfly}
-
-
-
- io.undertow
- undertow-websockets-jsr
- ${undertow-websockets-jsr.version}
- test
-
-
- org.jboss.resteasy
- resteasy-client
- ${resteasy.version}
- test
-
-
- org.jboss.resteasy
- resteasy-jaxb-provider
- ${resteasy.version}
- test
-
-
- org.jboss.resteasy
- resteasy-json-p-provider
- ${resteasy.version}
- test
-
-
- org.wildfly
- wildfly-arquillian-container-managed
- ${wildfly.version}
- test
-
-
+
+
+
+ org.jboss.arquillian
+ arquillian-bom
+ ${arquillian_core.version}
+ import
+ pom
+
+
+ org.jboss.arquillian.extension
+ arquillian-drone-bom
+ ${arquillian-drone-bom.version}
+ pom
+ import
+
+
+
-
-
-
-
- maven-dependency-plugin
- ${maven-dependency-plugin.version}
-
- ${maven.test.skip}
-
-
-
- unpack
- process-test-classes
-
- unpack
-
-
-
-
- org.wildfly
- wildfly-dist
- ${wildfly.version}
- zip
- false
- ${project.build.directory}
-
-
-
-
-
-
-
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
- ${project.build.directory}/wildfly-${wildfly.version}
-
-
-
-
-
-
-
-
- wildfly-remote-arquillian
-
-
- io.undertow
- undertow-websockets-jsr
- ${undertow-websockets-jsr.version}
- test
-
-
- org.jboss.resteasy
- resteasy-client
- ${resteasy.version}
- test
-
-
- org.jboss.resteasy
- resteasy-jaxb-provider
- ${resteasy.version}
- test
-
-
- org.jboss.resteasy
- resteasy-json-p-provider
- ${resteasy.version}
- test
-
-
- org.wildfly
- wildfly-arquillian-container-remote
- ${wildfly.version}
- test
-
-
-
-
- glassfish-embedded-arquillian
-
-
- org.glassfish.main.extras
- glassfish-embedded-all
- ${glassfish-embedded-all.version}
- test
-
-
- org.glassfish
- javax.json
- ${javax.json.version}
- test
-
-
- org.glassfish.tyrus
- tyrus-client
- ${tyrus.version}
- test
-
-
- org.glassfish.tyrus
- tyrus-container-grizzly-client
- ${tyrus.version}
- test
-
-
- org.glassfish.jersey.core
- jersey-client
- ${jersey.version}
- test
-
-
- org.jboss.arquillian.container
- arquillian-glassfish-embedded-3.1
- ${arquillian-glassfish.version}
- test
-
-
-
-
- glassfish-remote-arquillian
-
-
- org.glassfish
- javax.json
- ${javax.json.version}
- test
-
-
- org.glassfish.tyrus
- tyrus-client
- ${tyrus.version}
- test
-
-
- org.glassfish.tyrus
- tyrus-container-grizzly-client
- ${tyrus.version}
- test
-
-
- org.glassfish.jersey.core
- jersey-client
- ${jersey.version}
- test
-
-
- org.glassfish.jersey.media
- jersey-media-json-jackson
- ${jersey.version}
- test
-
-
- org.glassfish.jersey.media
- jersey-media-json-processing
- ${jersey.version}
- test
-
-
- org.jboss.arquillian.container
- arquillian-glassfish-remote-3.1
- ${arquillian-glassfish.version}
- test
-
-
-
-
- webdriver-chrome
-
- true
-
-
- chrome
-
-
-
- webdriver-firefox
-
- firefox
-
-
-
+
+
+ wildfly-managed-arquillian
+
+ true
+
+
+ standalone-full.xml
+ ${project.build.directory}/wildfly-${version.wildfly}
+
+
+
+ io.undertow
+ undertow-websockets-jsr
+ ${undertow-websockets-jsr.version}
+ test
+
+
+ org.jboss.resteasy
+ resteasy-client
+ ${resteasy.version}
+ test
+
+
+ org.jboss.resteasy
+ resteasy-jaxb-provider
+ ${resteasy.version}
+ test
+
+
+ org.jboss.resteasy
+ resteasy-json-p-provider
+ ${resteasy.version}
+ test
+
+
+ org.wildfly
+ wildfly-arquillian-container-managed
+ ${wildfly.version}
+ test
+
+
+ sun.jdk
+ jconsole
+
+
+
+
-
-
- bintray-mvc-spec-maven
- bintray
- http://dl.bintray.com/mvc-spec/maven
-
- true
-
-
- false
-
-
-
+
+
+
+
+ maven-dependency-plugin
+ ${maven-dependency-plugin.version}
+
+ ${maven.test.skip}
+
+
+
+ unpack
+ process-test-classes
+
+ unpack
+
+
+
+
+ org.wildfly
+ wildfly-dist
+ ${wildfly.version}
+ zip
+ false
+ ${project.build.directory}
+
+
+ sun.jdk
+ jconsole
+
+
+
+
+
+
+
+
+
+ maven-surefire-plugin
+ ${maven-surefire-plugin.version}
+
+
+ ${project.build.directory}/wildfly-${wildfly.version}
+
+
+
+
+
+
+
+
+ wildfly-remote-arquillian
+
+
+ io.undertow
+ undertow-websockets-jsr
+ ${undertow-websockets-jsr.version}
+ test
+
+
+ org.jboss.resteasy
+ resteasy-client
+ ${resteasy.version}
+ test
+
+
+ org.jboss.resteasy
+ resteasy-jaxb-provider
+ ${resteasy.version}
+ test
+
+
+ org.jboss.resteasy
+ resteasy-json-p-provider
+ ${resteasy.version}
+ test
+
+
+ org.wildfly
+ wildfly-arquillian-container-remote
+ ${wildfly.version}
+ test
+
+
+ sun.jdk
+ jconsole
+
+
+
+
+
+
+ glassfish-embedded-arquillian
+
+
+ org.glassfish.main.extras
+ glassfish-embedded-all
+ ${glassfish-embedded-all.version}
+ test
+
+
+ org.glassfish
+ javax.json
+ ${javax.json.version}
+ test
+
+
+ org.glassfish.tyrus
+ tyrus-client
+ ${tyrus.version}
+ test
+
+
+ org.glassfish.tyrus
+ tyrus-container-grizzly-client
+ ${tyrus.version}
+ test
+
+
+ org.glassfish.jersey.core
+ jersey-client
+ ${jersey.version}
+ test
+
+
+ org.jboss.arquillian.container
+ arquillian-glassfish-embedded-3.1
+ ${arquillian-glassfish.version}
+ test
+
+
+
+
+ glassfish-remote-arquillian
+
+
+ org.glassfish
+ javax.json
+ ${javax.json.version}
+ test
+
+
+ org.glassfish.tyrus
+ tyrus-client
+ ${tyrus.version}
+ test
+
+
+ org.glassfish.tyrus
+ tyrus-container-grizzly-client
+ ${tyrus.version}
+ test
+
+
+ org.glassfish.jersey.core
+ jersey-client
+ ${jersey.version}
+ test
+
+
+ org.glassfish.jersey.media
+ jersey-media-json-jackson
+ ${jersey.version}
+ test
+
+
+ org.glassfish.jersey.media
+ jersey-media-json-processing
+ ${jersey.version}
+ test
+
+
+ org.jboss.arquillian.container
+ arquillian-glassfish-remote-3.1
+ ${arquillian-glassfish.version}
+ test
+
+
+
+
+ webdriver-chrome
+
+ true
+
+
+ chrome
+
+
+
+ webdriver-firefox
+
+ firefox
+
+
+
-
- 1.8
- 3.0.0
- 7.0
- 1.1.11.Final
- 8.2.1.Final
- 1.7.0
- 1.4.6.Final
- 3.0.19.Final
- 4.1.1
- 1.0.4
- 1.13
- 2.25
- 1.0.0.Final
- 2.6
- 4.2.3.RELEASE
- 2.21.0
- 1.1.2
- 2.4
- 2.2.14
- 4.5
- 2.0.1.Final
- 3.1.0
- 2.1.0.Final
- 2.8
- 1.2
- 2.2
- 20160715
-
+
+
+ bintray-mvc-spec-maven
+ bintray
+ http://dl.bintray.com/mvc-spec/maven
+
+ true
+
+
+ false
+
+
+
-
+
+ 1.8
+ 3.0.0
+ 7.0
+ 1.1.11.Final
+ 8.2.1.Final
+ 1.7.0
+ 1.4.6.Final
+ 3.0.19.Final
+ 4.1.1
+ 1.0.4
+ 1.13
+ 2.25
+ 1.0.0.Final
+ 2.6
+ 4.2.3.RELEASE
+ 2.21.0
+ 1.1.2
+ 2.4
+ 2.2.14
+ 4.5
+ 2.0.1.Final
+ 3.1.0
+ 2.1.0.Final
+ 2.8
+ 1.2
+ 2.2
+ 20160715
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/ChunkExceptionSkipReadListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/ChunkExceptionSkipReadListener.java
new file mode 100644
index 0000000000..ce47de66af
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/ChunkExceptionSkipReadListener.java
@@ -0,0 +1,11 @@
+package com.baeldung.batch.understanding;
+
+import javax.batch.api.chunk.listener.SkipReadListener;
+import javax.inject.Named;
+
+@Named
+public class ChunkExceptionSkipReadListener implements SkipReadListener {
+ @Override
+ public void onSkipReadItem(Exception e) throws Exception {
+ }
+}
\ No newline at end of file
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/CustomCheckPoint.java b/jee-7/src/main/java/com/baeldung/batch/understanding/CustomCheckPoint.java
new file mode 100644
index 0000000000..fe6759b365
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/CustomCheckPoint.java
@@ -0,0 +1,12 @@
+package com.baeldung.batch.understanding;
+
+import javax.batch.api.chunk.AbstractCheckpointAlgorithm;
+import javax.inject.Named;
+
+@Named
+public class CustomCheckPoint extends AbstractCheckpointAlgorithm {
+ @Override
+ public boolean isReadyToCheckpoint() throws Exception {
+ return SimpleChunkItemReader.COUNT % 5 == 0;
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/DeciderJobSequence.java b/jee-7/src/main/java/com/baeldung/batch/understanding/DeciderJobSequence.java
new file mode 100644
index 0000000000..6cc2012f23
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/DeciderJobSequence.java
@@ -0,0 +1,14 @@
+package com.baeldung.batch.understanding;
+
+import javax.batch.api.Decider;
+import javax.batch.runtime.StepExecution;
+import javax.inject.Named;
+
+@Named
+public class DeciderJobSequence implements Decider {
+ @Override
+ public String decide(StepExecution[] ses) throws Exception {
+ return "nothing";
+ }
+
+}
\ No newline at end of file
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/InjectSimpleBatchLet.java b/jee-7/src/main/java/com/baeldung/batch/understanding/InjectSimpleBatchLet.java
new file mode 100644
index 0000000000..93eb20708d
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/InjectSimpleBatchLet.java
@@ -0,0 +1,20 @@
+package com.baeldung.batch.understanding;
+
+import javax.batch.api.AbstractBatchlet;
+import javax.batch.api.BatchProperty;
+import javax.batch.runtime.BatchStatus;
+import javax.inject.Inject;
+import javax.inject.Named;
+
+@Named
+public class InjectSimpleBatchLet extends AbstractBatchlet {
+ @Inject
+ @BatchProperty(name = "name")
+ private String nameString;
+
+ @Override
+ public String process() throws Exception {
+ System.out.println("Value passed in = " + nameString);
+ return BatchStatus.COMPLETED.toString();
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleBatchLet.java b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleBatchLet.java
new file mode 100644
index 0000000000..6a367b064b
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleBatchLet.java
@@ -0,0 +1,13 @@
+package com.baeldung.batch.understanding;
+
+import javax.batch.api.AbstractBatchlet;
+import javax.batch.runtime.BatchStatus;
+import javax.inject.Named;
+
+@Named
+public class SimpleBatchLet extends AbstractBatchlet {
+ @Override
+ public String process() throws Exception {
+ return BatchStatus.FAILED.toString();
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemProcessor.java b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemProcessor.java
new file mode 100644
index 0000000000..3f8166b6d8
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemProcessor.java
@@ -0,0 +1,12 @@
+package com.baeldung.batch.understanding;
+
+import javax.batch.api.chunk.ItemProcessor;
+import javax.inject.Named;
+
+@Named
+public class SimpleChunkItemProcessor implements ItemProcessor {
+ @Override
+ public Integer processItem(Object t) {
+ return ((Integer) t).intValue() % 2 == 0 ? null : ((Integer) t).intValue();
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemReader.java b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemReader.java
new file mode 100644
index 0000000000..10f81d95d0
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemReader.java
@@ -0,0 +1,27 @@
+package com.baeldung.batch.understanding;
+
+import java.io.Serializable;
+import java.util.StringTokenizer;
+import javax.batch.api.chunk.AbstractItemReader;
+import javax.inject.Named;
+
+@Named
+public class SimpleChunkItemReader extends AbstractItemReader {
+ private StringTokenizer tokens;
+ public static int COUNT = 0;
+
+ @Override
+ public Integer readItem() throws Exception {
+ if (tokens.hasMoreTokens()) {
+ COUNT++;
+ String tempTokenize = tokens.nextToken();
+ return Integer.valueOf(tempTokenize);
+ }
+ return null;
+ }
+
+ @Override
+ public void open(Serializable checkpoint) throws Exception {
+ tokens = new StringTokenizer("1,2,3,4,5,6,7,8,9,10", ",");
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemReaderError.java b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemReaderError.java
new file mode 100644
index 0000000000..92096d0571
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkItemReaderError.java
@@ -0,0 +1,31 @@
+package com.baeldung.batch.understanding;
+
+import java.io.Serializable;
+import java.util.StringTokenizer;
+
+import javax.batch.api.chunk.AbstractItemReader;
+import javax.inject.Named;
+
+@Named
+public class SimpleChunkItemReaderError extends AbstractItemReader {
+ private StringTokenizer tokens;
+ public static int COUNT = 0;
+
+ @Override
+ public Integer readItem() throws Exception {
+ if (tokens.hasMoreTokens()) {
+ COUNT++;
+ int token = Integer.valueOf(tokens.nextToken());
+ if (token == 3) {
+ throw new RuntimeException("Something happened");
+ }
+ return Integer.valueOf(token);
+ }
+ return null;
+ }
+
+ @Override
+ public void open(Serializable checkpoint) throws Exception {
+ tokens = new StringTokenizer("1,2,3,4,5,6,7,8,9,10", ",");
+ }
+}
\ No newline at end of file
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkWriter.java b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkWriter.java
new file mode 100644
index 0000000000..909596766d
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/SimpleChunkWriter.java
@@ -0,0 +1,13 @@
+package com.baeldung.batch.understanding;
+
+import java.util.List;
+
+import javax.batch.api.chunk.AbstractItemWriter;
+import javax.inject.Named;
+
+@Named
+public class SimpleChunkWriter extends AbstractItemWriter {
+ @Override
+ public void writeItems(List items) throws Exception {
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyInputRecord.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyInputRecord.java
new file mode 100644
index 0000000000..e813a699c2
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyInputRecord.java
@@ -0,0 +1,41 @@
+package com.baeldung.batch.understanding.exception;
+
+import java.io.Serializable;
+
+public class MyInputRecord implements Serializable {
+ private int id;
+
+ public MyInputRecord(int id) {
+ this.id = id;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+
+ MyInputRecord that = (MyInputRecord) o;
+
+ return id == that.id;
+ }
+
+ @Override
+ public int hashCode() {
+ return id;
+ }
+
+ @Override
+ public String toString() {
+ return "MyInputRecord: " + id;
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemProcessor.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemProcessor.java
new file mode 100644
index 0000000000..4427a1f548
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemProcessor.java
@@ -0,0 +1,15 @@
+package com.baeldung.batch.understanding.exception;
+
+import javax.batch.api.chunk.ItemProcessor;
+import javax.inject.Named;
+
+@Named
+public class MyItemProcessor implements ItemProcessor {
+ @Override
+ public Object processItem(Object t) {
+ if (((MyInputRecord) t).getId() == 6) {
+ throw new NullPointerException();
+ }
+ return new MyOutputRecord(((MyInputRecord) t).getId());
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemReader.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemReader.java
new file mode 100644
index 0000000000..dd1876ab7d
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemReader.java
@@ -0,0 +1,42 @@
+package com.baeldung.batch.understanding.exception;
+
+import javax.batch.api.chunk.AbstractItemReader;
+import javax.inject.Named;
+import java.io.Serializable;
+import java.util.StringTokenizer;
+
+@Named
+public class MyItemReader extends AbstractItemReader {
+ private StringTokenizer tokens;
+ private MyInputRecord lastElement;
+ private boolean alreadyFailed;
+
+ @Override
+ public void open(Serializable checkpoint) {
+ tokens = new StringTokenizer("1,2,3,4,5,6,7,8,9,10", ",");
+ if (checkpoint != null) {
+ while (!Integer.valueOf(tokens.nextToken())
+ .equals(((MyInputRecord) checkpoint).getId())) {
+ }
+ }
+ }
+
+ @Override
+ public Object readItem() {
+ if (tokens.hasMoreTokens()) {
+ int token = Integer.valueOf(tokens.nextToken());
+ if (token == 5 && !alreadyFailed) {
+ alreadyFailed = true;
+ throw new IllegalArgumentException("Could not read record");
+ }
+ lastElement = new MyInputRecord(token);
+ return lastElement;
+ }
+ return null;
+ }
+
+ @Override
+ public Serializable checkpointInfo() throws Exception {
+ return lastElement;
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemWriter.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemWriter.java
new file mode 100644
index 0000000000..4e80d86d44
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyItemWriter.java
@@ -0,0 +1,19 @@
+
+package com.baeldung.batch.understanding.exception;
+
+import javax.batch.api.chunk.AbstractItemWriter;
+import javax.inject.Named;
+import java.util.List;
+
+@Named
+public class MyItemWriter extends AbstractItemWriter {
+ private static int retries = 0;
+
+ @Override
+ public void writeItems(List list) {
+ if (retries <= 3 && list.contains(new MyOutputRecord(8))) {
+ retries++;
+ throw new UnsupportedOperationException();
+ }
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyOutputRecord.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyOutputRecord.java
new file mode 100644
index 0000000000..8f18fca7ba
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyOutputRecord.java
@@ -0,0 +1,39 @@
+package com.baeldung.batch.understanding.exception;
+
+import java.io.Serializable;
+
+public class MyOutputRecord implements Serializable {
+ private int id;
+
+ public MyOutputRecord(int id) {
+ this.id = id;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ MyOutputRecord that = (MyOutputRecord) o;
+
+ return id == that.id;
+ }
+
+ @Override
+ public int hashCode() {
+ return id;
+ }
+
+ @Override
+ public String toString() {
+ return "MyOutputRecord: " + id;
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryProcessorListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryProcessorListener.java
new file mode 100644
index 0000000000..3bd35820c3
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryProcessorListener.java
@@ -0,0 +1,11 @@
+package com.baeldung.batch.understanding.exception;
+
+import javax.batch.api.chunk.listener.RetryProcessListener;
+import javax.inject.Named;
+
+@Named
+public class MyRetryProcessorListener implements RetryProcessListener {
+ @Override
+ public void onRetryProcessException(Object item, Exception ex) throws Exception {
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryReadListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryReadListener.java
new file mode 100644
index 0000000000..5c4f56b75d
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryReadListener.java
@@ -0,0 +1,11 @@
+package com.baeldung.batch.understanding.exception;
+
+import javax.batch.api.chunk.listener.RetryReadListener;
+import javax.inject.Named;
+
+@Named
+public class MyRetryReadListener implements RetryReadListener {
+ @Override
+ public void onRetryReadException(Exception ex) throws Exception {
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryWriteListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryWriteListener.java
new file mode 100644
index 0000000000..a8683d86a9
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MyRetryWriteListener.java
@@ -0,0 +1,12 @@
+package com.baeldung.batch.understanding.exception;
+
+import javax.batch.api.chunk.listener.RetryWriteListener;
+import javax.inject.Named;
+import java.util.List;
+
+@Named
+public class MyRetryWriteListener implements RetryWriteListener {
+ @Override
+ public void onRetryWriteException(List items, Exception ex) throws Exception {
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipProcessorListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipProcessorListener.java
new file mode 100644
index 0000000000..74f7565cf7
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipProcessorListener.java
@@ -0,0 +1,11 @@
+package com.baeldung.batch.understanding.exception;
+
+import javax.batch.api.chunk.listener.SkipProcessListener;
+import javax.inject.Named;
+
+@Named
+public class MySkipProcessorListener implements SkipProcessListener {
+ @Override
+ public void onSkipProcessItem(Object t, Exception e) throws Exception {
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipReadListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipReadListener.java
new file mode 100644
index 0000000000..aecaf93e75
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipReadListener.java
@@ -0,0 +1,11 @@
+package com.baeldung.batch.understanding.exception;
+
+import javax.batch.api.chunk.listener.SkipReadListener;
+import javax.inject.Named;
+
+@Named
+public class MySkipReadListener implements SkipReadListener {
+ @Override
+ public void onSkipReadItem(Exception e) throws Exception {
+ }
+}
diff --git a/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipWriteListener.java b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipWriteListener.java
new file mode 100644
index 0000000000..928773b61d
--- /dev/null
+++ b/jee-7/src/main/java/com/baeldung/batch/understanding/exception/MySkipWriteListener.java
@@ -0,0 +1,13 @@
+package com.baeldung.batch.understanding.exception;
+
+import javax.batch.api.chunk.listener.SkipWriteListener;
+import javax.inject.Named;
+import java.util.List;
+
+@Named
+public class MySkipWriteListener implements SkipWriteListener {
+ @Override
+ public void onSkipWriteItem(List list, Exception e) throws Exception {
+ list.remove(new MyOutputRecord(2));
+ }
+}
diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/customCheckPoint.xml b/jee-7/src/main/resources/META-INF/batch-jobs/customCheckPoint.xml
new file mode 100644
index 0000000000..b0f327dd39
--- /dev/null
+++ b/jee-7/src/main/resources/META-INF/batch-jobs/customCheckPoint.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/decideJobSequence.xml b/jee-7/src/main/resources/META-INF/batch-jobs/decideJobSequence.xml
new file mode 100644
index 0000000000..4905586fb9
--- /dev/null
+++ b/jee-7/src/main/resources/META-INF/batch-jobs/decideJobSequence.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/flowJobSequence.xml b/jee-7/src/main/resources/META-INF/batch-jobs/flowJobSequence.xml
new file mode 100644
index 0000000000..207a9242b1
--- /dev/null
+++ b/jee-7/src/main/resources/META-INF/batch-jobs/flowJobSequence.xml
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/injectionSimpleBatchLet.xml b/jee-7/src/main/resources/META-INF/batch-jobs/injectionSimpleBatchLet.xml
new file mode 100644
index 0000000000..d152f063f6
--- /dev/null
+++ b/jee-7/src/main/resources/META-INF/batch-jobs/injectionSimpleBatchLet.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/partitionSimpleBatchLet.xml b/jee-7/src/main/resources/META-INF/batch-jobs/partitionSimpleBatchLet.xml
new file mode 100644
index 0000000000..76c64ee899
--- /dev/null
+++ b/jee-7/src/main/resources/META-INF/batch-jobs/partitionSimpleBatchLet.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/simpleBatchLet.xml b/jee-7/src/main/resources/META-INF/batch-jobs/simpleBatchLet.xml
new file mode 100644
index 0000000000..9c707de8a4
--- /dev/null
+++ b/jee-7/src/main/resources/META-INF/batch-jobs/simpleBatchLet.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/simpleChunk.xml b/jee-7/src/main/resources/META-INF/batch-jobs/simpleChunk.xml
new file mode 100644
index 0000000000..b2b15b7bd9
--- /dev/null
+++ b/jee-7/src/main/resources/META-INF/batch-jobs/simpleChunk.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/simpleErrorChunk.xml b/jee-7/src/main/resources/META-INF/batch-jobs/simpleErrorChunk.xml
new file mode 100644
index 0000000000..743fcafd65
--- /dev/null
+++ b/jee-7/src/main/resources/META-INF/batch-jobs/simpleErrorChunk.xml
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/simpleErrorSkipChunk.xml b/jee-7/src/main/resources/META-INF/batch-jobs/simpleErrorSkipChunk.xml
new file mode 100644
index 0000000000..2fafb83cc7
--- /dev/null
+++ b/jee-7/src/main/resources/META-INF/batch-jobs/simpleErrorSkipChunk.xml
@@ -0,0 +1,26 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/simpleJobSequence.xml b/jee-7/src/main/resources/META-INF/batch-jobs/simpleJobSequence.xml
new file mode 100644
index 0000000000..7110db7f23
--- /dev/null
+++ b/jee-7/src/main/resources/META-INF/batch-jobs/simpleJobSequence.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/main/resources/META-INF/batch-jobs/splitJobSequence.xml b/jee-7/src/main/resources/META-INF/batch-jobs/splitJobSequence.xml
new file mode 100644
index 0000000000..0a9ea97dc7
--- /dev/null
+++ b/jee-7/src/main/resources/META-INF/batch-jobs/splitJobSequence.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/main/resources/META-INF/beans.xml b/jee-7/src/main/resources/META-INF/beans.xml
new file mode 100644
index 0000000000..ae0f4bf2ee
--- /dev/null
+++ b/jee-7/src/main/resources/META-INF/beans.xml
@@ -0,0 +1,8 @@
+
+
+
\ No newline at end of file
diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/BatchTestHelper.java b/jee-7/src/test/java/com/baeldung/batch/understanding/BatchTestHelper.java
new file mode 100644
index 0000000000..5060bd9b91
--- /dev/null
+++ b/jee-7/src/test/java/com/baeldung/batch/understanding/BatchTestHelper.java
@@ -0,0 +1,79 @@
+package com.baeldung.batch.understanding;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.batch.runtime.BatchRuntime;
+import javax.batch.runtime.BatchStatus;
+import javax.batch.runtime.JobExecution;
+import javax.batch.runtime.Metric;
+
+public class BatchTestHelper {
+ private static final int MAX_TRIES = 40;
+ private static final int THREAD_SLEEP = 1000;
+
+ private BatchTestHelper() {
+ throw new UnsupportedOperationException();
+ }
+
+ public static JobExecution keepTestAlive(JobExecution jobExecution) throws InterruptedException {
+ int maxTries = 0;
+ while (!jobExecution.getBatchStatus()
+ .equals(BatchStatus.COMPLETED)) {
+ if (maxTries < MAX_TRIES) {
+ maxTries++;
+ Thread.sleep(THREAD_SLEEP);
+ jobExecution = BatchRuntime.getJobOperator()
+ .getJobExecution(jobExecution.getExecutionId());
+ } else {
+ break;
+ }
+ }
+ Thread.sleep(THREAD_SLEEP);
+ return jobExecution;
+ }
+
+ public static JobExecution keepTestFailed(JobExecution jobExecution) throws InterruptedException {
+ int maxTries = 0;
+ while (!jobExecution.getBatchStatus()
+ .equals(BatchStatus.FAILED)) {
+ if (maxTries < MAX_TRIES) {
+ maxTries++;
+ Thread.sleep(THREAD_SLEEP);
+ jobExecution = BatchRuntime.getJobOperator()
+ .getJobExecution(jobExecution.getExecutionId());
+ } else {
+ break;
+ }
+ }
+ Thread.sleep(THREAD_SLEEP);
+
+ return jobExecution;
+ }
+
+ public static JobExecution keepTestStopped(JobExecution jobExecution) throws InterruptedException {
+ int maxTries = 0;
+ while (!jobExecution.getBatchStatus()
+ .equals(BatchStatus.STOPPED)) {
+ if (maxTries < MAX_TRIES) {
+ maxTries++;
+ Thread.sleep(THREAD_SLEEP);
+ jobExecution = BatchRuntime.getJobOperator()
+ .getJobExecution(jobExecution.getExecutionId());
+ } else {
+ break;
+ }
+ }
+ Thread.sleep(THREAD_SLEEP);
+ return jobExecution;
+ }
+
+ public static Map getMetricsMap(Metric[] metrics) {
+ Map metricsMap = new HashMap<>();
+ for (Metric metric : metrics) {
+ metricsMap.put(metric.getType(), metric.getValue());
+ }
+ return metricsMap;
+ }
+
+}
diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java
new file mode 100644
index 0000000000..a9488c5c03
--- /dev/null
+++ b/jee-7/src/test/java/com/baeldung/batch/understanding/CustomCheckPointUnitTest.java
@@ -0,0 +1,33 @@
+package com.baeldung.batch.understanding;
+
+import static org.junit.jupiter.api.Assertions.*;
+import java.util.Map;
+import java.util.Properties;
+import javax.batch.operations.JobOperator;
+import javax.batch.runtime.BatchRuntime;
+import javax.batch.runtime.BatchStatus;
+import javax.batch.runtime.JobExecution;
+import javax.batch.runtime.Metric;
+import javax.batch.runtime.StepExecution;
+import com.baeldung.batch.understanding.BatchTestHelper;
+
+import org.junit.jupiter.api.Test;
+
+class CustomCheckPointUnitTest {
+ @Test
+ public void givenChunk_whenCustomCheckPoint_thenCommitCount_3() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("customCheckPoint", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobExecution = BatchTestHelper.keepTestAlive(jobExecution);
+ for (StepExecution stepExecution : jobOperator.getStepExecutions(executionId)) {
+ if (stepExecution.getStepName()
+ .equals("firstChunkStep")) {
+ Map metricsMap = BatchTestHelper.getMetricsMap(stepExecution.getMetrics());
+ assertEquals(3L, metricsMap.get(Metric.MetricType.COMMIT_COUNT)
+ .longValue());
+ }
+ }
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);
+ }
+}
diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java
new file mode 100644
index 0000000000..7c5e8d0b78
--- /dev/null
+++ b/jee-7/src/test/java/com/baeldung/batch/understanding/JobSequenceUnitTest.java
@@ -0,0 +1,74 @@
+package com.baeldung.batch.understanding;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+
+import javax.batch.operations.JobOperator;
+import javax.batch.runtime.BatchRuntime;
+import javax.batch.runtime.BatchStatus;
+import javax.batch.runtime.JobExecution;
+import javax.batch.runtime.StepExecution;
+
+import org.junit.jupiter.api.Test;
+
+class JobSequenceUnitTest {
+ @Test
+ public void givenTwoSteps_thenBatch_CompleteWithSuccess() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("simpleJobSequence", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobExecution = BatchTestHelper.keepTestAlive(jobExecution);
+ assertEquals(2 , jobOperator.getStepExecutions(executionId).size());
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);
+ }
+
+ @Test
+ public void givenFlow_thenBatch_CompleteWithSuccess() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("flowJobSequence", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobExecution = BatchTestHelper.keepTestAlive(jobExecution);
+ assertEquals(3 , jobOperator.getStepExecutions(executionId).size());
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);
+ }
+
+ @Test
+ public void givenDecider_thenBatch_CompleteWithSuccess() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("decideJobSequence", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobExecution = BatchTestHelper.keepTestAlive(jobExecution);
+ List stepExecutions = jobOperator.getStepExecutions(executionId);
+ List executedSteps = new ArrayList<>();
+ for (StepExecution stepExecution : stepExecutions) {
+ executedSteps.add(stepExecution.getStepName());
+ }
+ assertEquals(2, jobOperator.getStepExecutions(executionId).size());
+ assertArrayEquals(new String[] { "firstBatchStepStep1", "firstBatchStepStep3" }, executedSteps.toArray());
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);
+ }
+
+ @Test
+ public void givenSplit_thenBatch_CompletesWithSuccess() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("splitJobSequence", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobExecution = BatchTestHelper.keepTestAlive(jobExecution);
+ List stepExecutions = jobOperator.getStepExecutions(executionId);
+ List executedSteps = new ArrayList<>();
+ for (StepExecution stepExecution : stepExecutions) {
+ executedSteps.add(stepExecution.getStepName());
+ }
+ assertEquals(3, stepExecutions.size());
+ assertTrue(executedSteps.contains("splitJobSequenceStep1"));
+ assertTrue(executedSteps.contains("splitJobSequenceStep2"));
+ assertTrue(executedSteps.contains("splitJobSequenceStep3"));
+ assertTrue(executedSteps.get(0).equals("splitJobSequenceStep1") || executedSteps.get(0).equals("splitJobSequenceStep2"));
+ assertTrue(executedSteps.get(1).equals("splitJobSequenceStep1") || executedSteps.get(1).equals("splitJobSequenceStep2"));
+ assertTrue(executedSteps.get(2).equals("splitJobSequenceStep3"));
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);
+ }
+}
diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java
new file mode 100644
index 0000000000..485c997cc6
--- /dev/null
+++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleBatchLetUnitTest.java
@@ -0,0 +1,68 @@
+package com.baeldung.batch.understanding;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.batch.operations.JobOperator;
+import javax.batch.runtime.BatchRuntime;
+import javax.batch.runtime.BatchStatus;
+import javax.batch.runtime.JobExecution;
+import javax.batch.runtime.Metric;
+import javax.batch.runtime.StepExecution;
+
+import org.junit.jupiter.api.Test;
+
+class SimpleBatchLetUnitTest {
+ @Test
+ public void givenBatchLet_thenBatch_CompleteWithSuccess() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("simpleBatchLet", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobExecution = BatchTestHelper.keepTestAlive(jobExecution);
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);
+ }
+
+ @Test
+ public void givenBatchLetProperty_thenBatch_CompleteWithSuccess() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("injectionSimpleBatchLet", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobExecution = BatchTestHelper.keepTestAlive(jobExecution);
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);
+ }
+
+ @Test
+ public void givenBatchLetPartition_thenBatch_CompleteWithSuccess() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("partitionSimpleBatchLet", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobExecution = BatchTestHelper.keepTestAlive(jobExecution);
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);
+ }
+
+ @Test
+ public void givenBatchLetStarted_whenStopped_thenBatchStopped() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("simpleBatchLet", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobOperator.stop(executionId);
+ jobExecution = BatchTestHelper.keepTestStopped(jobExecution);
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.STOPPED);
+ }
+
+ @Test
+ public void givenBatchLetStopped_whenRestarted_thenBatchCompletesSuccess() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("simpleBatchLet", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobOperator.stop(executionId);
+ jobExecution = BatchTestHelper.keepTestStopped(jobExecution);
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.STOPPED);
+ executionId = jobOperator.restart(jobExecution.getExecutionId(), new Properties());
+ jobExecution = BatchTestHelper.keepTestAlive(jobOperator.getJobExecution(executionId));
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);
+ }
+}
diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java
new file mode 100644
index 0000000000..57c794ba00
--- /dev/null
+++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleChunkUnitTest.java
@@ -0,0 +1,67 @@
+package com.baeldung.batch.understanding;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import javax.batch.operations.JobOperator;
+import javax.batch.runtime.BatchRuntime;
+import javax.batch.runtime.BatchStatus;
+import javax.batch.runtime.JobExecution;
+import javax.batch.runtime.Metric;
+import javax.batch.runtime.StepExecution;
+
+import org.junit.jupiter.api.Test;
+
+class SimpleChunkUnitTest {
+ @Test
+ public void givenChunk_thenBatch_CompletesWithSucess() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("simpleChunk", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobExecution = BatchTestHelper.keepTestAlive(jobExecution);
+ List stepExecutions = jobOperator.getStepExecutions(executionId);
+ for (StepExecution stepExecution : stepExecutions) {
+ if (stepExecution.getStepName()
+ .equals("firstChunkStep")) {
+ Map metricsMap = BatchTestHelper.getMetricsMap(stepExecution.getMetrics());
+ assertEquals(10L, metricsMap.get(Metric.MetricType.READ_COUNT)
+ .longValue());
+ assertEquals(10L / 2L, metricsMap.get(Metric.MetricType.WRITE_COUNT)
+ .longValue());
+ assertEquals(10L / 3 + (10L % 3 > 0 ? 1 : 0), metricsMap.get(Metric.MetricType.COMMIT_COUNT)
+ .longValue());
+ }
+ }
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);
+ }
+
+ @Test
+ public void givenChunk__thenBatch_fetchInformation() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("simpleChunk", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobExecution = BatchTestHelper.keepTestAlive(jobExecution);
+ // job name contains simpleBatchLet which is the name of the file
+ assertTrue(jobOperator.getJobNames().contains("simpleChunk"));
+ // job parameters are empty
+ assertTrue(jobOperator.getParameters(executionId).isEmpty());
+ // step execution information
+ List stepExecutions = jobOperator.getStepExecutions(executionId);
+ assertEquals("firstChunkStep", stepExecutions.get(0).getStepName());
+ // finding out batch status
+ assertEquals(BatchStatus.COMPLETED, stepExecutions.get(0).getBatchStatus());
+ Map metricTest = BatchTestHelper.getMetricsMap(stepExecutions.get(0).getMetrics());
+ assertEquals(10L, metricTest.get(Metric.MetricType.READ_COUNT).longValue());
+ assertEquals(5L, metricTest.get(Metric.MetricType.FILTER_COUNT).longValue());
+ assertEquals(4L, metricTest.get(Metric.MetricType.COMMIT_COUNT).longValue());
+ assertEquals(5L, metricTest.get(Metric.MetricType.WRITE_COUNT).longValue());
+ assertEquals(0L, metricTest.get(Metric.MetricType.READ_SKIP_COUNT).longValue());
+ assertEquals(0L, metricTest.get(Metric.MetricType.WRITE_SKIP_COUNT).longValue());
+ assertEquals(0L, metricTest.get(Metric.MetricType.PROCESS_SKIP_COUNT).longValue());
+ assertEquals(0L, metricTest.get(Metric.MetricType.ROLLBACK_COUNT).longValue());
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);
+ }
+}
diff --git a/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java
new file mode 100644
index 0000000000..0f6d068888
--- /dev/null
+++ b/jee-7/src/test/java/com/baeldung/batch/understanding/SimpleErrorChunkUnitTest.java
@@ -0,0 +1,48 @@
+package com.baeldung.batch.understanding;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import javax.batch.operations.JobOperator;
+import javax.batch.runtime.BatchRuntime;
+import javax.batch.runtime.BatchStatus;
+import javax.batch.runtime.JobExecution;
+import javax.batch.runtime.Metric.MetricType;
+import javax.batch.runtime.StepExecution;
+
+import org.junit.jupiter.api.Test;
+
+class SimpleErrorChunkUnitTest {
+
+ @Test
+ public void givenChunkError_thenBatch_CompletesWithFailed() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("simpleErrorChunk", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobExecution = BatchTestHelper.keepTestFailed(jobExecution);
+ System.out.println(jobExecution.getBatchStatus());
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.FAILED);
+ }
+
+ @Test
+ public void givenChunkError_thenErrorSkipped_CompletesWithSuccess() throws Exception {
+ JobOperator jobOperator = BatchRuntime.getJobOperator();
+ Long executionId = jobOperator.start("simpleErrorSkipChunk", new Properties());
+ JobExecution jobExecution = jobOperator.getJobExecution(executionId);
+ jobExecution = BatchTestHelper.keepTestAlive(jobExecution);
+ List stepExecutions = jobOperator.getStepExecutions(executionId);
+ for (StepExecution stepExecution : stepExecutions) {
+ if (stepExecution.getStepName()
+ .equals("errorStep")) {
+ Map metricsMap = BatchTestHelper.getMetricsMap(stepExecution.getMetrics());
+ long skipCount = metricsMap.get(MetricType.PROCESS_SKIP_COUNT)
+ .longValue();
+ assertTrue("Skip count=" + skipCount, skipCount == 1l || skipCount == 2l);
+ }
+ }
+ assertEquals(jobExecution.getBatchStatus(), BatchStatus.COMPLETED);
+ }
+}
diff --git a/jenkins/hello-world/pom.xml b/jenkins/hello-world/pom.xml
index fb2154c7ad..f00a551173 100644
--- a/jenkins/hello-world/pom.xml
+++ b/jenkins/hello-world/pom.xml
@@ -2,10 +2,10 @@
4.0.0
- jenkins-hello-world
+ hello-world
1.0-SNAPSHOT
+ hello-world
hpi
- Hello World Plugin
A sample Jenkins Hello World plugin
diff --git a/jersey/pom.xml b/jersey/pom.xml
index b55bdc5330..a3adb4cf5a 100644
--- a/jersey/pom.xml
+++ b/jersey/pom.xml
@@ -2,9 +2,9 @@
4.0.0
- com.baeldung
jersey
0.0.1-SNAPSHOT
+ jersey
war
diff --git a/jhipster/jhipster-microservice/pom.xml b/jhipster/jhipster-microservice/pom.xml
index 4a60e47f87..051d5f70b7 100644
--- a/jhipster/jhipster-microservice/pom.xml
+++ b/jhipster/jhipster-microservice/pom.xml
@@ -3,9 +3,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jhipster-microservice
+ jhipster-microservice
pom
- JHipster Microservice
-
+
jhipster
com.baeldung.jhipster
diff --git a/jhipster/jhipster-monolithic/pom.xml b/jhipster/jhipster-monolithic/pom.xml
index e242668759..12dead99df 100644
--- a/jhipster/jhipster-monolithic/pom.xml
+++ b/jhipster/jhipster-monolithic/pom.xml
@@ -3,6 +3,7 @@
4.0.0
jhipster-monolithic
war
+ jhipster-monolithic
JHipster Monolithic Application
diff --git a/jni/pom.xml b/jni/pom.xml
index d4cc409d33..4850e07ed7 100644
--- a/jni/pom.xml
+++ b/jni/pom.xml
@@ -2,7 +2,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jni
-
+ jni
+
com.baeldung
parent-modules
diff --git a/jsf/pom.xml b/jsf/pom.xml
index 2ac8a9f7c2..fc6d4a0ee2 100644
--- a/jsf/pom.xml
+++ b/jsf/pom.xml
@@ -4,6 +4,7 @@
4.0.0
jsf
0.1-SNAPSHOT
+ jsf
war
diff --git a/json/pom.xml b/json/pom.xml
index b688baec06..fce2d26db5 100644
--- a/json/pom.xml
+++ b/json/pom.xml
@@ -4,7 +4,8 @@
org.baeldung
json
0.0.1-SNAPSHOT
-
+ json
+
com.baeldung
parent-modules
@@ -32,6 +33,16 @@
org.json
json
20171018
+
+
+ com.google.code.gson
+ gson
+ 2.8.5
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ 2.9.7
javax.json.bind
diff --git a/json/src/main/java/com/baeldung/escape/JsonEscape.java b/json/src/main/java/com/baeldung/escape/JsonEscape.java
new file mode 100644
index 0000000000..1e5f0d87cb
--- /dev/null
+++ b/json/src/main/java/com/baeldung/escape/JsonEscape.java
@@ -0,0 +1,41 @@
+package com.baeldung.escape;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.gson.JsonObject;
+import org.json.JSONObject;
+
+class JsonEscape {
+
+ String escapeJson(String input) {
+ JSONObject jsonObject = new JSONObject();
+ jsonObject.put("message", input);
+ return jsonObject.toString();
+ }
+
+ String escapeGson(String input) {
+ JsonObject gsonObject = new JsonObject();
+ gsonObject.addProperty("message", input);
+ return gsonObject.toString();
+ }
+
+ String escapeJackson(String input) throws JsonProcessingException {
+ return new ObjectMapper().writeValueAsString(new Payload(input));
+ }
+
+ static class Payload {
+ String message;
+
+ Payload(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+ }
+}
diff --git a/json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java b/json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java
new file mode 100644
index 0000000000..e959fa227b
--- /dev/null
+++ b/json/src/test/java/com/baeldung/escape/JsonEscapeUnitTest.java
@@ -0,0 +1,36 @@
+package com.baeldung.escape;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class JsonEscapeUnitTest {
+
+ private JsonEscape testedInstance;
+ private static final String EXPECTED = "{\"message\":\"Hello \\\"World\\\"\"}";
+
+ @BeforeEach
+ void setUp() {
+ testedInstance = new JsonEscape();
+ }
+
+ @Test
+ void escapeJson() {
+ String actual = testedInstance.escapeJson("Hello \"World\"");
+ assertEquals(EXPECTED, actual);
+ }
+
+ @Test
+ void escapeGson() {
+ String actual = testedInstance.escapeGson("Hello \"World\"");
+ assertEquals(EXPECTED, actual);
+ }
+
+ @Test
+ void escapeJackson() throws JsonProcessingException {
+ String actual = testedInstance.escapeJackson("Hello \"World\"");
+ assertEquals(EXPECTED, actual);
+ }
+}
\ No newline at end of file
diff --git a/jsoup/pom.xml b/jsoup/pom.xml
index 2704d7bc00..f6e25e7a23 100644
--- a/jsoup/pom.xml
+++ b/jsoup/pom.xml
@@ -3,6 +3,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jsoup
+ jsoup
jar
diff --git a/jta/pom.xml b/jta/pom.xml
index 89bdccf25e..4754c1872b 100644
--- a/jta/pom.xml
+++ b/jta/pom.xml
@@ -3,8 +3,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.baeldung
- jta-demo
+ jta
1.0-SNAPSHOT
+ jta
jar
JEE JTA demo
diff --git a/jws/pom.xml b/jws/pom.xml
index 1970ab9921..2c89b687f8 100644
--- a/jws/pom.xml
+++ b/jws/pom.xml
@@ -3,9 +3,9 @@
4.0.0
com.example
jws
- war
0.0.1-SNAPSHOT
- jws-example
+ jws
+ war
com.baeldung
diff --git a/kotlin-libraries/README.md b/kotlin-libraries/README.md
index b9611043c8..d1ef77aa46 100644
--- a/kotlin-libraries/README.md
+++ b/kotlin-libraries/README.md
@@ -8,3 +8,4 @@
- [Kotlin with Ktor](http://www.baeldung.com/kotlin-ktor)
- [Guide to the Kotlin Exposed Framework](https://www.baeldung.com/kotlin-exposed-persistence)
- [Working with Dates in Kotlin](https://www.baeldung.com/kotlin-dates)
+- [Introduction to Arrow in Kotlin](https://www.baeldung.com/kotlin-arrow)
diff --git a/kotlin-libraries/pom.xml b/kotlin-libraries/pom.xml
index c5b7fed951..ae77a9aa2d 100644
--- a/kotlin-libraries/pom.xml
+++ b/kotlin-libraries/pom.xml
@@ -3,6 +3,7 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
kotlin-libraries
+ kotlin-libraries
jar
@@ -87,6 +88,13 @@
h2
${h2database.version}
+
+
+ io.arrow-kt
+ arrow-core
+ 0.7.3
+
+
diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEither.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEither.kt
new file mode 100644
index 0000000000..75dfb9a2a4
--- /dev/null
+++ b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEither.kt
@@ -0,0 +1,54 @@
+package com.baeldung.kotlin.arrow
+
+import arrow.core.Either
+import arrow.core.filterOrElse
+import kotlin.math.sqrt
+
+class FunctionalErrorHandlingWithEither {
+
+ sealed class ComputeProblem {
+ object OddNumber : ComputeProblem()
+ object NotANumber : ComputeProblem()
+ }
+
+ fun parseInput(s : String) : Either = Either.cond(s.toIntOrNull() != null, {-> s.toInt()}, {->ComputeProblem.NotANumber} )
+
+ fun isEven(x : Int) : Boolean = x % 2 == 0
+
+ fun biggestDivisor(x: Int) : Int = biggestDivisor(x, 2)
+
+ fun biggestDivisor(x : Int, y : Int) : Int {
+ if(x == y){
+ return 1;
+ }
+ if(x % y == 0){
+ return x / y;
+ }
+ return biggestDivisor(x, y+1)
+ }
+
+ fun isSquareNumber(x : Int) : Boolean {
+ val sqrt: Double = sqrt(x.toDouble())
+ return sqrt % 1.0 == 0.0
+ }
+
+ fun computeWithEither(input : String) : Either {
+ return parseInput(input)
+ .filterOrElse(::isEven) {->ComputeProblem.OddNumber}
+ .map (::biggestDivisor)
+ .map (::isSquareNumber)
+ }
+
+ fun computeWithEitherClient(input : String) {
+ val computeWithEither = computeWithEither(input)
+
+ when(computeWithEither){
+ is Either.Right -> "The greatest divisor is square number: ${computeWithEither.b}"
+ is Either.Left -> when(computeWithEither.a){
+ is ComputeProblem.NotANumber -> "Wrong input! Not a number!"
+ is ComputeProblem.OddNumber -> "It is an odd number!"
+ }
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOption.kt b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOption.kt
new file mode 100644
index 0000000000..5fddd1d88e
--- /dev/null
+++ b/kotlin-libraries/src/main/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOption.kt
@@ -0,0 +1,46 @@
+package com.baeldung.kotlin.arrow
+
+import arrow.core.None
+import arrow.core.Option
+import arrow.core.Some
+import kotlin.math.sqrt
+
+class FunctionalErrorHandlingWithOption {
+
+ fun parseInput(s : String) : Option = Option.fromNullable(s.toIntOrNull())
+
+ fun isEven(x : Int) : Boolean = x % 2 == 0
+
+ fun biggestDivisor(x: Int) : Int = biggestDivisor(x, 2)
+
+ fun biggestDivisor(x : Int, y : Int) : Int {
+ if(x == y){
+ return 1;
+ }
+ if(x % y == 0){
+ return x / y;
+ }
+ return biggestDivisor(x, y+1)
+ }
+
+ fun isSquareNumber(x : Int) : Boolean {
+ val sqrt: Double = sqrt(x.toDouble())
+ return sqrt % 1.0 == 0.0
+ }
+
+ fun computeWithOption(input : String) : Option {
+ return parseInput(input)
+ .filter(::isEven)
+ .map(::biggestDivisor)
+ .map(::isSquareNumber)
+ }
+
+ fun computeWithOptionClient(input : String) : String{
+ val computeOption = computeWithOption(input)
+
+ return when(computeOption){
+ is None -> "Not an even number!"
+ is Some -> "The greatest divisor is square number: ${computeOption.t}"
+ }
+ }
+}
\ No newline at end of file
diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalDataTypes.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalDataTypes.kt
new file mode 100644
index 0000000000..692425ee07
--- /dev/null
+++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalDataTypes.kt
@@ -0,0 +1,143 @@
+package com.baeldung.kotlin.arrow
+
+import arrow.core.*
+import org.junit.Assert
+import org.junit.Test
+
+class FunctionalDataTypes {
+
+ @Test
+ fun whenIdCreated_thanValueIsPresent(){
+ val id = Id("foo")
+ val justId = Id.just("foo");
+
+ Assert.assertEquals("foo", id.extract())
+ Assert.assertEquals(justId, id)
+ }
+
+ fun length(s : String) : Int = s.length
+
+ fun isBigEnough(i : Int) : Boolean = i > 10
+
+ @Test
+ fun whenIdCreated_thanMapIsAssociative(){
+ val foo = Id("foo")
+
+ val map1 = foo.map(::length)
+ .map(::isBigEnough)
+ val map2 = foo.map { s -> isBigEnough(length(s)) }
+
+ Assert.assertEquals(map1, map2)
+ }
+
+ fun lengthId(s : String) : Id = Id.just(length(s))
+
+ fun isBigEnoughId(i : Int) : Id = Id.just(isBigEnough(i))
+
+ @Test
+ fun whenIdCreated_thanFlatMapIsAssociative(){
+ val bar = Id("bar")
+
+ val flatMap = bar.flatMap(::lengthId)
+ .flatMap(::isBigEnoughId)
+ val flatMap1 = bar.flatMap { s -> lengthId(s).flatMap(::isBigEnoughId) }
+
+ Assert.assertEquals(flatMap, flatMap1)
+ }
+
+ @Test
+ fun whenOptionCreated_thanValueIsPresent(){
+ val factory = Option.just(42)
+ val constructor = Option(42)
+ val emptyOptional = Option.empty()
+ val fromNullable = Option.fromNullable(null)
+
+ Assert.assertEquals(42, factory.getOrElse { -1 })
+ Assert.assertEquals(factory, constructor)
+ Assert.assertEquals(emptyOptional, fromNullable)
+ }
+
+ @Test
+ fun whenOptionCreated_thanConstructorDifferFromFactory(){
+ val constructor : Option = Option(null)
+ val fromNullable : Option = Option.fromNullable(null)
+
+ try{
+ constructor.map { s -> s!!.length }
+ Assert.fail()
+ } catch (e : KotlinNullPointerException){
+ fromNullable.map { s->s!!.length }
+ }
+ Assert.assertNotEquals(constructor, fromNullable)
+ }
+
+ fun wrapper(x : Integer?) : Option = if (x == null) Option.just(-1) else Option.just(x.toInt())
+
+ @Test
+ fun whenOptionFromNullableCreated_thanItBreaksLeftIdentity(){
+ val optionFromNull = Option.fromNullable(null)
+
+ Assert.assertNotEquals(optionFromNull.flatMap(::wrapper), wrapper(null))
+ }
+
+ @Test
+ fun whenEitherCreated_thanOneValueIsPresent(){
+ val rightOnly : Either = Either.right(42)
+ val leftOnly : Either = Either.left("foo")
+
+ Assert.assertTrue(rightOnly.isRight())
+ Assert.assertTrue(leftOnly.isLeft())
+ Assert.assertEquals(42, rightOnly.getOrElse { -1 })
+ Assert.assertEquals(-1, leftOnly.getOrElse { -1 })
+
+ Assert.assertEquals(0, rightOnly.map { it % 2 }.getOrElse { -1 })
+ Assert.assertEquals(-1, leftOnly.map { it % 2 }.getOrElse { -1 })
+ Assert.assertTrue(rightOnly.flatMap { Either.Right(it % 2) }.isRight())
+ Assert.assertTrue(leftOnly.flatMap { Either.Right(it % 2) }.isLeft())
+ }
+
+ @Test
+ fun whenEvalNowUsed_thenMapEvaluatedLazily(){
+ val now = Eval.now(1)
+ Assert.assertEquals(1, now.value())
+
+ var counter : Int = 0
+ val map = now.map { x -> counter++; x+1 }
+ Assert.assertEquals(0, counter)
+
+ val value = map.value()
+ Assert.assertEquals(2, value)
+ Assert.assertEquals(1, counter)
+ }
+
+ @Test
+ fun whenEvalLaterUsed_theResultIsMemoized(){
+ var counter : Int = 0
+ val later = Eval.later { counter++; counter }
+ Assert.assertEquals(0, counter)
+
+ val firstValue = later.value()
+ Assert.assertEquals(1, firstValue)
+ Assert.assertEquals(1, counter)
+
+ val secondValue = later.value()
+ Assert.assertEquals(1, secondValue)
+ Assert.assertEquals(1, counter)
+ }
+
+ @Test
+ fun whenEvalAlwaysUsed_theResultIsNotMemoized(){
+ var counter : Int = 0
+ val later = Eval.always { counter++; counter }
+ Assert.assertEquals(0, counter)
+
+ val firstValue = later.value()
+ Assert.assertEquals(1, firstValue)
+ Assert.assertEquals(1, counter)
+
+ val secondValue = later.value()
+ Assert.assertEquals(2, secondValue)
+ Assert.assertEquals(2, counter)
+ }
+
+}
\ No newline at end of file
diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEitherTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEitherTest.kt
new file mode 100644
index 0000000000..47fbf825a0
--- /dev/null
+++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEitherTest.kt
@@ -0,0 +1,68 @@
+package com.baeldung.kotlin.arrow
+
+import arrow.core.Either
+import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.NotANumber
+import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.OddNumber
+import org.junit.Assert
+import org.junit.Test
+
+class FunctionalErrorHandlingWithEitherTest {
+
+ val operator = FunctionalErrorHandlingWithEither()
+
+ @Test
+ fun givenInvalidInput_whenComputeInvoked_NotANumberIsPresent(){
+ val computeWithEither = operator.computeWithEither("bar")
+
+ Assert.assertTrue(computeWithEither.isLeft())
+ when(computeWithEither){
+ is Either.Left -> when(computeWithEither.a){
+ NotANumber -> "Ok."
+ else -> Assert.fail()
+ }
+ else -> Assert.fail()
+ }
+ }
+
+ @Test
+ fun givenOddNumberInput_whenComputeInvoked_OddNumberIsPresent(){
+ val computeWithEither = operator.computeWithEither("121")
+
+ Assert.assertTrue(computeWithEither.isLeft())
+ when(computeWithEither){
+ is Either.Left -> when(computeWithEither.a){
+ OddNumber -> "Ok."
+ else -> Assert.fail()
+ }
+ else -> Assert.fail()
+ }
+ }
+
+ @Test
+ fun givenEvenNumberWithoutSquare_whenComputeInvoked_OddNumberIsPresent(){
+ val computeWithEither = operator.computeWithEither("100")
+
+ Assert.assertTrue(computeWithEither.isRight())
+ when(computeWithEither){
+ is Either.Right -> when(computeWithEither.b){
+ false -> "Ok."
+ else -> Assert.fail()
+ }
+ else -> Assert.fail()
+ }
+ }
+
+ @Test
+ fun givenEvenNumberWithSquare_whenComputeInvoked_OddNumberIsPresent(){
+ val computeWithEither = operator.computeWithEither("98")
+
+ Assert.assertTrue(computeWithEither.isRight())
+ when(computeWithEither){
+ is Either.Right -> when(computeWithEither.b){
+ true -> "Ok."
+ else -> Assert.fail()
+ }
+ else -> Assert.fail()
+ }
+ }
+}
\ No newline at end of file
diff --git a/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOptionTest.kt b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOptionTest.kt
new file mode 100644
index 0000000000..3ca4cd033f
--- /dev/null
+++ b/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithOptionTest.kt
@@ -0,0 +1,34 @@
+package com.baeldung.kotlin.arrow
+
+import org.junit.Assert
+import org.junit.Test
+
+class FunctionalErrorHandlingWithOptionTest {
+
+ val operator = FunctionalErrorHandlingWithOption()
+
+ @Test
+ fun givenInvalidInput_thenErrorMessageIsPresent(){
+ val useComputeOption = operator.computeWithOptionClient("foo")
+ Assert.assertEquals("Not an even number!", useComputeOption)
+ }
+
+ @Test
+ fun givenOddNumberInput_thenErrorMessageIsPresent(){
+ val useComputeOption = operator.computeWithOptionClient("539")
+ Assert.assertEquals("Not an even number!",useComputeOption)
+ }
+
+ @Test
+ fun givenEvenNumberInputWithNonSquareNum_thenFalseMessageIsPresent(){
+ val useComputeOption = operator.computeWithOptionClient("100")
+ Assert.assertEquals("The greatest divisor is square number: false",useComputeOption)
+ }
+
+ @Test
+ fun givenEvenNumberInputWithSquareNum_thenTrueMessageIsPresent(){
+ val useComputeOption = operator.computeWithOptionClient("242")
+ Assert.assertEquals("The greatest divisor is square number: true",useComputeOption)
+ }
+
+}
\ No newline at end of file
diff --git a/libraries-data/README.md b/libraries-data/README.md
index 7e40a4a2e2..69856af66b 100644
--- a/libraries-data/README.md
+++ b/libraries-data/README.md
@@ -14,3 +14,4 @@
- [Building a Data Pipeline with Flink and Kafka](https://www.baeldung.com/kafka-flink-data-pipeline)
- [Intro to Apache Storm](https://www.baeldung.com/apache-storm)
- [Guide to Ebean ORM](https://www.baeldung.com/ebean-orm)
+- [Introduction to Kafka Connectors](https://www.baeldung.com/kafka-connectors-guide)
diff --git a/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-file-sink.properties b/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-file-sink.properties
new file mode 100644
index 0000000000..594ccc6e95
--- /dev/null
+++ b/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-file-sink.properties
@@ -0,0 +1,20 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+name=local-file-sink
+connector.class=FileStreamSink
+tasks.max=1
+file=test.sink.txt
+topics=connect-test
\ No newline at end of file
diff --git a/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-file-source.properties b/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-file-source.properties
new file mode 100644
index 0000000000..599cf4cb2a
--- /dev/null
+++ b/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-file-source.properties
@@ -0,0 +1,20 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+name=local-file-source
+connector.class=FileStreamSource
+tasks.max=1
+file=test.txt
+topic=connect-test
\ No newline at end of file
diff --git a/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-standalone.properties b/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-standalone.properties
new file mode 100644
index 0000000000..a2369fa144
--- /dev/null
+++ b/libraries-data/src/main/kafka-connect/01_Quick_Start/connect-standalone.properties
@@ -0,0 +1,44 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# These are defaults. This file just demonstrates how to override some settings.
+bootstrap.servers=localhost:9092
+
+# The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will
+# need to configure these based on the format they want their data in when loaded from or stored into Kafka
+key.converter=org.apache.kafka.connect.json.JsonConverter
+value.converter=org.apache.kafka.connect.json.JsonConverter
+# Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply
+# it to
+key.converter.schemas.enable=false
+value.converter.schemas.enable=false
+
+offset.storage.file.filename=/tmp/connect.offsets
+# Flush much faster than normal, which is useful for testing/debugging
+offset.flush.interval.ms=10000
+
+# Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins
+# (connectors, converters, transformations). The list should consist of top level directories that include
+# any combination of:
+# a) directories immediately containing jars with plugins and their dependencies
+# b) uber-jars with plugins and their dependencies
+# c) directories immediately containing the package directory structure of classes of plugins and their dependencies
+# Note: symlinks will be followed to discover dependencies or plugins.
+# Examples:
+# plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors,
+# Replace the relative path below with an absolute path if you are planning to start Kafka Connect from within a
+# directory other than the home directory of Confluent Platform.
+plugin.path=C:\Software\confluent-5.0.0\share\java
+#plugin.path=./share/java
diff --git a/libraries-data/src/main/kafka-connect/02_Distributed/connect-distributed.properties b/libraries-data/src/main/kafka-connect/02_Distributed/connect-distributed.properties
new file mode 100644
index 0000000000..5b91baddbd
--- /dev/null
+++ b/libraries-data/src/main/kafka-connect/02_Distributed/connect-distributed.properties
@@ -0,0 +1,88 @@
+##
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+# This file contains some of the configurations for the Kafka Connect distributed worker. This file is intended
+# to be used with the examples, and some settings may differ from those used in a production system, especially
+# the `bootstrap.servers` and those specifying replication factors.
+
+# A list of host/port pairs to use for establishing the initial connection to the Kafka cluster.
+bootstrap.servers=localhost:9092
+
+# unique name for the cluster, used in forming the Connect cluster group. Note that this must not conflict with consumer group IDs
+group.id=connect-cluster
+
+# The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will
+# need to configure these based on the format they want their data in when loaded from or stored into Kafka
+key.converter=org.apache.kafka.connect.json.JsonConverter
+value.converter=org.apache.kafka.connect.json.JsonConverter
+# Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply
+# it to
+key.converter.schemas.enable=true
+value.converter.schemas.enable=true
+
+# Topic to use for storing offsets. This topic should have many partitions and be replicated and compacted.
+# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
+# the topic before starting Kafka Connect if a specific topic configuration is needed.
+# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
+# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
+# to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
+offset.storage.topic=connect-offsets
+offset.storage.replication.factor=1
+#offset.storage.partitions=25
+
+# Topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated,
+# and compacted topic. Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
+# the topic before starting Kafka Connect if a specific topic configuration is needed.
+# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
+# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
+# to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
+config.storage.topic=connect-configs
+config.storage.replication.factor=1
+
+# Topic to use for storing statuses. This topic can have multiple partitions and should be replicated and compacted.
+# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
+# the topic before starting Kafka Connect if a specific topic configuration is needed.
+# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
+# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
+# to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
+status.storage.topic=connect-status
+status.storage.replication.factor=1
+#status.storage.partitions=5
+
+# Flush much faster than normal, which is useful for testing/debugging
+offset.flush.interval.ms=10000
+
+# These are provided to inform the user about the presence of the REST host and port configs
+# Hostname & Port for the REST API to listen on. If this is set, it will bind to the interface used to listen to requests.
+#rest.host.name=
+#rest.port=8083
+
+# The Hostname & Port that will be given out to other workers to connect to i.e. URLs that are routable from other servers.
+#rest.advertised.host.name=
+#rest.advertised.port=
+
+# Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins
+# (connectors, converters, transformations). The list should consist of top level directories that include
+# any combination of:
+# a) directories immediately containing jars with plugins and their dependencies
+# b) uber-jars with plugins and their dependencies
+# c) directories immediately containing the package directory structure of classes of plugins and their dependencies
+# Examples:
+# plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors,
+# Replace the relative path below with an absolute path if you are planning to start Kafka Connect from within a
+# directory other than the home directory of Confluent Platform.
+plugin.path=./share/java
diff --git a/libraries-data/src/main/kafka-connect/02_Distributed/connect-file-sink.json b/libraries-data/src/main/kafka-connect/02_Distributed/connect-file-sink.json
new file mode 100644
index 0000000000..8902ecce52
--- /dev/null
+++ b/libraries-data/src/main/kafka-connect/02_Distributed/connect-file-sink.json
@@ -0,0 +1,9 @@
+{
+ "name": "local-file-sink",
+ "config": {
+ "connector.class": "FileStreamSink",
+ "tasks.max": 1,
+ "file": "test-distributed.sink.txt",
+ "topics": "connect-distributed"
+ }
+}
diff --git a/libraries-data/src/main/kafka-connect/02_Distributed/connect-file-source.json b/libraries-data/src/main/kafka-connect/02_Distributed/connect-file-source.json
new file mode 100644
index 0000000000..77e949c91b
--- /dev/null
+++ b/libraries-data/src/main/kafka-connect/02_Distributed/connect-file-source.json
@@ -0,0 +1,9 @@
+{
+ "name": "local-file-source",
+ "config": {
+ "connector.class": "FileStreamSource",
+ "tasks.max": 1,
+ "file": "test-distributed.txt",
+ "topic": "connect-distributed"
+ }
+}
diff --git a/libraries-data/src/main/kafka-connect/03_Transform/connect-distributed.properties b/libraries-data/src/main/kafka-connect/03_Transform/connect-distributed.properties
new file mode 100644
index 0000000000..fa63be24b8
--- /dev/null
+++ b/libraries-data/src/main/kafka-connect/03_Transform/connect-distributed.properties
@@ -0,0 +1,88 @@
+##
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+# This file contains some of the configurations for the Kafka Connect distributed worker. This file is intended
+# to be used with the examples, and some settings may differ from those used in a production system, especially
+# the `bootstrap.servers` and those specifying replication factors.
+
+# A list of host/port pairs to use for establishing the initial connection to the Kafka cluster.
+bootstrap.servers=localhost:9092
+
+# unique name for the cluster, used in forming the Connect cluster group. Note that this must not conflict with consumer group IDs
+group.id=connect-cluster
+
+# The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will
+# need to configure these based on the format they want their data in when loaded from or stored into Kafka
+key.converter=org.apache.kafka.connect.json.JsonConverter
+value.converter=org.apache.kafka.connect.json.JsonConverter
+# Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply
+# it to
+key.converter.schemas.enable=false
+value.converter.schemas.enable=false
+
+# Topic to use for storing offsets. This topic should have many partitions and be replicated and compacted.
+# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
+# the topic before starting Kafka Connect if a specific topic configuration is needed.
+# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
+# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
+# to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
+offset.storage.topic=connect-offsets
+offset.storage.replication.factor=1
+#offset.storage.partitions=25
+
+# Topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated,
+# and compacted topic. Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
+# the topic before starting Kafka Connect if a specific topic configuration is needed.
+# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
+# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
+# to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
+config.storage.topic=connect-configs
+config.storage.replication.factor=1
+
+# Topic to use for storing statuses. This topic can have multiple partitions and should be replicated and compacted.
+# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
+# the topic before starting Kafka Connect if a specific topic configuration is needed.
+# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
+# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
+# to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
+status.storage.topic=connect-status
+status.storage.replication.factor=1
+#status.storage.partitions=5
+
+# Flush much faster than normal, which is useful for testing/debugging
+offset.flush.interval.ms=10000
+
+# These are provided to inform the user about the presence of the REST host and port configs
+# Hostname & Port for the REST API to listen on. If this is set, it will bind to the interface used to listen to requests.
+#rest.host.name=
+#rest.port=8083
+
+# The Hostname & Port that will be given out to other workers to connect to i.e. URLs that are routable from other servers.
+#rest.advertised.host.name=
+#rest.advertised.port=
+
+# Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins
+# (connectors, converters, transformations). The list should consist of top level directories that include
+# any combination of:
+# a) directories immediately containing jars with plugins and their dependencies
+# b) uber-jars with plugins and their dependencies
+# c) directories immediately containing the package directory structure of classes of plugins and their dependencies
+# Examples:
+# plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors,
+# Replace the relative path below with an absolute path if you are planning to start Kafka Connect from within a
+# directory other than the home directory of Confluent Platform.
+plugin.path=./share/java
diff --git a/libraries-data/src/main/kafka-connect/03_Transform/connect-file-source-transform.json b/libraries-data/src/main/kafka-connect/03_Transform/connect-file-source-transform.json
new file mode 100644
index 0000000000..e5e21a0608
--- /dev/null
+++ b/libraries-data/src/main/kafka-connect/03_Transform/connect-file-source-transform.json
@@ -0,0 +1,15 @@
+{
+ "name": "local-file-source",
+ "config": {
+ "connector.class": "FileStreamSource",
+ "tasks.max": 1,
+ "file": "transformation.txt",
+ "topic": "connect-transformation",
+ "transforms": "MakeMap,InsertSource",
+ "transforms.MakeMap.type": "org.apache.kafka.connect.transforms.HoistField$Value",
+ "transforms.MakeMap.field": "line",
+ "transforms.InsertSource.type": "org.apache.kafka.connect.transforms.InsertField$Value",
+ "transforms.InsertSource.static.field": "data_source",
+ "transforms.InsertSource.static.value": "test-file-source"
+ }
+}
diff --git a/libraries-data/src/main/kafka-connect/04_Custom/connect-distributed.properties b/libraries-data/src/main/kafka-connect/04_Custom/connect-distributed.properties
new file mode 100644
index 0000000000..5b91baddbd
--- /dev/null
+++ b/libraries-data/src/main/kafka-connect/04_Custom/connect-distributed.properties
@@ -0,0 +1,88 @@
+##
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+# This file contains some of the configurations for the Kafka Connect distributed worker. This file is intended
+# to be used with the examples, and some settings may differ from those used in a production system, especially
+# the `bootstrap.servers` and those specifying replication factors.
+
+# A list of host/port pairs to use for establishing the initial connection to the Kafka cluster.
+bootstrap.servers=localhost:9092
+
+# unique name for the cluster, used in forming the Connect cluster group. Note that this must not conflict with consumer group IDs
+group.id=connect-cluster
+
+# The converters specify the format of data in Kafka and how to translate it into Connect data. Every Connect user will
+# need to configure these based on the format they want their data in when loaded from or stored into Kafka
+key.converter=org.apache.kafka.connect.json.JsonConverter
+value.converter=org.apache.kafka.connect.json.JsonConverter
+# Converter-specific settings can be passed in by prefixing the Converter's setting with the converter we want to apply
+# it to
+key.converter.schemas.enable=true
+value.converter.schemas.enable=true
+
+# Topic to use for storing offsets. This topic should have many partitions and be replicated and compacted.
+# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
+# the topic before starting Kafka Connect if a specific topic configuration is needed.
+# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
+# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
+# to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
+offset.storage.topic=connect-offsets
+offset.storage.replication.factor=1
+#offset.storage.partitions=25
+
+# Topic to use for storing connector and task configurations; note that this should be a single partition, highly replicated,
+# and compacted topic. Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
+# the topic before starting Kafka Connect if a specific topic configuration is needed.
+# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
+# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
+# to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
+config.storage.topic=connect-configs
+config.storage.replication.factor=1
+
+# Topic to use for storing statuses. This topic can have multiple partitions and should be replicated and compacted.
+# Kafka Connect will attempt to create the topic automatically when needed, but you can always manually create
+# the topic before starting Kafka Connect if a specific topic configuration is needed.
+# Most users will want to use the built-in default replication factor of 3 or in some cases even specify a larger value.
+# Since this means there must be at least as many brokers as the maximum replication factor used, we'd like to be able
+# to run this example on a single-broker cluster and so here we instead set the replication factor to 1.
+status.storage.topic=connect-status
+status.storage.replication.factor=1
+#status.storage.partitions=5
+
+# Flush much faster than normal, which is useful for testing/debugging
+offset.flush.interval.ms=10000
+
+# These are provided to inform the user about the presence of the REST host and port configs
+# Hostname & Port for the REST API to listen on. If this is set, it will bind to the interface used to listen to requests.
+#rest.host.name=
+#rest.port=8083
+
+# The Hostname & Port that will be given out to other workers to connect to i.e. URLs that are routable from other servers.
+#rest.advertised.host.name=
+#rest.advertised.port=
+
+# Set to a list of filesystem paths separated by commas (,) to enable class loading isolation for plugins
+# (connectors, converters, transformations). The list should consist of top level directories that include
+# any combination of:
+# a) directories immediately containing jars with plugins and their dependencies
+# b) uber-jars with plugins and their dependencies
+# c) directories immediately containing the package directory structure of classes of plugins and their dependencies
+# Examples:
+# plugin.path=/usr/local/share/java,/usr/local/share/kafka/plugins,/opt/connectors,
+# Replace the relative path below with an absolute path if you are planning to start Kafka Connect from within a
+# directory other than the home directory of Confluent Platform.
+plugin.path=./share/java
diff --git a/libraries-data/src/main/kafka-connect/04_Custom/connect-mongodb-sink.json b/libraries-data/src/main/kafka-connect/04_Custom/connect-mongodb-sink.json
new file mode 100644
index 0000000000..333768e4b7
--- /dev/null
+++ b/libraries-data/src/main/kafka-connect/04_Custom/connect-mongodb-sink.json
@@ -0,0 +1,22 @@
+{
+ "firstName": "John",
+ "lastName": "Smith",
+ "age": 25,
+ "address": {
+ "streetAddress": "21 2nd Street",
+ "city": "New York",
+ "state": "NY",
+ "postalCode": "10021"
+ },
+ "phoneNumber": [{
+ "type": "home",
+ "number": "212 555-1234"
+ }, {
+ "type": "fax",
+ "number": "646 555-4567"
+ }
+ ],
+ "gender": {
+ "type": "male"
+ }
+}
diff --git a/libraries-data/src/main/kafka-connect/04_Custom/connect-mqtt-source.json b/libraries-data/src/main/kafka-connect/04_Custom/connect-mqtt-source.json
new file mode 100644
index 0000000000..02d87c5ad7
--- /dev/null
+++ b/libraries-data/src/main/kafka-connect/04_Custom/connect-mqtt-source.json
@@ -0,0 +1,11 @@
+{
+ "name": "mqtt-source",
+ "config": {
+ "connector.class": "io.confluent.connect.mqtt.MqttSourceConnector",
+ "tasks.max": 1,
+ "mqtt.server.uri": "ws://broker.hivemq.com:8000/mqtt",
+ "mqtt.topics": "baeldung",
+ "kafka.topic": "connect-custom",
+ "value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter"
+ }
+}
diff --git a/libraries-server/pom.xml b/libraries-server/pom.xml
index 6fca09faf4..661f5f01d5 100644
--- a/libraries-server/pom.xml
+++ b/libraries-server/pom.xml
@@ -1,9 +1,10 @@
4.0.0
- com.baeldung
libraries-server
0.0.1-SNAPSHOT
+ libraries-server
+
com.baeldung
parent-modules
diff --git a/libraries/pom.xml b/libraries/pom.xml
index 8ffd33272d..cb85a57304 100644
--- a/libraries/pom.xml
+++ b/libraries/pom.xml
@@ -717,14 +717,20 @@
${suanshu.version}
+
+ org.derive4j
+ derive4j
+ ${derive4j.version}
+ true
+
-
+
false
@@ -942,7 +948,7 @@
2.0.4
1.3.1
1.2.6
- 4.7
+ 4.8.1
1.0.1
3.3.5
2.1
@@ -952,6 +958,7 @@
4.5.1
3.3.0
3.0.2
+ 1.1.0
diff --git a/libraries/src/main/java/com/baeldung/derive4j/adt/Either.java b/libraries/src/main/java/com/baeldung/derive4j/adt/Either.java
new file mode 100644
index 0000000000..d22bb89fe2
--- /dev/null
+++ b/libraries/src/main/java/com/baeldung/derive4j/adt/Either.java
@@ -0,0 +1,10 @@
+package com.baeldung.derive4j.adt;
+
+import org.derive4j.Data;
+
+import java.util.function.Function;
+
+@Data
+interface Either{
+ X match(Function left, Function right);
+}
diff --git a/libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java b/libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java
new file mode 100644
index 0000000000..9f53f3d25b
--- /dev/null
+++ b/libraries/src/main/java/com/baeldung/derive4j/lazy/LazyRequest.java
@@ -0,0 +1,21 @@
+package com.baeldung.derive4j.lazy;
+
+import org.derive4j.Data;
+import org.derive4j.Derive;
+import org.derive4j.Make;
+
+@Data(value = @Derive(
+ inClass = "{ClassName}Impl",
+ make = {Make.lazyConstructor, Make.constructors}
+))
+public interface LazyRequest {
+ interface Cases{
+ R GET(String path);
+ R POST(String path, String body);
+ R PUT(String path, String body);
+ R DELETE(String path);
+ }
+
+ R match(LazyRequest.Cases method);
+}
+
diff --git a/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java
new file mode 100644
index 0000000000..04d630f1ef
--- /dev/null
+++ b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPRequest.java
@@ -0,0 +1,15 @@
+package com.baeldung.derive4j.pattern;
+
+import org.derive4j.Data;
+
+@Data
+interface HTTPRequest {
+ interface Cases{
+ R GET(String path);
+ R POST(String path, String body);
+ R PUT(String path, String body);
+ R DELETE(String path);
+ }
+
+ R match(Cases method);
+}
diff --git a/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java
new file mode 100644
index 0000000000..593f94a8b7
--- /dev/null
+++ b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPResponse.java
@@ -0,0 +1,19 @@
+package com.baeldung.derive4j.pattern;
+
+public class HTTPResponse {
+ private int statusCode;
+ private String responseBody;
+
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ public String getResponseBody() {
+ return responseBody;
+ }
+
+ public HTTPResponse(int statusCode, String responseBody) {
+ this.statusCode = statusCode;
+ this.responseBody = responseBody;
+ }
+}
diff --git a/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java
new file mode 100644
index 0000000000..53f4af628c
--- /dev/null
+++ b/libraries/src/main/java/com/baeldung/derive4j/pattern/HTTPServer.java
@@ -0,0 +1,17 @@
+package com.baeldung.derive4j.pattern;
+
+
+public class HTTPServer {
+ public static String GET_RESPONSE_BODY = "Success!";
+ public static String PUT_RESPONSE_BODY = "Resource Created!";
+ public static String POST_RESPONSE_BODY = "Resource Updated!";
+ public static String DELETE_RESPONSE_BODY = "Resource Deleted!";
+
+ public HTTPResponse acceptRequest(HTTPRequest request) {
+ return HTTPRequests.caseOf(request)
+ .GET((path) -> new HTTPResponse(200, GET_RESPONSE_BODY))
+ .POST((path,body) -> new HTTPResponse(201, POST_RESPONSE_BODY))
+ .PUT((path,body) -> new HTTPResponse(200, PUT_RESPONSE_BODY))
+ .DELETE(path -> new HTTPResponse(200, DELETE_RESPONSE_BODY));
+ }
+}
diff --git a/libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java b/libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java
new file mode 100644
index 0000000000..511e24961f
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/derive4j/adt/EitherUnitTest.java
@@ -0,0 +1,33 @@
+package com.baeldung.derive4j.adt;
+
+import org.assertj.core.api.Assertions;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+
+import java.util.Optional;
+import java.util.function.Function;
+@RunWith(MockitoJUnitRunner.class)
+public class EitherUnitTest {
+ @Test
+ public void testEitherIsCreatedFromRight() {
+ Either either = Eithers.right("Okay");
+ Optional leftOptional = Eithers.getLeft(either);
+ Optional rightOptional = Eithers.getRight(either);
+ Assertions.assertThat(leftOptional).isEmpty();
+ Assertions.assertThat(rightOptional).hasValue("Okay");
+
+ }
+
+ @Test
+ public void testEitherIsMatchedWithRight() {
+ Either either = Eithers.right("Okay");
+ Function leftFunction = Mockito.mock(Function.class);
+ Function rightFunction = Mockito.mock(Function.class);
+ either.match(leftFunction, rightFunction);
+ Mockito.verify(rightFunction, Mockito.times(1)).apply("Okay");
+ Mockito.verify(leftFunction, Mockito.times(0)).apply(Mockito.any(Exception.class));
+ }
+
+}
diff --git a/libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java b/libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java
new file mode 100644
index 0000000000..3830bc52d0
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/derive4j/lazy/LazyRequestUnitTest.java
@@ -0,0 +1,28 @@
+package com.baeldung.derive4j.lazy;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import java.util.function.Supplier;
+
+public class LazyRequestUnitTest {
+
+ @Test
+ public void givenLazyContstructedRequest_whenRequestIsReferenced_thenRequestIsLazilyContructed() {
+ LazyRequestSupplier mockSupplier = Mockito.spy(new LazyRequestSupplier());
+
+ LazyRequest request = LazyRequestImpl.lazy(() -> mockSupplier.get());
+ Mockito.verify(mockSupplier, Mockito.times(0)).get();
+ Assert.assertEquals(LazyRequestImpl.getPath(request), "http://test.com/get");
+ Mockito.verify(mockSupplier, Mockito.times(1)).get();
+
+ }
+
+ class LazyRequestSupplier implements Supplier {
+ @Override
+ public LazyRequest get() {
+ return LazyRequestImpl.GET("http://test.com/get");
+ }
+ }
+}
diff --git a/libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java b/libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java
new file mode 100644
index 0000000000..0fc257742a
--- /dev/null
+++ b/libraries/src/test/java/com/baeldung/derive4j/pattern/HTTPRequestUnitTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.derive4j.pattern;
+
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class HTTPRequestUnitTest {
+ public static HTTPServer server;
+
+ @BeforeClass
+ public static void setUp() {
+ server = new HTTPServer();
+ }
+
+ @Test
+ public void givenHttpGETRequest_whenRequestReachesServer_thenProperResponseIsReturned() {
+ HTTPRequest postRequest = HTTPRequests.POST("http://test.com/post", "Resource");
+ HTTPResponse response = server.acceptRequest(postRequest);
+ Assert.assertEquals(201, response.getStatusCode());
+ Assert.assertEquals(HTTPServer.POST_RESPONSE_BODY, response.getResponseBody());
+ }
+}
diff --git a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java
index d62a115abd..aa06ba4eb9 100644
--- a/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java
+++ b/libraries/src/test/java/com/baeldung/fj/FunctionalJavaUnitTest.java
@@ -1,79 +1,122 @@
-package com.baeldung.fj;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-import fj.F;
-import fj.data.Array;
-import fj.data.List;
-import fj.data.Option;
-import fj.function.Characters;
-import fj.function.Integers;
-
-public class FunctionalJavaUnitTest {
-
- public static final F isEven = i -> i % 2 == 0;
-
- @Test
- public void calculateEvenNumbers_givenIntList_returnTrue() {
- List fList = List.list(3, 4, 5, 6);
- List evenList = fList.map(isEven);
- List evenListTrueResult = List.list(false, true, false, true);
- List evenListFalseResult = List.list(true, false, false, true);
- assertEquals(evenList.equals(evenListTrueResult), true);
- assertEquals(evenList.equals(evenListFalseResult), false);
- }
-
- @Test
- public void mapList_givenIntList_returnResult() {
- List fList = List.list(3, 4, 5, 6);
- fList = fList.map(i -> i + 100);
- List resultList = List.list(103, 104, 105, 106);
- List falseResultList = List.list(15, 504, 105, 106);
- assertEquals(fList.equals(resultList), true);
- assertEquals(fList.equals(falseResultList), false);
- }
-
- @Test
- public void filterList_givenIntList_returnResult() {
- Array array = Array.array(3, 4, 5, 6);
- Array filteredArray = array.filter(Integers.even);
- Array result = Array.array(4, 6);
- Array wrongResult = Array.array(3, 5);
- assertEquals(filteredArray.equals(result), true);
- assertEquals(filteredArray.equals(wrongResult), false);
- }
-
- @Test
- public void checkForLowerCase_givenStringArray_returnResult() {
- Array array = Array.array("Welcome", "To", "baeldung");
- Array array2 = Array.array("Welcome", "To", "Baeldung");
- Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
- Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
- assertEquals(isExist, true);
- assertEquals(isExist2, false);
- }
-
- @Test
- public void checkOptions_givenOptions_returnResult() {
- Option n1 = Option.some(1);
- Option n2 = Option.some(2);
-
- F> f1 = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
-
- Option result1 = n1.bind(f1);
- Option result2 = n2.bind(f1);
-
- assertEquals(result1, Option.none());
- assertEquals(result2, Option.some(102));
- }
-
- @Test
- public void foldLeft_givenArray_returnResult() {
- Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
- int sum = intArray.foldLeft(Integers.add, 0);
- assertEquals(sum, 260);
- }
-
-}
+package com.baeldung.fj;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+import fj.F;
+import fj.Show;
+import fj.data.Array;
+import fj.data.List;
+import fj.data.Option;
+import fj.function.Characters;
+import fj.function.Integers;
+
+public class FunctionalJavaUnitTest {
+
+ public static final F isEven = i -> i % 2 == 0;
+
+ public static final Integer timesTwoRegular(Integer i) {
+ return i * 2;
+ }
+
+ public static final F timesTwo = i -> i * 2;
+
+ public static final F plusOne = i -> i + 1;
+
+ @Test
+ public void multiplyNumbers_givenIntList_returnTrue() {
+ List fList = List.list(1, 2, 3, 4);
+ List fList1 = fList.map(timesTwo);
+ List fList2 = fList.map(i -> i * 2);
+
+ assertEquals(fList1.equals(fList2), true);
+ }
+
+ @Test
+ public void applyMultipleFunctions_givenIntList_returnFalse() {
+ List fList = List.list(1, 2, 3, 4);
+ List fList1 = fList.map(timesTwo).map(plusOne);
+ Show.listShow(Show.intShow).println(fList1);
+ List fList2 = fList.map(plusOne).map(timesTwo);
+ Show.listShow(Show.intShow).println(fList2);
+
+ assertEquals(fList1.equals(fList2), false);
+ }
+
+ @Test
+ public void calculateEvenNumbers_givenIntList_returnTrue() {
+ List fList = List.list(3, 4, 5, 6);
+ List evenList = fList.map(isEven);
+ List evenListTrueResult = List.list(false, true, false, true);
+ List evenListFalseResult = List.list(true, false, false, true);
+
+ assertEquals(evenList.equals(evenListTrueResult), true);
+ assertEquals(evenList.equals(evenListFalseResult), false);
+ }
+
+ @Test
+ public void mapList_givenIntList_returnResult() {
+ List fList = List.list(3, 4, 5, 6);
+ fList = fList.map(i -> i + 100);
+ List resultList = List.list(103, 104, 105, 106);
+ List falseResultList = List.list(15, 504, 105, 106);
+
+ assertEquals(fList.equals(resultList), true);
+ assertEquals(fList.equals(falseResultList), false);
+ }
+
+ @Test
+ public void filterList_givenIntList_returnResult() {
+ Array array = Array.array(3, 4, 5, 6);
+ Array filteredArray = array.filter(isEven);
+ Array result = Array.array(4, 6);
+ Array wrongResult = Array.array(3, 5);
+
+ assertEquals(filteredArray.equals(result), true);
+ assertEquals(filteredArray.equals(wrongResult), false);
+ }
+
+ @Test
+ public void checkForLowerCase_givenStringArray_returnResult() {
+ Array array = Array.array("Welcome", "To", "baeldung");
+ Array array2 = Array.array("Welcome", "To", "Baeldung");
+ Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
+ Boolean isExist2 = array2.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
+ Boolean isAll = array.forall(s -> List.fromString(s).forall(Characters.isLowerCase));
+
+ assertEquals(isExist, true);
+ assertEquals(isExist2, false);
+ assertEquals(isAll, false);
+ }
+
+ @Test
+ public void checkOptions_givenOptions_returnResult() {
+ Option n1 = Option.some(1);
+ Option n2 = Option.some(2);
+ Option n3 = Option.none();
+
+ F> function = i -> i % 2 == 0 ? Option.some(i + 100) : Option.none();
+
+ Option result1 = n1.bind(function);
+ Option result2 = n2.bind(function);
+ Option result3 = n3.bind(function);
+
+ assertEquals(result1, Option.none());
+ assertEquals(result2, Option.some(102));
+ assertEquals(result3, Option.none());
+ }
+
+ @Test
+ public void foldLeft_givenArray_returnResult() {
+ Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
+ int sumAll = intArray.foldLeft(Integers.add, 0);
+
+ assertEquals(sumAll, 260);
+
+ int sumEven = intArray.filter(isEven).foldLeft(Integers.add, 0);
+
+ assertEquals(sumEven, 148);
+ }
+
+}
diff --git a/linkrest/pom.xml b/linkrest/pom.xml
index a27caea1ff..073a173aff 100644
--- a/linkrest/pom.xml
+++ b/linkrest/pom.xml
@@ -1,9 +1,9 @@
4.0.0
- com.baeldung
linkrest
0.0.1-SNAPSHOT
+ linkrest
war
diff --git a/logging-modules/log4j/pom.xml b/logging-modules/log4j/pom.xml
index 432295fc62..af97d812de 100644
--- a/logging-modules/log4j/pom.xml
+++ b/logging-modules/log4j/pom.xml
@@ -1,10 +1,12 @@
-
4.0.0
com.baeldung
log4j
1.0-SNAPSHOT
+ log4j
com.baeldung
diff --git a/logging-modules/log4j2/pom.xml b/logging-modules/log4j2/pom.xml
index 65da318636..d46f92dcd6 100644
--- a/logging-modules/log4j2/pom.xml
+++ b/logging-modules/log4j2/pom.xml
@@ -3,7 +3,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
log4j2
-
+ log4j2
+
com.baeldung
parent-modules
diff --git a/maven-archetype/pom.xml b/maven-archetype/pom.xml
index f7871c81ea..73ddc78fc7 100644
--- a/maven-archetype/pom.xml
+++ b/maven-archetype/pom.xml
@@ -5,9 +5,10 @@
com.baeldung.archetypes
maven-archetype
1.0-SNAPSHOT
+ maven-archetype
maven-archetype
Archetype used to generate rest application based on jaxrs 2.1
-
+
diff --git a/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-polyglot/maven-polyglot-json-extension/pom.xml
index d5c5b7ab55..fe1e025d1f 100644
--- a/maven-polyglot/maven-polyglot-json-extension/pom.xml
+++ b/maven-polyglot/maven-polyglot-json-extension/pom.xml
@@ -3,11 +3,11 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
-
com.baeldung.maven.polyglot
maven-polyglot-json-extension
1.0-SNAPSHOT
-
+ maven-polyglot-json-extension
+
1.8
1.8
diff --git a/maven/pom.xml b/maven/pom.xml
index 4bec533226..01fd28db74 100644
--- a/maven/pom.xml
+++ b/maven/pom.xml
@@ -4,6 +4,7 @@
com.baeldung
maven
0.0.1-SNAPSHOT
+ maven
war
diff --git a/maven/versions-maven-plugin/pom.xml b/maven/versions-maven-plugin/pom.xml
index 295c77b860..dc0cba75f9 100644
--- a/maven/versions-maven-plugin/pom.xml
+++ b/maven/versions-maven-plugin/pom.xml
@@ -3,9 +3,10 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.baeldung
- versions-maven-plugin-example
+ versions-maven-plugin
0.0.1-SNAPSHOT
-
+ versions-maven-plugin
+
1.15
diff --git a/mesos-marathon/pom.xml b/mesos-marathon/pom.xml
index f92c00892b..dee8eca10d 100644
--- a/mesos-marathon/pom.xml
+++ b/mesos-marathon/pom.xml
@@ -5,7 +5,8 @@
com.baeldung
mesos-marathon
0.0.1-SNAPSHOT
-
+ mesos-marathon
+
parent-boot-1
com.baeldung
diff --git a/metrics/pom.xml b/metrics/pom.xml
index 9cf1ec588f..79d340aa49 100644
--- a/metrics/pom.xml
+++ b/metrics/pom.xml
@@ -3,7 +3,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
metrics
-
+ metrics
+
parent-modules
com.baeldung
diff --git a/micronaut/pom.xml b/micronaut/pom.xml
index 7b722306b6..aa69c77f73 100644
--- a/micronaut/pom.xml
+++ b/micronaut/pom.xml
@@ -7,15 +7,10 @@
com.baeldung.micronaut.helloworld.server.ServerApplication
- 1.0.0.M2
- 9
+ 1.0.0.RC2
+ 1.8
-
-
- jcenter.bintray.com
- http://jcenter.bintray.com
-
-
+
diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java
index d4051cef52..96bc51f235 100644
--- a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java
+++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/ConcreteGreetingClient.java
@@ -1,7 +1,7 @@
package com.baeldung.micronaut.helloworld.client;
import io.micronaut.http.HttpRequest;
-import io.micronaut.http.client.Client;
+import io.micronaut.http.client.annotation.Client;
import io.micronaut.http.client.RxHttpClient;
import io.reactivex.Single;
diff --git a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java
index 8a691d5b06..d29a97fd50 100644
--- a/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java
+++ b/micronaut/src/main/java/com/baeldung/micronaut/helloworld/client/GreetingClient.java
@@ -1,10 +1,7 @@
package com.baeldung.micronaut.helloworld.client;
import io.micronaut.http.annotation.Get;
-import io.micronaut.http.client.Client;
-import io.micronaut.http.client.RxHttpClient;
-
-import javax.inject.Inject;
+import io.micronaut.http.client.annotation.Client;
@Client("/greet")
public interface GreetingClient {
diff --git a/microprofile/pom.xml b/microprofile/pom.xml
index d75b6443ed..52df348ace 100644
--- a/microprofile/pom.xml
+++ b/microprofile/pom.xml
@@ -5,6 +5,7 @@
com.baeldung
microprofile
1.0-SNAPSHOT
+ microprofile
war
diff --git a/msf4j/pom.xml b/msf4j/pom.xml
index 9a6483772b..4a6f63159d 100644
--- a/msf4j/pom.xml
+++ b/msf4j/pom.xml
@@ -5,6 +5,7 @@
com.baeldung.msf4j
msf4j
0.0.1-SNAPSHOT
+ msf4j
parent-modules
diff --git a/muleesb/pom.xml b/muleesb/pom.xml
index b34123567a..4b74b6d4f4 100644
--- a/muleesb/pom.xml
+++ b/muleesb/pom.xml
@@ -6,9 +6,9 @@
com.mycompany
muleesb
1.0.0-SNAPSHOT
- mule
- Mule muleesb Application
-
+ muleesb
+ mule
+
com.baeldung
parent-modules
diff --git a/mybatis/pom.xml b/mybatis/pom.xml
index aa9ff9e288..4e63d14ded 100644
--- a/mybatis/pom.xml
+++ b/mybatis/pom.xml
@@ -5,7 +5,8 @@
com.baeldung
mybatis
1.0.0-SNAPSHOT
-
+ mybatis
+
com.baeldung
parent-modules
diff --git a/optaplanner/pom.xml b/optaplanner/pom.xml
index 22abbedc8c..fbce0ea072 100644
--- a/optaplanner/pom.xml
+++ b/optaplanner/pom.xml
@@ -2,14 +2,15 @@
+ 4.0.0
+ optaplanner
+ optaplanner
+
parent-modules
com.baeldung
1.0.0-SNAPSHOT
- 4.0.0
-
- optaplanner
diff --git a/parent-boot-1/README.md b/parent-boot-1/README.md
deleted file mode 100644
index ff12555376..0000000000
--- a/parent-boot-1/README.md
+++ /dev/null
@@ -1 +0,0 @@
-## Relevant articles:
diff --git a/parent-boot-1/pom.xml b/parent-boot-1/pom.xml
index 171806390d..53f91f975d 100644
--- a/parent-boot-1/pom.xml
+++ b/parent-boot-1/pom.xml
@@ -3,6 +3,7 @@
4.0.0
parent-boot-1
0.0.1-SNAPSHOT
+ parent-boot-1
pom
Parent for all Spring Boot 1.x modules
diff --git a/parent-boot-2.0-temp/README.md b/parent-boot-2.0-temp/README.md
new file mode 100644
index 0000000000..8134c8eafe
--- /dev/null
+++ b/parent-boot-2.0-temp/README.md
@@ -0,0 +1,2 @@
+This pom will be ued only temporary until we migrate parent-boot-2 to 2.1.0 for ticket BAEL-10354
+
diff --git a/parent-boot-2.0-temp/pom.xml b/parent-boot-2.0-temp/pom.xml
new file mode 100644
index 0000000000..9284e4af13
--- /dev/null
+++ b/parent-boot-2.0-temp/pom.xml
@@ -0,0 +1,85 @@
+
+ 4.0.0
+ parent-boot-2.0-temp
+ 0.0.1-SNAPSHOT
+ pom
+ Temporary Parent for all Spring Boot 2.0.x modules
+
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-dependencies
+ ${spring-boot.version}
+ pom
+ import
+
+
+
+
+
+ io.rest-assured
+ rest-assured
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+ ${spring-boot.version}
+
+ ${start-class}
+
+
+
+
+
+
+
+
+
+ thin-jar
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+