diff --git a/.gitignore b/.gitignore
index a0a519c8cb..180462a32f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -56,4 +56,9 @@ core-java-io/hard_link.txt
core-java-io/target_link.txt
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
ethereum/logs/
-jmeter/src/main/resources/*-JMeter.csv
\ No newline at end of file
+jmeter/src/main/resources/*-JMeter.csv
+
+**/node_modules/
+**/dist
+**/tmp
+**/out-tsc
diff --git a/JGit/pom.xml b/JGit/pom.xml
index d1ebd364da..176d55d321 100644
--- a/JGit/pom.xml
+++ b/JGit/pom.xml
@@ -3,10 +3,11 @@
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
- JGitSnippets
+ JGit
1.0-SNAPSHOT
jar
http://maven.apache.org
+ JGit
com.baeldung
diff --git a/JGit/src/main/resources/logback.xml b/JGit/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/JGit/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/README.md b/README.md
index d018783465..d20968b455 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
The "REST with Spring" Classes
==============================
-After 5 months of work, here's the Master Class of REST With Spring:
+Here's the Master Class of REST With Spring (price changes permanently next Friday):
**[>> THE REST WITH SPRING MASTER CLASS](http://www.baeldung.com/rest-with-spring-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=rws#master-class)**
And here's the Master Class of Learn Spring Security:
diff --git a/Twitter4J/src/main/resources/logback.xml b/Twitter4J/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/Twitter4J/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/activejdbc/src/main/resources/logback.xml b/activejdbc/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/activejdbc/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/akka-streams/src/main/resources/logback.xml b/akka-streams/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/akka-streams/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/algorithms/README.md b/algorithms/README.md
index 14ec7294e7..47ddd7028a 100644
--- a/algorithms/README.md
+++ b/algorithms/README.md
@@ -23,3 +23,4 @@
- [Converting Between Roman and Arabic Numerals in Java](http://www.baeldung.com/java-convert-roman-arabic)
- [Practical Java Examples of the Big O Notation](http://www.baeldung.com/java-algorithm-complexity)
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
+- [An Introduction to the Theory of Big-O Notation](http://www.baeldung.com/big-o-notation)
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java b/algorithms/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java
new file mode 100644
index 0000000000..0c8eb86a38
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsService.java
@@ -0,0 +1,38 @@
+package com.baeldung.algorithms.distancebetweenpoints;
+
+import java.awt.geom.Point2D;
+
+public class DistanceBetweenPointsService {
+
+ public double calculateDistanceBetweenPoints(
+ double x1,
+ double y1,
+ double x2,
+ double y2) {
+
+ return Math.sqrt((y2 - y1) * (y2 - y1) + (x2 - x1) * (x2 - x1));
+ }
+
+ public double calculateDistanceBetweenPointsWithHypot(
+ double x1,
+ double y1,
+ double x2,
+ double y2) {
+
+ double ac = Math.abs(y2 - y1);
+ double cb = Math.abs(x2 - x1);
+
+ return Math.hypot(ac, cb);
+ }
+
+ public double calculateDistanceBetweenPointsWithPoint2D(
+ double x1,
+ double y1,
+ double x2,
+ double y2) {
+
+ return Point2D.distance(x1, y1, x2, y2);
+
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java b/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java
new file mode 100644
index 0000000000..35d6c8b424
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/linesintersection/LinesIntersectionService.java
@@ -0,0 +1,21 @@
+package com.baeldung.algorithms.linesintersection;
+
+import java.awt.Point;
+import java.util.Optional;
+
+public class LinesIntersectionService {
+
+ public Optional calculateIntersectionPoint(double m1, double b1, double m2, double b2) {
+
+ if (m1 == m2) {
+ return Optional.empty();
+ }
+
+ double x = (b2 - b1) / (m1 - m2);
+ double y = m1 * x + b1;
+
+ Point point = new Point();
+ point.setLocation(x, y);
+ return Optional.of(point);
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java
index d855f775a8..5d4b265500 100644
--- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/montecarlo/State.java
@@ -87,7 +87,7 @@ public class State {
void randomPlay() {
List availablePositions = this.board.getEmptyPositions();
int totalPossibilities = availablePositions.size();
- int selectRandom = (int) (Math.random() * ((totalPossibilities - 1) + 1));
+ int selectRandom = (int) (Math.random() * totalPossibilities);
this.board.performMove(this.playerNo, availablePositions.get(selectRandom));
}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java
index 20f9e992b5..0ad6510e50 100644
--- a/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mcts/tree/Node.java
@@ -65,7 +65,7 @@ public class Node {
public Node getRandomChildNode() {
int noOfPossibleMoves = this.childArray.size();
- int selectRandom = (int) (Math.random() * ((noOfPossibleMoves - 1) + 1));
+ int selectRandom = (int) (Math.random() * noOfPossibleMoves);
return this.childArray.get(selectRandom);
}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java b/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java
new file mode 100644
index 0000000000..2dd1fdcb75
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/string/EnglishAlphabetLetters.java
@@ -0,0 +1,35 @@
+package com.baeldung.algorithms.string;
+
+public class EnglishAlphabetLetters {
+
+ public static boolean checkStringForAllTheLetters(String input) {
+ boolean[] visited = new boolean[26];
+
+ int index = 0;
+
+ for (int id = 0; id < input.length(); id++) {
+ if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
+ index = input.charAt(id) - 'a';
+ } else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
+ index = input.charAt(id) - 'A';
+ }
+ visited[index] = true;
+ }
+
+ for (int id = 0; id < 26; id++) {
+ if (!visited[id]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public static boolean checkStringForAllLetterUsingStream(String input) {
+ long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count();
+ return c == 26;
+ }
+
+ public static void main(String[] args) {
+ checkStringForAllLetterUsingStream("intit");
+ }
+}
\ No newline at end of file
diff --git a/algorithms/src/main/resources/logback.xml b/algorithms/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/algorithms/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java
similarity index 94%
rename from algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java
index b0218ae23e..2ac7adc3aa 100644
--- a/algorithms/src/test/java/algorithms/AntColonyOptimizationLongRunningUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/AntColonyOptimizationLongRunningUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
diff --git a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
similarity index 92%
rename from algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
index fa8ecdee77..e819da4b36 100644
--- a/algorithms/src/test/java/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/BinaryGeneticAlgorithmLongRunningUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
diff --git a/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
similarity index 98%
rename from algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
index 68386278fc..bbc4d4f398 100644
--- a/algorithms/src/test/java/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/DijkstraAlgorithmLongRunningUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import org.junit.Test;
diff --git a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java
similarity index 98%
rename from algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java
index e4746b521c..e817d195b3 100644
--- a/algorithms/src/test/java/algorithms/HillClimbingAlgorithmUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/HillClimbingAlgorithmUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import com.baeldung.algorithms.hillclimbing.HillClimbing;
import com.baeldung.algorithms.hillclimbing.State;
diff --git a/algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java
similarity index 99%
rename from algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java
index 01f9ca2f76..2cda0ccb36 100644
--- a/algorithms/src/test/java/algorithms/MiddleElementLookupUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/MiddleElementLookupUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import com.baeldung.algorithms.middleelementlookup.MiddleElementLookup;
import com.baeldung.algorithms.middleelementlookup.Node;
diff --git a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
similarity index 98%
rename from algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
index 99e962773f..fddccfcd9f 100644
--- a/algorithms/src/test/java/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/RtFiniteStateMachineLongRunningUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import com.baeldung.algorithms.automata.*;
import org.junit.Test;
diff --git a/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java
similarity index 90%
rename from algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java
index 6ee129ece9..2ce7d75e43 100644
--- a/algorithms/src/test/java/algorithms/SimulatedAnnealingLongRunningUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/SimulatedAnnealingLongRunningUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import org.junit.Assert;
import org.junit.Test;
diff --git a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java
similarity index 94%
rename from algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java
index c98a8a53f3..dfe015aad2 100755
--- a/algorithms/src/test/java/algorithms/StringSearchAlgorithmsUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/StringSearchAlgorithmsUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms;
+package com.baeldung.algorithms;
import org.junit.Assert;
diff --git a/algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java
similarity index 95%
rename from algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java
index 74db4236b9..826682d373 100644
--- a/algorithms/src/test/java/algorithms/binarysearch/BinarySearchUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/binarysearch/BinarySearchUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms.binarysearch;
+package com.baeldung.algorithms.binarysearch;
import java.util.Arrays;
import java.util.List;
diff --git a/algorithms/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java
new file mode 100644
index 0000000000..785afdbb2b
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/distancebetweenpoints/DistanceBetweenPointsServiceUnitTest.java
@@ -0,0 +1,54 @@
+package com.baeldung.algorithms.distancebetweenpoints;
+
+import org.junit.Test;
+
+import com.baeldung.algorithms.distancebetweenpoints.DistanceBetweenPointsService;
+
+import static org.junit.Assert.assertEquals;
+
+public class DistanceBetweenPointsServiceUnitTest {
+
+ private DistanceBetweenPointsService service = new DistanceBetweenPointsService();
+
+ @Test
+ public void givenTwoPoints_whenCalculateDistanceByFormula_thenCorrect() {
+
+ double x1 = 3;
+ double y1 = 4;
+ double x2 = 7;
+ double y2 = 1;
+
+ double distance = service.calculateDistanceBetweenPoints(x1, y1, x2, y2);
+
+ assertEquals(distance, 5, 0.001);
+
+ }
+
+ @Test
+ public void givenTwoPoints_whenCalculateDistanceWithHypot_thenCorrect() {
+
+ double x1 = 3;
+ double y1 = 4;
+ double x2 = 7;
+ double y2 = 1;
+
+ double distance = service.calculateDistanceBetweenPointsWithHypot(x1, y1, x2, y2);
+
+ assertEquals(distance, 5, 0.001);
+
+ }
+
+ @Test
+ public void givenTwoPoints_whenCalculateDistanceWithPoint2D_thenCorrect() {
+
+ double x1 = 3;
+ double y1 = 4;
+ double x2 = 7;
+ double y2 = 1;
+
+ double distance = service.calculateDistanceBetweenPointsWithPoint2D(x1, y1, x2, y2);
+
+ assertEquals(distance, 5, 0.001);
+
+ }
+}
diff --git a/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java
new file mode 100644
index 0000000000..22371107f3
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/linesintersection/LinesIntersectionServiceUnitTest.java
@@ -0,0 +1,40 @@
+package com.baeldung.algorithms.linesintersection;
+
+import java.awt.Point;
+import java.util.Optional;
+
+import org.junit.Test;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertEquals;
+
+public class LinesIntersectionServiceUnitTest {
+ private LinesIntersectionService service = new LinesIntersectionService();
+
+ @Test
+ public void givenNotParallelLines_whenCalculatePoint_thenPresent() {
+
+ double m1 = 0;
+ double b1 = 0;
+ double m2 = 1;
+ double b2 = -1;
+
+ Optional point = service.calculateIntersectionPoint(m1, b1, m2, b2);
+
+ assertTrue(point.isPresent());
+ assertEquals(point.get().getX(), 1, 0.001);
+ assertEquals(point.get().getY(), 0, 0.001);
+ }
+
+ @Test
+ public void givenParallelLines_whenCalculatePoint_thenEmpty() {
+ double m1 = 1;
+ double b1 = 0;
+ double m2 = 1;
+ double b2 = -1;
+
+ Optional point = service.calculateIntersectionPoint(m1, b1, m2, b2);
+
+ assertFalse(point.isPresent());
+ }
+}
diff --git a/algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java
similarity index 98%
rename from algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java
index edbf21390d..59afed65de 100644
--- a/algorithms/src/test/java/algorithms/mcts/MCTSUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/mcts/MCTSUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms.mcts;
+package com.baeldung.algorithms.mcts;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
diff --git a/algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java
similarity index 95%
rename from algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java
rename to algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java
index c07975bca0..59f0fcf053 100644
--- a/algorithms/src/test/java/algorithms/minimax/MinimaxUnitTest.java
+++ b/algorithms/src/test/java/com/baeldung/algorithms/minimax/MinimaxUnitTest.java
@@ -1,4 +1,4 @@
-package algorithms.minimax;
+package com.baeldung.algorithms.minimax;
import org.junit.Before;
import org.junit.Test;
diff --git a/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java
new file mode 100644
index 0000000000..54863cddc8
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/string/EnglishAlphabetLettersUnitTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.algorithms.string;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class EnglishAlphabetLettersUnitTest {
+
+ @Test
+ void givenString_whenContainsAllCharacter_thenTrue() {
+ String input = "Farmer jack realized that big yellow quilts were expensive";
+ Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(input));
+ }
+
+ @Test
+ void givenString_whenContainsAllCharacter_thenUsingStreamExpectTrue() {
+ String input = "Farmer jack realized that big yellow quilts were expensive";
+ Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllLetterUsingStream(input));
+ }
+
+}
diff --git a/animal-sniffer-mvn-plugin/src/main/resources/logback.xml b/animal-sniffer-mvn-plugin/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/animal-sniffer-mvn-plugin/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/annotations/annotation-processing/src/main/resources/logback.xml b/annotations/annotation-processing/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/annotations/annotation-processing/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/annotations/annotation-user/src/main/resources/logback.xml b/annotations/annotation-user/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/annotations/annotation-user/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/antlr/src/main/resources/logback.xml b/antlr/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/antlr/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-avro/README.md b/apache-avro/README.md
new file mode 100644
index 0000000000..32d84ecc76
--- /dev/null
+++ b/apache-avro/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Guide to Apache Avro](http://www.baeldung.com/java-apache-avro)
diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml
index 39da518269..3e3234ff96 100644
--- a/apache-avro/pom.xml
+++ b/apache-avro/pom.xml
@@ -4,8 +4,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
- apache-avro-tutorial
+ apache-avro
0.0.1-SNAPSHOT
+ Apache Avro
UTF-8
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
index d2219a45f2..7d30c3d1ee 100644
--- a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
@@ -5,29 +5,37 @@ import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.io.IOException;
public class AvroDeSerealizer {
-public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data){
- DatumReader reader = new SpecificDatumReader<>(AvroHttpRequest.class);
- Decoder decoder = null;
- try {
- decoder = DecoderFactory.get().jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
- return reader.read(null, decoder);
- } catch (IOException e) {
- return null;
- }
-}
+ private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
-public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data){
- DatumReader employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
- Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);
- try {
- return employeeReader.read(null, decoder);
- } catch (IOException e) {
+ public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) {
+ DatumReader reader = new SpecificDatumReader<>(AvroHttpRequest.class);
+ Decoder decoder = null;
+ try {
+ decoder = DecoderFactory.get()
+ .jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
+ return reader.read(null, decoder);
+ } catch (IOException e) {
+ logger.error("Deserialization error" + e.getMessage());
+ }
+ return null;
+ }
+
+ public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data) {
+ DatumReader employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
+ Decoder decoder = DecoderFactory.get()
+ .binaryDecoder(data, null);
+ try {
+ return employeeReader.read(null, decoder);
+ } catch (IOException e) {
+ logger.error("Deserialization error" + e.getMessage());
+ }
return null;
}
}
-}
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
index f56c89e201..767b688dea 100644
--- a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
@@ -3,42 +3,48 @@ package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.*;
import org.apache.avro.specific.SpecificDatumWriter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class AvroSerealizer {
-public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request){
- DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
- byte[] data = new byte[0];
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- Encoder jsonEncoder = null;
- try {
- jsonEncoder = EncoderFactory.get().jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
- writer.write(request, jsonEncoder);
- jsonEncoder.flush();
- data = stream.toByteArray();
- } catch (IOException e) {
- data =null;
- }
- return data;
-}
+ private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class);
-public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request){
- DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
- byte[] data = new byte[0];
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- Encoder jsonEncoder = EncoderFactory.get().binaryEncoder(stream,null);
- try {
- writer.write(request, jsonEncoder);
- jsonEncoder.flush();
- data = stream.toByteArray();
- } catch (IOException e) {
- data = null;
+ public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request) {
+ DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
+ byte[] data = new byte[0];
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ Encoder jsonEncoder = null;
+ try {
+ jsonEncoder = EncoderFactory.get()
+ .jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
+ writer.write(request, jsonEncoder);
+ jsonEncoder.flush();
+ data = stream.toByteArray();
+ } catch (IOException e) {
+ logger.error("Serialization error " + e.getMessage());
+ }
+ return data;
}
- return data;
-}
+ public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request) {
+ DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
+ byte[] data = new byte[0];
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ Encoder jsonEncoder = EncoderFactory.get()
+ .binaryEncoder(stream, null);
+ try {
+ writer.write(request, jsonEncoder);
+ jsonEncoder.flush();
+ data = stream.toByteArray();
+ } catch (IOException e) {
+ logger.error("Serialization error " + e.getMessage());
+ }
+
+ return data;
+ }
}
diff --git a/apache-avro/src/main/resources/logback.xml b/apache-avro/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-avro/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java
index 937a4ae650..ecd15ccbbc 100644
--- a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java
+++ b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java
@@ -24,8 +24,10 @@ public class AvroSerealizerDeSerealizerTest {
serealizer = new AvroSerealizer();
deSerealizer = new AvroDeSerealizer();
- ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder().
- setHostName("localhost").setIpAddress("255.255.255.0").build();
+ ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder()
+ .setHostName("localhost")
+ .setIpAddress("255.255.255.0")
+ .build();
List employees = new ArrayList();
employees.add("James");
@@ -33,43 +35,49 @@ public class AvroSerealizerDeSerealizerTest {
employees.add("David");
employees.add("Han");
- request = AvroHttpRequest.newBuilder().setRequestTime(01l)
- .setActive(Active.YES).setClientIdentifier(clientIdentifier)
- .setEmployeeNames(employees).build();
+ request = AvroHttpRequest.newBuilder()
+ .setRequestTime(01l)
+ .setActive(Active.YES)
+ .setClientIdentifier(clientIdentifier)
+ .setEmployeeNames(employees)
+ .build();
}
@After
public void tearDown() throws Exception {
}
-@Test
-public void WhenSerialized_UsingJSONEncoder_ObjectGetsSerialized(){
- byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
- assertTrue(Objects.nonNull(data));
- assertTrue(data.length > 0);
-}
-
-@Test
-public void WhenSerialized_UsingBinaryEncoder_ObjectGetsSerialized(){
- byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
- assertTrue(Objects.nonNull(data));
- assertTrue(data.length > 0);
-}
-
-@Test
-public void WhenDeserialize_UsingJSONDecoder_ActualAndExpectedObjectsAreEqual(){
- byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
- AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
- assertEquals(actualRequest,request);
- assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
-}
-
-@Test
-public void WhenDeserialize_UsingBinaryecoder_ActualAndExpectedObjectsAreEqual(){
- byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
- AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
- assertEquals(actualRequest,request);
- assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
-}
+ @Test
+ public void WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() {
+ byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
+ assertTrue(Objects.nonNull(data));
+ assertTrue(data.length > 0);
+ }
+
+ @Test
+ public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() {
+ byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
+ assertTrue(Objects.nonNull(data));
+ assertTrue(data.length > 0);
+ }
+
+ @Test
+ public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() {
+ byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
+ AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
+ assertEquals(actualRequest, request);
+ assertTrue(actualRequest.getRequestTime()
+ .equals(request.getRequestTime()));
+ }
+
+ @Test
+ public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() {
+ byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
+ AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
+ assertEquals(actualRequest, request);
+ assertTrue(actualRequest.getRequestTime()
+ .equals(request.getRequestTime()));
+ }
+
}
diff --git a/apache-bval/src/main/resources/logback.xml b/apache-bval/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-bval/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-cayenne/src/main/resources/logback.xml b/apache-cayenne/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-cayenne/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-curator/src/main/resources/logback.xml b/apache-curator/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-curator/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-cxf/cxf-aegis/src/main/resources/logback.xml b/apache-cxf/cxf-aegis/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-cxf/cxf-aegis/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-cxf/cxf-introduction/src/main/resources/logback.xml b/apache-cxf/cxf-introduction/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-cxf/cxf-introduction/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-cxf/cxf-jaxrs-implementation/src/main/resources/logback.xml b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-cxf/cxf-jaxrs-implementation/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-cxf/cxf-spring/src/main/resources/logback.xml b/apache-cxf/cxf-spring/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-cxf/cxf-spring/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml
index 53d9d4054c..8918fd4450 100644
--- a/apache-cxf/pom.xml
+++ b/apache-cxf/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
com.baeldung
apache-cxf
@@ -17,6 +17,7 @@
cxf-spring
cxf-jaxrs-implementation
cxf-aegis
+ sse-jaxrs
diff --git a/apache-cxf/sse-jaxrs/pom.xml b/apache-cxf/sse-jaxrs/pom.xml
new file mode 100644
index 0000000000..d4b6c19d03
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/pom.xml
@@ -0,0 +1,21 @@
+
+
+ 4.0.0
+
+ sse-jaxrs
+ pom
+
+
+ com.baeldung
+ apache-cxf
+ 0.0.1-SNAPSHOT
+
+
+
+ sse-jaxrs-server
+ sse-jaxrs-client
+
+
+
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
new file mode 100644
index 0000000000..0f5406fbc7
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
@@ -0,0 +1,62 @@
+
+
+ 4.0.0
+
+
+ com.baeldung
+ sse-jaxrs
+ 0.0.1-SNAPSHOT
+
+
+ sse-jaxrs-client
+
+
+ 3.2.0
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ 1.6.0
+
+
+ singleEvent
+
+ java
+
+
+ com.baeldung.sse.jaxrs.client.SseClientApp
+
+
+
+ broadcast
+
+ java
+
+
+ com.baeldung.sse.jaxrs.client.SseClientBroadcastApp
+
+
+
+
+
+
+
+
+
+ org.apache.cxf
+ cxf-rt-rs-client
+ ${cxf-version}
+
+
+ org.apache.cxf
+ cxf-rt-rs-sse
+ ${cxf-version}
+
+
+
+
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java
new file mode 100644
index 0000000000..5d42b3a243
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java
@@ -0,0 +1,48 @@
+package com.baeldung.sse.jaxrs.client;
+
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.sse.InboundSseEvent;
+import javax.ws.rs.sse.SseEventSource;
+import java.util.function.Consumer;
+
+public class SseClientApp {
+
+ private static final String url = "http://127.0.0.1:9080/sse-jaxrs-server/sse/stock/prices";
+
+ public static void main(String... args) throws Exception {
+
+ Client client = ClientBuilder.newClient();
+ WebTarget target = client.target(url);
+ try (SseEventSource eventSource = SseEventSource.target(target).build()) {
+
+ eventSource.register(onEvent, onError, onComplete);
+ eventSource.open();
+
+ //Consuming events for one hour
+ Thread.sleep(60 * 60 * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ client.close();
+ System.out.println("End");
+ }
+
+ // A new event is received
+ private static Consumer onEvent = (inboundSseEvent) -> {
+ String data = inboundSseEvent.readData();
+ System.out.println(data);
+ };
+
+ //Error
+ private static Consumer onError = (throwable) -> {
+ throwable.printStackTrace();
+ };
+
+ //Connection close and there is nothing to receive
+ private static Runnable onComplete = () -> {
+ System.out.println("Done!");
+ };
+
+}
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java
new file mode 100644
index 0000000000..9afc187a6d
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java
@@ -0,0 +1,52 @@
+package com.baeldung.sse.jaxrs.client;
+
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.sse.InboundSseEvent;
+import javax.ws.rs.sse.SseEventSource;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+
+public class SseClientBroadcastApp {
+
+ private static final String subscribeUrl = "http://localhost:9080/sse-jaxrs-server/sse/stock/subscribe";
+
+
+ public static void main(String... args) throws Exception {
+
+ Client client = ClientBuilder.newClient();
+ WebTarget target = client.target(subscribeUrl);
+ try (final SseEventSource eventSource = SseEventSource.target(target)
+ .reconnectingEvery(5, TimeUnit.SECONDS)
+ .build()) {
+ eventSource.register(onEvent, onError, onComplete);
+ eventSource.open();
+ System.out.println("Wainting for incoming event ...");
+
+ //Consuming events for one hour
+ Thread.sleep(60 * 60 * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ client.close();
+ System.out.println("End");
+ }
+
+ // A new event is received
+ private static Consumer onEvent = (inboundSseEvent) -> {
+ String data = inboundSseEvent.readData();
+ System.out.println(data);
+ };
+
+ //Error
+ private static Consumer onError = (throwable) -> {
+ throwable.printStackTrace();
+ };
+
+ //Connection close and there is nothing to receive
+ private static Runnable onComplete = () -> {
+ System.out.println("Done!");
+ };
+
+}
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
new file mode 100644
index 0000000000..46572a2b75
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
@@ -0,0 +1,85 @@
+
+
+ 4.0.0
+
+
+ com.baeldung
+ sse-jaxrs
+ 0.0.1-SNAPSHOT
+
+
+ sse-jaxrs-server
+ war
+
+
+ 2.4.2
+ false
+ 18.0.0.2
+
+
+
+ ${artifactId}
+
+
+ net.wasdev.wlp.maven.plugins
+ liberty-maven-plugin
+ ${liberty-maven-plugin.version}
+
+
+ io.openliberty
+ openliberty-webProfile8
+ ${openliberty-version}
+ zip
+
+ project
+ true
+ src/main/liberty/config/server.xml
+
+
+
+ install-server
+ prepare-package
+
+ install-server
+ create-server
+ install-feature
+
+
+
+ install-apps
+ package
+
+ install-apps
+
+
+
+
+
+
+
+
+
+
+ javax.ws.rs
+ javax.ws.rs-api
+ 2.1
+ provided
+
+
+ javax.enterprise
+ cdi-api
+ 2.0
+ provided
+
+
+ javax.json.bind
+ javax.json.bind-api
+ 1.0
+ provided
+
+
+
+
+
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java
new file mode 100644
index 0000000000..058d19f045
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java
@@ -0,0 +1,8 @@
+package com.baeldung.sse.jaxrs;
+
+import javax.ws.rs.ApplicationPath;
+import javax.ws.rs.core.Application;
+
+@ApplicationPath("sse")
+public class AppConfig extends Application {
+}
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java
new file mode 100644
index 0000000000..1f60168a1b
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java
@@ -0,0 +1,119 @@
+package com.baeldung.sse.jaxrs;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.sse.OutboundSseEvent;
+import javax.ws.rs.sse.Sse;
+import javax.ws.rs.sse.SseBroadcaster;
+import javax.ws.rs.sse.SseEventSink;
+
+@ApplicationScoped
+@Path("stock")
+public class SseResource {
+
+ @Inject
+ private StockService stockService;
+
+ private Sse sse;
+ private SseBroadcaster sseBroadcaster;
+ private OutboundSseEvent.Builder eventBuilder;
+
+ @Context
+ public void setSse(Sse sse) {
+ this.sse = sse;
+ this.eventBuilder = sse.newEventBuilder();
+ this.sseBroadcaster = sse.newBroadcaster();
+ }
+
+ @GET
+ @Path("prices")
+ @Produces("text/event-stream")
+ public void getStockPrices(@Context SseEventSink sseEventSink,
+ @HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastReceivedId) {
+
+ int lastEventId = 1;
+ if (lastReceivedId != -1) {
+ lastEventId = ++lastReceivedId;
+ }
+ boolean running = true;
+ while (running) {
+ Stock stock = stockService.getNextTransaction(lastEventId);
+ if (stock != null) {
+ OutboundSseEvent sseEvent = this.eventBuilder
+ .name("stock")
+ .id(String.valueOf(lastEventId))
+ .mediaType(MediaType.APPLICATION_JSON_TYPE)
+ .data(Stock.class, stock)
+ .reconnectDelay(3000)
+ .comment("price change")
+ .build();
+ sseEventSink.send(sseEvent);
+ lastEventId++;
+ }
+ //Simulate connection close
+ if (lastEventId % 5 == 0) {
+ sseEventSink.close();
+ break;
+ }
+
+ try {
+ //Wait 5 seconds
+ Thread.sleep(5 * 1000);
+ } catch (InterruptedException ex) {
+ // ...
+ }
+ //Simulatae a while boucle break
+ running = lastEventId <= 2000;
+ }
+ sseEventSink.close();
+ }
+
+ @GET
+ @Path("subscribe")
+ @Produces(MediaType.SERVER_SENT_EVENTS)
+ public void listen(@Context SseEventSink sseEventSink) {
+ sseEventSink.send(sse.newEvent("Welcome !"));
+ this.sseBroadcaster.register(sseEventSink);
+ sseEventSink.send(sse.newEvent("You are registred !"));
+ }
+
+ @GET
+ @Path("publish")
+ public void broadcast() {
+ Runnable r = new Runnable() {
+ @Override
+ public void run() {
+ int lastEventId = 0;
+ boolean running = true;
+ while (running) {
+ lastEventId++;
+ Stock stock = stockService.getNextTransaction(lastEventId);
+ if (stock != null) {
+ OutboundSseEvent sseEvent = eventBuilder
+ .name("stock")
+ .id(String.valueOf(lastEventId))
+ .mediaType(MediaType.APPLICATION_JSON_TYPE)
+ .data(Stock.class, stock)
+ .reconnectDelay(3000)
+ .comment("price change")
+ .build();
+ sseBroadcaster.broadcast(sseEvent);
+ }
+ try {
+ //Wait 5 seconds
+ Thread.currentThread().sleep(5 * 1000);
+ } catch (InterruptedException ex) {
+ // ...
+ }
+ //Simulatae a while boucle break
+ running = lastEventId <= 2000;
+ }
+ }
+ };
+ new Thread(r).start();
+ }
+}
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java
new file mode 100644
index 0000000000..a186b32771
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java
@@ -0,0 +1,50 @@
+package com.baeldung.sse.jaxrs;
+
+import java.math.BigDecimal;
+import java.time.LocalDateTime;
+
+public class Stock {
+ private Integer id;
+ private String name;
+ private BigDecimal price;
+ LocalDateTime dateTime;
+
+ public Stock(Integer id, String name, BigDecimal price, LocalDateTime dateTime) {
+ this.id = id;
+ this.name = name;
+ this.price = price;
+ this.dateTime = dateTime;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public BigDecimal getPrice() {
+ return price;
+ }
+
+ public void setPrice(BigDecimal price) {
+ this.price = price;
+ }
+
+ public LocalDateTime getDateTime() {
+ return dateTime;
+ }
+
+ public void setDateTime(LocalDateTime dateTime) {
+ this.dateTime = dateTime;
+ }
+}
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java
new file mode 100644
index 0000000000..15818ead5d
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java
@@ -0,0 +1,78 @@
+package com.baeldung.sse.jaxrs;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.context.Initialized;
+import javax.enterprise.event.Event;
+import javax.enterprise.event.Observes;
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicInteger;
+
+@ApplicationScoped
+@Named
+public class StockService {
+
+ private static final BigDecimal UP = BigDecimal.valueOf(1.05f);
+ private static final BigDecimal DOWN = BigDecimal.valueOf(0.95f);
+
+ List stockNames = Arrays.asList("GOOG", "IBM", "MS", "GOOG", "YAHO");
+ List stocksDB = new ArrayList<>();
+ private AtomicInteger counter = new AtomicInteger(0);
+
+ public void init(@Observes @Initialized(ApplicationScoped.class) Object init) {
+ //Open price
+ System.out.println("@Start Init ...");
+ stockNames.forEach(stockName -> {
+ stocksDB.add(new Stock(counter.incrementAndGet(), stockName, generateOpenPrice(), LocalDateTime.now()));
+ });
+
+ Runnable runnable = new Runnable() {
+ @Override
+ public void run() {
+ //Simulate Change price and put every x seconds
+ while (true) {
+ int indx = new Random().nextInt(stockNames.size());
+ String stockName = stockNames.get(indx);
+ BigDecimal price = getLastPrice(stockName);
+ BigDecimal newprice = changePrice(price);
+ Stock stock = new Stock(counter.incrementAndGet(), stockName, newprice, LocalDateTime.now());
+ stocksDB.add(stock);
+
+ int r = new Random().nextInt(30);
+ try {
+ Thread.currentThread().sleep(r*1000);
+ } catch (InterruptedException ex) {
+ // ...
+ }
+ }
+ }
+ };
+ new Thread(runnable).start();
+ System.out.println("@End Init ...");
+ }
+
+ public Stock getNextTransaction(Integer lastEventId) {
+ return stocksDB.stream().filter(s -> s.getId().equals(lastEventId)).findFirst().orElse(null);
+ }
+
+ BigDecimal generateOpenPrice() {
+ float min = 70;
+ float max = 120;
+ return BigDecimal.valueOf(min + new Random().nextFloat() * (max - min)).setScale(4,RoundingMode.CEILING);
+ }
+
+ BigDecimal changePrice(BigDecimal price) {
+ return Math.random() >= 0.5 ? price.multiply(UP).setScale(4,RoundingMode.CEILING) : price.multiply(DOWN).setScale(4,RoundingMode.CEILING);
+ }
+
+ private BigDecimal getLastPrice(String stockName) {
+ return stocksDB.stream().filter(stock -> stock.getName().equals(stockName)).findFirst().get().getPrice();
+ }
+}
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml
new file mode 100644
index 0000000000..9bf66d7795
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml
@@ -0,0 +1,7 @@
+
+
+ jaxrs-2.1
+ cdi-2.0
+
+
+
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml
new file mode 100644
index 0000000000..4f0b3cdeeb
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml
@@ -0,0 +1,6 @@
+
+
\ No newline at end of file
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000..b4b8121fdd
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,11 @@
+
+
+ Hello Servlet
+
+
+ index.html
+
+
+
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html
new file mode 100644
index 0000000000..9015a7a32c
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html
@@ -0,0 +1 @@
+index
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html
new file mode 100644
index 0000000000..5a46e2a5d3
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html
@@ -0,0 +1,38 @@
+
+
+
+ Server-Sent Event Broadcasting
+
+
+Stock prices :
+
+
+
+
\ No newline at end of file
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html
new file mode 100644
index 0000000000..8fddae4717
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html
@@ -0,0 +1,38 @@
+
+
+
+ Server-Sent Event
+
+
+Stock prices :
+
+
+
+
\ No newline at end of file
diff --git a/apache-fop/src/main/resources/logback.xml b/apache-fop/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/apache-fop/src/main/resources/logback.xml
+++ b/apache-fop/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/apache-meecrowave/src/main/resources/logback.xml b/apache-meecrowave/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-meecrowave/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-opennlp/src/main/resources/logback.xml b/apache-opennlp/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-opennlp/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-poi/src/main/resources/logback.xml b/apache-poi/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-poi/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-shiro/pom.xml b/apache-shiro/pom.xml
index 9e11f6948f..3a72804ab1 100644
--- a/apache-shiro/pom.xml
+++ b/apache-shiro/pom.xml
@@ -8,9 +8,10 @@
1.0-SNAPSHOT
- org.springframework.boot
- spring-boot-starter-parent
- 1.5.2.RELEASE
+ parent-boot-1
+ com.baeldung
+ 0.0.1-SNAPSHOT
+ ../parent-boot-1
diff --git a/apache-solrj/src/main/resources/logback.xml b/apache-solrj/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-solrj/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-spark/src/main/resources/logback.xml b/apache-spark/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-spark/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-thrift/pom.xml b/apache-thrift/pom.xml
index 6947cc71bc..b22364cb19 100644
--- a/apache-thrift/pom.xml
+++ b/apache-thrift/pom.xml
@@ -39,6 +39,7 @@
org.codehaus.mojo
build-helper-maven-plugin
+ ${build-helper-maven-plugin.version}
generate-sources
@@ -60,6 +61,7 @@
0.10.0
0.1.11
1.7.12
+ 3.0.0
diff --git a/apache-thrift/src/main/resources/logback.xml b/apache-thrift/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-thrift/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-tika/src/main/resources/logback.xml b/apache-tika/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-tika/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-velocity/src/main/resources/logback.xml b/apache-velocity/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/apache-velocity/src/main/resources/logback.xml
+++ b/apache-velocity/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/apache-zookeeper/src/main/resources/logback.xml b/apache-zookeeper/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-zookeeper/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/asciidoctor/src/main/resources/logback.xml b/asciidoctor/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/asciidoctor/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/asm/src/main/resources/logback.xml b/asm/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/asm/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/atomix/src/main/resources/logback.xml b/atomix/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/atomix/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/autovalue/src/main/resources/logback.xml b/autovalue/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/autovalue/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/aws-lambda/src/main/resources/logback.xml b/aws-lambda/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/aws-lambda/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/aws/pom.xml b/aws/pom.xml
index 176ecaa40d..26bc0c8037 100644
--- a/aws/pom.xml
+++ b/aws/pom.xml
@@ -137,7 +137,7 @@
1.1.0
2.8.0
1.11.290
- 2.8.9
+ 2.21.0
3.8.0
1.11.86
https://s3-us-west-2.amazonaws.com/dynamodb-local/release
diff --git a/aws/src/main/resources/logback.xml b/aws/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/aws/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/axon/src/main/resources/logback.xml b/axon/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/axon/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/azure/src/main/resources/logback.xml b/azure/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/azure/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/bootique/src/main/resources/logback.xml b/bootique/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/bootique/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cas/cas-secured-app/pom.xml b/cas/cas-secured-app/pom.xml
index 98213b2b78..22d1522fbe 100644
--- a/cas/cas-secured-app/pom.xml
+++ b/cas/cas-secured-app/pom.xml
@@ -10,10 +10,10 @@
Demo project for Spring Boot
- org.springframework.boot
- spring-boot-starter-parent
- 1.5.13.RELEASE
-
+ parent-boot-1
+ com.baeldung
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-1
diff --git a/cas/cas-secured-app/src/main/resources/logback.xml b/cas/cas-secured-app/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/cas/cas-secured-app/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cdi/src/main/resources/logback.xml b/cdi/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/cdi/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java
index 8b5fa409c9..930e913109 100644
--- a/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java
+++ b/cdi/src/test/java/com/baeldung/test/dependencyinjection/ImageProcessorUnitTest.java
@@ -1,70 +1,91 @@
package com.baeldung.test.dependencyinjection;
-import com.baeldung.dependencyinjection.imagefileeditors.GifFileEditor;
-import com.baeldung.dependencyinjection.imagefileeditors.JpgFileEditor;
-import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
-import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
-import com.baeldung.dependencyinjection.loggers.TimeLogger;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.within;
+
+import java.text.ParseException;
+import java.time.LocalTime;
+import java.time.temporal.ChronoUnit;
+
import org.jboss.weld.environment.se.Weld;
import org.jboss.weld.environment.se.WeldContainer;
import org.junit.BeforeClass;
import org.junit.Test;
+import com.baeldung.dependencyinjection.imagefileeditors.PngFileEditor;
+import com.baeldung.dependencyinjection.imageprocessors.ImageFileProcessor;
+import com.baeldung.dependencyinjection.loggers.TimeLogger;
+
public class ImageProcessorUnitTest {
-
+
private static ImageFileProcessor imageFileProcessor;
- private static SimpleDateFormat dateFormat;
- private static Calendar calendar;
-
-
+
@BeforeClass
public static void setImageProcessorInstance() {
Weld weld = new Weld();
WeldContainer container = weld.initialize();
- imageFileProcessor = container.select(ImageFileProcessor.class).get();
+ imageFileProcessor = container.select(ImageFileProcessor.class)
+ .get();
container.shutdown();
}
-
- @BeforeClass
- public static void setSimpleDateFormatInstance() {
- dateFormat = new SimpleDateFormat("HH:mm");
- }
-
- @BeforeClass
- public static void setCalendarInstance() {
- calendar = Calendar.getInstance();
- }
-
+
@Test
public void givenImageProcessorInstance_whenInjectedPngFileEditorandTimeLoggerInstances_thenTwoAssertions() {
assertThat(imageFileProcessor.getImageFileditor()).isInstanceOf(PngFileEditor.class);
assertThat(imageFileProcessor.getTimeLogger()).isInstanceOf(TimeLogger.class);
}
-
+
@Test
- public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() {
- String currentTime = dateFormat.format(calendar.getTime());
- assertThat(imageFileProcessor.openFile("file1.png")).isEqualTo("Opening PNG file file1.png at: " + currentTime);
+ public void givenImageProcessorInstance_whenCalledopenFile_thenOneAssertion() throws ParseException {
+ LocalTime currentTime = LocalTime.now();
+
+ String openFileLog = imageFileProcessor.openFile("file1.png");
+ assertThat(openFileLog).contains("Opening PNG file file1.png at: ");
+
+ LocalTime loggedTime = getLoggedTime(openFileLog);
+ assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
}
-
+
@Test
- public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() {
- String currentTime = dateFormat.format(calendar.getTime());
- assertThat(imageFileProcessor.editFile("file1.png")).isEqualTo("Editing PNG file file1.png at: " + currentTime);
+ public void givenImageProcessorInstance_whenCallededitFile_thenOneAssertion() throws ParseException {
+ LocalTime currentTime = LocalTime.now();
+
+ String editFileLog = imageFileProcessor.editFile("file1.png");
+ assertThat(editFileLog).contains("Editing PNG file file1.png at: ");
+
+ LocalTime loggedTime = getLoggedTime(editFileLog);
+ assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
}
-
+
@Test
- public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() {
- String currentTime = dateFormat.format(calendar.getTime());
- assertThat(imageFileProcessor.writeFile("file1.png")).isEqualTo("Writing PNG file file1.png at: " + currentTime);
+ public void givenImageProcessorInstance_whenCalledwriteFile_thenOneAssertion() throws ParseException {
+ LocalTime currentTime = LocalTime.now();
+
+ String writeFileLog = imageFileProcessor.writeFile("file1.png");
+ assertThat(writeFileLog).contains("Writing PNG file file1.png at: ");
+
+ LocalTime loggedTime = getLoggedTime(writeFileLog);
+ assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
}
-
+
@Test
- public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() {
- String currentTime = dateFormat.format(calendar.getTime());
- assertThat(imageFileProcessor.saveFile("file1.png")).isEqualTo("Saving PNG file file1.png at: " + currentTime);
+ public void givenImageProcessorInstance_whenCalledsaveFile_thenOneAssertion() throws ParseException {
+ LocalTime currentTime = LocalTime.now();
+
+ String saveFileLog = imageFileProcessor.saveFile("file1.png");
+ assertThat(saveFileLog).contains("Saving PNG file file1.png at: ");
+
+ LocalTime loggedTime = getLoggedTime(saveFileLog);
+ assertThat(loggedTime).isCloseTo(currentTime, within(2, ChronoUnit.MINUTES));
+ }
+
+ private LocalTime getLoggedTime(String log) throws ParseException {
+ String logTimeString = log.split("at: ")[1];
+
+ int hour = Integer.valueOf(logTimeString.split(":")[0]);
+ int minutes = Integer.valueOf(logTimeString.split(":")[1]);
+
+ LocalTime loggedTime = LocalTime.of(hour, minutes);
+ return loggedTime;
}
}
\ No newline at end of file
diff --git a/checker-plugin/src/main/resources/logback.xml b/checker-plugin/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/checker-plugin/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-groovy/src/main/resources/logback.xml b/core-groovy/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/core-groovy/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-10/README.md b/core-java-10/README.md
index 863448c194..84fa381a26 100644
--- a/core-java-10/README.md
+++ b/core-java-10/README.md
@@ -3,3 +3,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)
diff --git a/core-java-10/src/main/resources/logback.xml b/core-java-10/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/core-java-10/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-11/src/main/resources/logback.xml b/core-java-11/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/core-java-11/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-8/README.md b/core-java-8/README.md
index 8e4e5f95b5..e23a2a6d1e 100644
--- a/core-java-8/README.md
+++ b/core-java-8/README.md
@@ -9,50 +9,23 @@
- [Java 8 New Features](http://www.baeldung.com/java-8-new-features)
- [Lambda Expressions and Functional Interfaces: Tips and Best Practices](http://www.baeldung.com/java-8-lambda-expressions-tips)
- [The Double Colon Operator in Java 8](http://www.baeldung.com/java-8-double-colon-operator)
-- [Java 8 Streams Advanced](http://www.baeldung.com/java-8-streams)
-- [Introduction to Java 8 Streams](http://www.baeldung.com/java-8-streams-introduction)
- [Guide to Java 8 groupingBy Collector](http://www.baeldung.com/java-groupingby-collector)
- [Strategy Design Pattern in Java 8](http://www.baeldung.com/java-strategy-pattern)
-- [Java 8 and Infinite Streams](http://www.baeldung.com/java-inifinite-streams)
-- [String Operations with Java Streams](http://www.baeldung.com/java-stream-operations-on-strings)
- [Exceptions in Java 8 Lambda Expressions](http://www.baeldung.com/java-lambda-exceptions)
-- [Java 8 Stream findFirst() vs. findAny()](http://www.baeldung.com/java-stream-findfirst-vs-findany)
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
-- [How to Get the Last Element of a Stream in Java?](http://www.baeldung.com/java-stream-last-element)
-- [Introduction to the Java 8 Date/Time API](http://www.baeldung.com/java-8-date-time-intro)
-- [Migrating to the New Java 8 Date Time API](http://www.baeldung.com/migrating-to-java-8-date-time-api)
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
-- [Get the Current Date, Time and Timestamp in Java 8](http://www.baeldung.com/current-date-time-and-timestamp-in-java-8)
-- [TemporalAdjuster in Java](http://www.baeldung.com/java-temporal-adjuster)
-- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
-- [Merging Streams in Java](http://www.baeldung.com/java-merge-streams)
-- [“Stream has already been operated upon or closed” Exception in Java](http://www.baeldung.com/java-stream-operated-upon-or-closed-exception)
-- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
-- [Copy a File with Java](http://www.baeldung.com/java-copy-file)
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
-- [Iterable to Stream in Java](http://www.baeldung.com/java-iterable-to-stream)
-- [Converting String to Stream of chars](http://www.baeldung.com/java-string-to-stream)
-- [How to Iterate Over a Stream With Indices](http://www.baeldung.com/java-stream-indices)
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)
-- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
-- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
-- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
-- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
- [Java 8 Math New Methods](http://www.baeldung.com/java-8-math)
- [Overview of Java Built-in Annotations](http://www.baeldung.com/java-default-annotations)
- [Finding Min/Max in an Array with Java](http://www.baeldung.com/java-array-min-max)
- [Internationalization and Localization in Java 8](http://www.baeldung.com/java-8-localization)
-- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
-- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
-- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
-- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
-- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
-- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
+- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)
diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml
index 7e3b8cb280..fa0d79e405 100644
--- a/core-java-8/pom.xml
+++ b/core-java-8/pom.xml
@@ -89,11 +89,6 @@
vavr
${vavr.version}
-
- one.util
- streamex
- ${streamex.version}
-
joda-time
joda-time
@@ -151,6 +146,7 @@
org.springframework.boot
spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
@@ -176,7 +172,6 @@
1.16.12
0.9.0
1.13
- 0.6.5
2.10
3.6.1
@@ -184,6 +179,6 @@
1.7.0
1.19
1.19
+ 2.0.4.RELEASE
-
-
\ No newline at end of file
+
diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java
new file mode 100644
index 0000000000..7587cc6834
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java
@@ -0,0 +1,19 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Collection;
+import java.util.stream.Stream;
+import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
+
+public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull {
+
+ /**
+ * This method shows how to make a null safe stream from a collection through the use of
+ * emptyIfNull() method from Apache Commons CollectionUtils library
+ *
+ * @param collection The collection that is to be converted into a stream
+ * @return The stream that has been created from the collection or an empty stream if the collection is null
+ */
+ public Stream collectionAsStream(Collection collection) {
+ return emptyIfNull(collection).stream();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java
new file mode 100644
index 0000000000..ae8e399d53
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java
@@ -0,0 +1,21 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Collection;
+import java.util.Optional;
+import java.util.stream.Stream;
+
+public class NullSafeCollectionStreamsUsingJava8OptionalContainer {
+
+ /**
+ * This method shows how to make a null safe stream from a collection through the use of
+ * Java SE 8’s Optional Container
+ *
+ * @param collection The collection that is to be converted into a stream
+ * @return The stream that has been created from the collection or an empty stream if the collection is null
+ */
+ public Stream collectionAsStream(Collection collection) {
+ return Optional.ofNullable(collection)
+ .map(Collection::stream)
+ .orElseGet(Stream::empty);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java
new file mode 100644
index 0000000000..63b6d34f11
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java
@@ -0,0 +1,20 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Collection;
+import java.util.stream.Stream;
+
+public class NullSafeCollectionStreamsUsingNullDereferenceCheck {
+
+ /**
+ * This method shows how to make a null safe stream from a collection through the use of a check
+ * to prevent null dereferences
+ *
+ * @param collection The collection that is to be converted into a stream
+ * @return The stream that has been created from the collection or an empty stream if the collection is null
+ */
+ public Stream collectionAsStream(Collection collection) {
+ return collection == null ? Stream.empty() : collection.stream();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java b/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java
new file mode 100644
index 0000000000..46018faf80
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java
@@ -0,0 +1,9 @@
+package com.baeldung.optional;
+
+public class PersonRepository {
+
+ public String findNameById(String id) {
+ return id == null ? null : "Name";
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java b/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java
new file mode 100644
index 0000000000..2513ec0d03
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java
@@ -0,0 +1,23 @@
+package com.baeldung.primitive;
+
+public class BenchmarkRunner {
+
+ public static void main(String[] args) throws Exception {
+ new IntPrimitiveLookup().run();
+ new IntegerWrapperLookup().run();
+ new FloatPrimitiveLookup().run();
+ new FloatWrapperLookup().run();
+ new DoublePrimitiveLookup().run();
+ new DoubleWrapperLookup().run();
+ new ShortPrimitiveLookup().run();
+ new ShortWrapperLookup().run();
+ new BooleanPrimitiveLookup().run();
+ new BooleanWrapperLookup().run();
+ new CharPrimitiveLookup().run();
+ new CharacterWrapperLookup().run();
+ new BytePrimitiveLookup().run();
+ new ByteWrapperLookup().run();
+ new LongPrimitiveLookup().run();
+ new LongWrapperLookup().run();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java
new file mode 100644
index 0000000000..2ad698eba4
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class BooleanPrimitiveLookup extends Lookup {
+
+ private boolean[] elements;
+ private final boolean pivot = false;
+
+ @Setup
+ @Override
+ public void prepare() {
+ elements = new boolean[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = true;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return BooleanPrimitiveLookup.class.getSimpleName();
+ }
+
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java
new file mode 100644
index 0000000000..8d996739a8
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class BooleanWrapperLookup extends Lookup {
+ private Boolean[] elements;
+ private final boolean pivot = false;
+
+ @Override
+ @Setup
+ public void prepare() {
+ elements = new Boolean[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = true;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Boolean pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return BooleanWrapperLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java
new file mode 100644
index 0000000000..73eda5cf5b
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class BytePrimitiveLookup extends Lookup {
+
+ private byte[] elements;
+ private final byte pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ byte common = 1;
+ elements = new byte[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return BytePrimitiveLookup.class.getSimpleName();
+ }
+
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java
new file mode 100644
index 0000000000..23e02315a6
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class ByteWrapperLookup extends Lookup {
+ private Byte[] elements;
+ private final byte pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ byte common = 1;
+ elements = new Byte[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Byte pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return ByteWrapperLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java
new file mode 100644
index 0000000000..a6d4be6206
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class CharPrimitiveLookup extends Lookup {
+
+ private char[] elements;
+ private final char pivot = 'b';
+
+ @Setup
+ @Override
+ public void prepare() {
+ char common = 'a';
+ elements = new char[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return CharPrimitiveLookup.class.getSimpleName();
+ }
+
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java
new file mode 100644
index 0000000000..9509b4a156
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class CharacterWrapperLookup extends Lookup {
+ private Character[] elements;
+ private final char pivot = 'b';
+
+ @Override
+ @Setup
+ public void prepare() {
+ char common = 'a';
+ elements = new Character[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Character pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return CharacterWrapperLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java
new file mode 100644
index 0000000000..f95515a02d
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java
@@ -0,0 +1,42 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class DoublePrimitiveLookup extends Lookup {
+ private double[] elements;
+ private final double pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ double common = 1;
+ elements = new double[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return DoublePrimitiveLookup.class.getSimpleName();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java
new file mode 100644
index 0000000000..671c2ccc29
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class DoubleWrapperLookup extends Lookup {
+ private Double[] elements;
+ private final double pivot = 2d;
+
+ @Override
+ @Setup
+ public void prepare() {
+ double common = 1;
+ elements = new Double[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Double pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return DoubleWrapperLookup.class.getSimpleName();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java
new file mode 100644
index 0000000000..26b58f0053
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java
@@ -0,0 +1,42 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class FloatPrimitiveLookup extends Lookup {
+ private float[] elements;
+ private final float pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ int common = 1;
+ elements = new float[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return FloatPrimitiveLookup.class.getSimpleName();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java
new file mode 100644
index 0000000000..8e75eae3e3
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java
@@ -0,0 +1,43 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class FloatWrapperLookup extends Lookup {
+ private Float[] elements;
+ private final float pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ float common = 1;
+ elements = new Float[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Float pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return FloatWrapperLookup.class.getSimpleName();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java
new file mode 100644
index 0000000000..551163dba2
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class IntPrimitiveLookup extends Lookup {
+
+ private int[] elements;
+ private final int pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ int common = 1;
+ elements = new int[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return IntPrimitiveLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java
new file mode 100644
index 0000000000..f39fb80a0b
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class IntegerWrapperLookup extends Lookup {
+ private Integer[] elements;
+ private final int pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ int common = 1;
+ elements = new Integer[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Integer pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return IntegerWrapperLookup.class.getSimpleName();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java
new file mode 100644
index 0000000000..2f414577da
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java
@@ -0,0 +1,42 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class LongPrimitiveLookup extends Lookup {
+ private long[] elements;
+ private final long pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ long common = 1;
+ elements = new long[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return LongPrimitiveLookup.class.getSimpleName();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java
new file mode 100644
index 0000000000..692a9fd15c
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class LongWrapperLookup extends Lookup{
+ private Long[] elements;
+ private final long pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ long common = 1;
+ elements = new Long[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Long pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return LongWrapperLookup.class.getSimpleName();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java b/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java
new file mode 100644
index 0000000000..3dc7b7655e
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java
@@ -0,0 +1,56 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.results.RunResult;
+import org.openjdk.jmh.runner.Runner;
+import org.openjdk.jmh.runner.RunnerException;
+import org.openjdk.jmh.runner.options.Options;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+import java.util.Collection;
+
+/**
+ * An abstract class that is to be extended by the classes that
+ * perform lookup in the arrays either of Java primitive types or their wrappers.
+ */
+public abstract class Lookup {
+ /**
+ * the array size
+ */
+ final protected int s = 50000000;
+
+ /**
+ * Initialize the array: fill in the array with the same
+ * elements except for the last one.
+ */
+ abstract public void prepare();
+
+ /**
+ * Free the array's reference.
+ */
+ abstract public void clean();
+
+ /**
+ * Find the position of the element that is different from the others.
+ * By construction, it is the last array element.
+ *
+ * @return array's last element index
+ */
+ abstract public int findPosition();
+
+ /**
+ * Get the name of the class that extends this one. It is needed in order
+ * to set up the benchmark.
+ *
+ * @return
+ */
+ abstract public String getSimpleClassName();
+
+ Collection run() throws RunnerException {
+ Options opt = new OptionsBuilder()
+ .include(getSimpleClassName())
+ .forks(1)
+ .build();
+ return new Runner(opt).run();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java
new file mode 100644
index 0000000000..2d2ffbd67b
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class ShortPrimitiveLookup extends Lookup {
+
+ private short[] elements;
+ private final short pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ short common = 1;
+ elements = new short[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return ShortPrimitiveLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java
new file mode 100644
index 0000000000..1c1cd4a345
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class ShortWrapperLookup extends Lookup {
+ private Short[] elements;
+ private final short pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ short common = 1;
+ elements = new Short[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Short pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return ShortWrapperLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/resources/logback.xml b/core-java-8/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/core-java-8/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java
new file mode 100644
index 0000000000..f68df2c821
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.stream.Stream;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+
+public class NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest {
+
+ private final NullSafeCollectionStreamsUsingCommonsEmptyIfNull instance =
+ new NullSafeCollectionStreamsUsingCommonsEmptyIfNull();
+
+ @Test
+ public void whenCollectionIsNull_thenExpectAnEmptyStream() {
+ Collection collection = null;
+ Stream expResult = Stream.empty();
+ Stream result = instance.collectionAsStream(collection);
+ assertStreamEquals(expResult, result);
+
+ }
+
+ @Test
+ public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
+
+ Collection collection = Arrays.asList("a", "b", "c");
+ Stream expResult = Arrays.stream(new String[] { "a", "b", "c" });
+ Stream result = instance.collectionAsStream(collection);
+ assertStreamEquals(expResult, result);
+ }
+
+ private static void assertStreamEquals(Stream> s1, Stream> s2) {
+ Iterator> iter1 = s1.iterator(), iter2 = s2.iterator();
+ while (iter1.hasNext() && iter2.hasNext())
+ assertEquals(iter1.next(), iter2.next());
+ assert !iter1.hasNext() && !iter2.hasNext();
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java
new file mode 100644
index 0000000000..df6c72d346
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java
@@ -0,0 +1,50 @@
+/*
+ * To change this license header, choose License Headers in Project Properties.
+ * To change this template file, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package com.baeldung.nullsafecollectionstreams;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.stream.Stream;
+
+import org.junit.Test;
+
+/**
+ *
+ * @author Kwaje Anthony
+ */
+public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
+
+ private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance = new NullSafeCollectionStreamsUsingJava8OptionalContainer();
+
+ @Test
+ public void whenCollectionIsNull_thenExpectAnEmptyStream() {
+ Collection collection = null;
+ Stream expResult = Stream.empty();
+ Stream result = instance.collectionAsStream(collection);
+ assertStreamEquals(expResult, result);
+
+ }
+
+ @Test
+ public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
+
+ Collection collection = Arrays.asList("a", "b", "c");
+ Stream expResult = Arrays.stream(new String[] { "a", "b", "c" });
+ Stream result = instance.collectionAsStream(collection);
+ assertStreamEquals(expResult, result);
+ }
+
+ private static void assertStreamEquals(Stream> s1, Stream> s2) {
+ Iterator> iter1 = s1.iterator(), iter2 = s2.iterator();
+ while (iter1.hasNext() && iter2.hasNext())
+ assertEquals(iter1.next(), iter2.next());
+ assert !iter1.hasNext() && !iter2.hasNext();
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java
new file mode 100644
index 0000000000..ddb4dcdc12
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java
@@ -0,0 +1,45 @@
+
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.stream.Stream;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+/**
+ *
+ * @author Kwaje Anthony
+ */
+public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest {
+
+ private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance =
+ new NullSafeCollectionStreamsUsingNullDereferenceCheck();
+
+ @Test
+ public void whenCollectionIsNull_thenExpectAnEmptyStream() {
+ Collection collection = null;
+ Stream expResult = Stream.empty();
+ Stream result = instance.collectionAsStream(collection);
+ assertStreamEquals(expResult, result);
+
+ }
+
+ @Test
+ public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
+
+ Collection collection = Arrays.asList("a", "b", "c");
+ Stream expResult = Arrays.stream(new String[] { "a", "b", "c" });
+ Stream result = instance.collectionAsStream(collection);
+ assertStreamEquals(expResult, result);
+ }
+
+ private static void assertStreamEquals(Stream> s1, Stream> s2) {
+ Iterator> iter1 = s1.iterator(), iter2 = s2.iterator();
+ while (iter1.hasNext() && iter2.hasNext())
+ assertEquals(iter1.next(), iter2.next());
+ assert !iter1.hasNext() && !iter2.hasNext();
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java b/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java
new file mode 100644
index 0000000000..4efa625ccd
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/optional/PersonRepositoryUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.optional;
+
+import org.junit.Test;
+
+import java.util.Optional;
+
+import static org.junit.jupiter.api.Assertions.assertAll;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class PersonRepositoryUnitTest {
+
+ PersonRepository personRepository = new PersonRepository();
+
+ @Test
+ public void whenIdIsNull_thenExceptionIsThrown() {
+ assertThrows(IllegalArgumentException.class,
+ () ->
+ Optional
+ .ofNullable(personRepository.findNameById(null))
+ .orElseThrow(IllegalArgumentException::new));
+ }
+
+ @Test
+ public void whenIdIsNonNull_thenNoExceptionIsThrown() {
+ assertAll(
+ () ->
+ Optional
+ .ofNullable(personRepository.findNameById("id"))
+ .orElseThrow(RuntimeException::new));
+ }
+
+ @Test
+ public void whenIdNonNull_thenReturnsNameUpperCase() {
+ String name = Optional
+ .ofNullable(personRepository.findNameById("id"))
+ .map(String::toUpperCase)
+ .orElseThrow(RuntimeException::new);
+
+ assertEquals("NAME", name);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java
index 1689a5054d..ec20b7794b 100644
--- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java
+++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java
@@ -1,7 +1,6 @@
package com.baeldung.util;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import java.time.Clock;
import java.time.Instant;
@@ -10,8 +9,6 @@ import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
-import org.joda.time.DateTime;
-import org.joda.time.DateTimeUtils;
import org.junit.Test;
public class CurrentDateTimeUnitTest {
diff --git a/core-java-9/README.md b/core-java-9/README.md
index a76dcefc69..6fa2c24f9e 100644
--- a/core-java-9/README.md
+++ b/core-java-9/README.md
@@ -15,10 +15,7 @@
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)
- [Java 9 Optional API Additions](http://www.baeldung.com/java-9-optional)
- [Java 9 Reactive Streams](http://www.baeldung.com/java-9-reactive-streams)
-- [How to Get All Dates Between Two Dates?](http://www.baeldung.com/java-between-dates)
- [Java 9 java.util.Objects Additions](http://www.baeldung.com/java-9-objects-new)
-- [Compact Strings in Java 9](http://www.baeldung.com/java-9-compact-string)
-- [Convert Date to LocalDate or LocalDateTime and Back](http://www.baeldung.com/java-date-to-localdate-and-localdatetime)
- [Java 9 Variable Handles Demistyfied](http://www.baeldung.com/java-variable-handles)
- [Exploring the New HTTP Client in Java 9](http://www.baeldung.com/java-9-http-client)
- [Method Handles in Java](http://www.baeldung.com/java-method-handles)
@@ -26,3 +23,4 @@
- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)
+- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
diff --git a/core-java-9/src/main/java/com/baeldung/java9/maps/initialize/MapsInitializer.java b/core-java-9/src/main/java/com/baeldung/java9/maps/initialize/MapsInitializer.java
new file mode 100644
index 0000000000..2a8ce588bb
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/maps/initialize/MapsInitializer.java
@@ -0,0 +1,33 @@
+package com.baeldung.java9.maps.initialize;
+
+import java.util.AbstractMap;
+import java.util.HashMap;
+import java.util.Map;
+
+public class MapsInitializer {
+
+ @SuppressWarnings("unused")
+ public void createMapWithMapOf() {
+ Map emptyMap = Map.of();
+ Map singletonMap = Map.of("key1", "value");
+ Map map = Map.of("key1","value1", "key2", "value2");
+ }
+
+ public void createMapWithMapEntries() {
+ Map map = Map.ofEntries(
+ new AbstractMap.SimpleEntry("name", "John"),
+ new AbstractMap.SimpleEntry("city", "budapest"),
+ new AbstractMap.SimpleEntry("zip", "000000"),
+ new AbstractMap.SimpleEntry("home", "1231231231")
+ );
+ }
+
+ @SuppressWarnings("unused")
+ public void createMutableMaps() {
+ Map map = new HashMap (Map.of("key1","value1", "key2", "value2"));
+ Map map2 = new HashMap ( Map.ofEntries(
+ new AbstractMap.SimpleEntry("name", "John"),
+ new AbstractMap.SimpleEntry("city", "budapest")));
+
+ }
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java b/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java
new file mode 100644
index 0000000000..46c2e688ce
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/process/ChildProcess.java
@@ -0,0 +1,15 @@
+package com.baeldung.java9.process;
+
+import java.util.Scanner;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class ChildProcess {
+
+ public static void main(String[] args) {
+ @SuppressWarnings("resource")
+ Scanner input = new Scanner(System.in);
+ Logger log = Logger.getLogger(ChildProcess.class.getName());
+ log.log(Level.INFO, input.nextLine());
+ }
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java b/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java
new file mode 100644
index 0000000000..443847916a
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/process/OutputStreamExample.java
@@ -0,0 +1,16 @@
+package com.baeldung.java9.process;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class OutputStreamExample {
+
+ public static void main(String[] args) {
+ Logger log = Logger.getLogger(OutputStreamExample.class.getName());
+ log.log(Level.INFO, Integer.toString(sum(1,2)));
+ }
+
+ public static int sum(int a, int b) {
+ return a + b;
+ }
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java
new file mode 100644
index 0000000000..8b6ae0b441
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessCompilationError.java
@@ -0,0 +1,7 @@
+package com.baeldung.java9.process;
+
+public class ProcessCompilationError {
+ //This method has been written to generate error to display
+ //how process errorStream() can consume error
+ public static void();
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java
new file mode 100644
index 0000000000..74101ba3da
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/process/ProcessUnderstanding.java
@@ -0,0 +1,110 @@
+package com.baeldung.java9.process;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.util.Optional;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class ProcessUnderstanding {
+
+ public static int compileAndRunJavaProgram() throws IOException {
+ Process process = Runtime.getRuntime()
+ .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
+ process = Runtime.getRuntime()
+ .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
+ BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ int value = Integer.parseInt(output.readLine());
+ return value;
+ }
+
+ public static String getErrorStreamExample() throws IOException {
+ Process process = Runtime.getRuntime()
+ .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
+ BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String errorString = error.readLine();
+ return errorString;
+ }
+
+ public static void creatingNewProcess() throws IOException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ }
+
+ public static int filterProcessWithStreamsInSpecificRangeReturnCount() {
+ return (int) ProcessHandle.allProcesses()
+ .filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
+ .count();
+ }
+
+ public static void destroyingProcessCreatedBySameProcess() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ Thread.sleep(10000);
+ process.destroy();
+ }
+
+ public static void destroyingProcessCreatedByDifferentProcess() {
+ // find out the process id of current running task by checking
+ // task manager in windows and enter the integer value
+ Optional optionalProcessHandle = ProcessHandle.of(5232);
+ ProcessHandle processHandle = optionalProcessHandle.get();
+ processHandle.destroy();
+ }
+
+ public static int waitForExample() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ return process.waitFor();
+ }
+
+ public static int exitValueExample() throws IOException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ process.destroy();
+ return process.exitValue();
+ }
+
+ public static void destroyExample() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ Thread.sleep(10000);
+ process.destroy();
+ }
+
+ public static void destroyForciblyExample() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ Thread.sleep(10000);
+ process.destroy();
+ if (process.isAlive()) {
+ process.destroyForcibly();
+ }
+ }
+
+ public static void outputStreamDemo() throws IOException, InterruptedException {
+ Logger log = Logger.getLogger(ProcessUnderstanding.class.getName());
+ Process pr = Runtime.getRuntime()
+ .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java");
+ final Process process = Runtime.getRuntime()
+ .exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess");
+ try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) {
+ w.write("send to child\n");
+ }
+ new Thread(() -> {
+ try {
+ int c;
+ while ((c = process.getInputStream()
+ .read()) != -1)
+ System.out.write((byte) c);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }).start();
+ // send to child
+ log.log(Level.INFO, "rc=" + process.waitFor());
+ }
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/rangedates/DatesCollectionIteration.java b/core-java-9/src/main/java/com/baeldung/java9/rangedates/DatesCollectionIteration.java
new file mode 100644
index 0000000000..f5ec5d29dc
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/rangedates/DatesCollectionIteration.java
@@ -0,0 +1,24 @@
+package com.baeldung.java9.rangedates;
+
+import java.util.Collection;
+import java.util.Date;
+
+public class DatesCollectionIteration {
+
+ public void iteratingRangeOfDatesJava7(Collection dates) {
+
+ for (Date date : dates) {
+ processDate(date);
+ }
+ }
+
+ public void iteratingRangeOfDatesJava8(Collection dates) {
+ dates.stream()
+ .forEach(this::processDate);
+ }
+
+ private void processDate(Date date) {
+ System.out.println(date);
+ }
+
+}
diff --git a/core-java-9/src/main/java/com/baeldung/java9/rangedates/RangeDatesIteration.java b/core-java-9/src/main/java/com/baeldung/java9/rangedates/RangeDatesIteration.java
new file mode 100644
index 0000000000..4972036c91
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/rangedates/RangeDatesIteration.java
@@ -0,0 +1,43 @@
+package com.baeldung.java9.rangedates;
+
+import java.time.LocalDate;
+import java.util.Calendar;
+import java.util.Date;
+
+public class RangeDatesIteration {
+
+ public void iterateBetweenDatesJava9(LocalDate startDate, LocalDate endDate) {
+
+ startDate.datesUntil(endDate)
+ .forEach(this::processDate);
+ }
+
+ public void iterateBetweenDatesJava8(LocalDate start, LocalDate end) {
+ for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
+ processDate(date);
+ }
+ }
+
+ public void iterateBetweenDatesJava7(Date start, Date end) {
+ Date current = start;
+
+ while (current.before(end)) {
+ processDate(current);
+
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(current);
+
+ calendar.add(Calendar.DATE, 1);
+
+ current = calendar.getTime();
+ }
+ }
+
+ private void processDate(LocalDate date) {
+ System.out.println(date);
+ }
+
+ private void processDate(Date date) {
+ System.out.println(date);
+ }
+}
diff --git a/core-java-9/src/main/resources/logback.xml b/core-java-9/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/core-java-9/src/main/resources/logback.xml
+++ b/core-java-9/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java
new file mode 100644
index 0000000000..2f61846c1c
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/process/ProcessUnderstandingTest.java
@@ -0,0 +1,121 @@
+package com.baeldung.java9.process;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.lang.String;
+import java.util.Optional;
+import java.util.concurrent.TimeUnit;
+import java.lang.Integer;
+
+import org.junit.jupiter.api.Test;
+
+class ProcessUnderstandingTest {
+
+ @Test
+ public void givenSourceProgram_whenExecutedFromAnotherProgram_thenSourceProgramOutput3() throws IOException {
+ Process process = Runtime.getRuntime()
+ .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
+ process = Runtime.getRuntime()
+ .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
+ BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ int value = Integer.parseInt(output.readLine());
+ assertEquals(3, value);
+ }
+
+ @Test
+ public void givenSourceProgram_whenReadingInputStream_thenFirstLineEquals3() throws IOException {
+ Process process = Runtime.getRuntime()
+ .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\OutputStreamExample.java");
+ process = Runtime.getRuntime()
+ .exec("java -cp src/main/java com.baeldung.java9.process.OutputStreamExample");
+ BufferedReader output = new BufferedReader(new InputStreamReader(process.getInputStream()));
+ int value = Integer.parseInt(output.readLine());
+ assertEquals(3, value);
+ }
+
+ @Test
+ public void givenSubProcess_whenEncounteringError_thenErrorStreamNotNull() throws IOException {
+ Process process = Runtime.getRuntime()
+ .exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ProcessCompilationError.java");
+ BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+ String errorString = error.readLine();
+ assertNotNull(errorString);
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_thenStartSuccessIsAlive() throws IOException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ assertTrue(builder.start().isAlive());
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_whenDestroying_thenProcessNotAlive() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ Thread.sleep(10000);
+ process.destroy();
+ assertFalse(process.isAlive());
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_whenAlive_thenDestroyForcibly() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ Thread.sleep(10000);
+ process.destroy();
+ if (process.isAlive()) {
+ process.destroyForcibly();
+ }
+ assertFalse(process.isAlive());
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_checkAlive() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ Thread.sleep(10000);
+ process.destroy();
+ assertFalse(process.isAlive());
+ }
+
+ @Test
+ public void givenProcessNotCreated_fromWithinJavaApplicationDestroying_thenProcessNotAlive() {
+ Optional optionalProcessHandle = ProcessHandle.of(5232);
+ ProcessHandle processHandle = optionalProcessHandle.get();
+ processHandle.destroy();
+ assertFalse(processHandle.isAlive());
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_whenCurrentThreadWaitsIndefinitelyuntilSubProcessEnds_thenProcessWaitForReturnsGrt0() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ assertThat(process.waitFor() >= 0);
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_whenCurrentThreadWaitsAndSubProcessNotTerminated_thenProcessWaitForReturnsFalse() throws IOException, InterruptedException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ assertFalse(process.waitFor(1, TimeUnit.SECONDS));
+ }
+
+ //@Test - windows specific
+ public void givenSubProcess_whenCurrentThreadWillNotWaitIndefinitelyforSubProcessToEnd_thenProcessExitValueReturnsGrt0() throws IOException {
+ ProcessBuilder builder = new ProcessBuilder("notepad.exe");
+ Process process = builder.start();
+ assertThat(process.exitValue() >= 0);
+ }
+
+ @Test
+ public void givenRunningProcesses_whenFilterOnProcessIdRange_thenGetSelectedProcessPid() {
+ assertThat(((int) ProcessHandle.allProcesses()
+ .filter(ph -> (ph.pid() > 10000 && ph.pid() < 50000))
+ .count()) > 0);
+ }
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/rangedates/DatesCollectionIterationUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/rangedates/DatesCollectionIterationUnitTest.java
new file mode 100644
index 0000000000..522b00065e
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/rangedates/DatesCollectionIterationUnitTest.java
@@ -0,0 +1,61 @@
+package com.baeldung.java9.rangedates;
+
+import java.time.LocalDate;
+import java.time.ZoneId;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.junit.Test;
+
+public class DatesCollectionIterationUnitTest {
+
+ private Collection localDates = LocalDate.now()
+ .datesUntil(LocalDate.now()
+ .plus(10L, ChronoUnit.DAYS))
+ .collect(Collectors.toList());
+
+ private Collection dates = localDates.stream()
+ .map(localDate -> Date.from(localDate.atStartOfDay(ZoneId.systemDefault())
+ .toInstant()))
+ .collect(Collectors.toList());
+
+ @Test
+ public void givenIteratingListOfDatesJava7_WhenStartTodayAndEnding10DaysAhead() {
+ DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration();
+ Calendar today = Calendar.getInstance();
+ Calendar next10Ahead = (Calendar) today.clone();
+ next10Ahead.add(Calendar.DATE, 10);
+
+ iterateInColleciton.iteratingRangeOfDatesJava7(createRangeDates(today.getTime(), next10Ahead.getTime()));
+ }
+
+ @Test
+ public void givenIteratingListOfDatesJava8_WhenStartTodayAndEnd10DaysAhead() {
+ DatesCollectionIteration iterateInColleciton = new DatesCollectionIteration();
+
+ iterateInColleciton.iteratingRangeOfDatesJava8(dates);
+ }
+
+ private List createRangeDates(Date start, Date end) {
+
+ List dates = new ArrayList<>();
+ Date current = start;
+
+ while (current.before(end)) {
+ dates.add(current);
+
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(current);
+ calendar.add(Calendar.DATE, 1);
+
+ current = calendar.getTime();
+ }
+
+ return dates;
+ }
+}
diff --git a/core-java-9/src/test/java/com/baeldung/java9/rangedates/RangeDatesIterationUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/rangedates/RangeDatesIterationUnitTest.java
new file mode 100644
index 0000000000..4f5cd17d98
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/rangedates/RangeDatesIterationUnitTest.java
@@ -0,0 +1,48 @@
+package com.baeldung.java9.rangedates;
+
+import java.time.LocalDate;
+import java.time.temporal.ChronoUnit;
+import java.util.Calendar;
+import java.util.Date;
+
+import org.junit.Test;
+
+public class RangeDatesIterationUnitTest {
+
+ @Test
+ public void givenIterateBetweenDatesJava9_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
+ LocalDate start = LocalDate.now();
+ LocalDate end = start.plus(10L, ChronoUnit.DAYS);
+
+ RangeDatesIteration iteration = new RangeDatesIteration();
+
+ iteration.iterateBetweenDatesJava9(start, end);
+ }
+
+ @Test
+ public void givenIterateBetweenDatesJava8_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
+ LocalDate start = LocalDate.now();
+ LocalDate end = start.plus(10L, ChronoUnit.DAYS);
+
+ RangeDatesIteration iteration = new RangeDatesIteration();
+
+ iteration.iterateBetweenDatesJava8(start, end);
+ }
+
+ @Test
+ public void givenIterateBetweenDatesJava7_WhenStartDateAsTodayAndEndDateAs10DaysAhead() {
+ Calendar today = Calendar.getInstance();
+ Calendar calendar = Calendar.getInstance();
+ calendar.clear();
+ calendar.set(today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
+ Date start = calendar.getTime();
+
+ calendar.add(Calendar.DATE, 10);
+ Date end = calendar.getTime();
+
+ RangeDatesIteration iteration = new RangeDatesIteration();
+
+ iteration.iterateBetweenDatesJava7(start, end);
+ }
+
+}
diff --git a/core-java-collections/README.md b/core-java-collections/README.md
index 7b3745b486..ab13ba7c01 100644
--- a/core-java-collections/README.md
+++ b/core-java-collections/README.md
@@ -31,3 +31,15 @@
- [How to Store Duplicate Keys in a Map in Java?](http://www.baeldung.com/java-map-duplicate-keys)
- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size)
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
+- [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering)
+- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
+- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
+- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
+- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
+- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
+- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
+- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
+- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
+- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
+- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
+- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml
index ff06714bfe..92e4278593 100644
--- a/core-java-collections/pom.xml
+++ b/core-java-collections/pom.xml
@@ -36,11 +36,6 @@
commons-lang3
${commons-lang3.version}
-
- org.eclipse.collections
- eclipse-collections-api
- ${eclipse.collections.version}
-
org.eclipse.collections
eclipse-collections
@@ -58,15 +53,27 @@
${junit.platform.version}
test
+
+ org.openjdk.jmh
+ jmh-core
+ ${openjdk.jmh.version}
+
+
+ org.openjdk.jmh
+ jmh-generator-annprocess
+ ${openjdk.jmh.version}
+
+
+ 1.19
1.2.0
3.5
4.1
4.01
1.7.0
3.6.1
- 9.2.0
+ 7.1.0
diff --git a/core-java-8/src/main/java/com/baeldung/findanelement/Customer.java b/core-java-collections/src/main/java/com/baeldung/findanelement/Customer.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/findanelement/Customer.java
rename to core-java-collections/src/main/java/com/baeldung/findanelement/Customer.java
diff --git a/core-java-8/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java b/core-java-collections/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java
rename to core-java-collections/src/main/java/com/baeldung/findanelement/FindACustomerInGivenList.java
diff --git a/core-java-8/src/main/java/com/baeldung/hashtable/Word.java b/core-java-collections/src/main/java/com/baeldung/hashtable/Word.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/hashtable/Word.java
rename to core-java-collections/src/main/java/com/baeldung/hashtable/Word.java
diff --git a/core-java-8/src/main/java/com/baeldung/iterators/Iterators.java b/core-java-collections/src/main/java/com/baeldung/iterators/Iterators.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/iterators/Iterators.java
rename to core-java-collections/src/main/java/com/baeldung/iterators/Iterators.java
diff --git a/core-java-8/src/main/java/com/baeldung/list/CopyListService.java b/core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java
similarity index 98%
rename from core-java-8/src/main/java/com/baeldung/list/CopyListService.java
rename to core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java
index 55d5bb9379..5c92d856aa 100644
--- a/core-java-8/src/main/java/com/baeldung/list/CopyListService.java
+++ b/core-java-collections/src/main/java/com/baeldung/java/list/CopyListService.java
@@ -1,4 +1,4 @@
-package com.baeldung.list;
+package com.baeldung.java.list;
import java.util.ArrayList;
import java.util.Collections;
diff --git a/core-java-collections/src/main/java/com/baeldung/java/list/Flower.java b/core-java-collections/src/main/java/com/baeldung/java/list/Flower.java
new file mode 100644
index 0000000000..eb897ea72f
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/java/list/Flower.java
@@ -0,0 +1,28 @@
+package com.baeldung.java.list;
+
+public class Flower {
+
+ private String name;
+ private int petals;
+
+ public Flower(String name, int petals) {
+ this.name = name;
+ this.petals = petals;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int getPetals() {
+ return petals;
+ }
+
+ public void setPetals(int petals) {
+ this.petals = petals;
+ }
+}
diff --git a/core-java-collections/src/main/java/com/baeldung/java/map/initialize/MapInitializer.java b/core-java-collections/src/main/java/com/baeldung/java/map/initialize/MapInitializer.java
new file mode 100644
index 0000000000..4dbaceac62
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/java/map/initialize/MapInitializer.java
@@ -0,0 +1,80 @@
+package com.baeldung.java.map.initialize;
+
+import java.util.AbstractMap;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class MapInitializer {
+
+ public static Map articleMapOne;
+ static {
+ articleMapOne = new HashMap<>();
+ articleMapOne.put("ar01", "Intro to Map");
+ articleMapOne.put("ar02", "Some article");
+ }
+
+ public static Map createSingletonMap() {
+ Map passwordMap = Collections.singletonMap("username1", "password1");
+ return passwordMap;
+
+ }
+
+ public Map createEmptyMap() {
+ Map emptyMap = Collections.emptyMap();
+ return emptyMap;
+ }
+
+ public Map createUsingDoubleBrace() {
+ Map doubleBraceMap = new HashMap() {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ {
+ put("key1", "value1");
+ put("key2", "value2");
+ }
+ };
+ return doubleBraceMap;
+ }
+
+ public Map createMapUsingStreamStringArray() {
+ Map map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
+ .collect(Collectors.toMap(data -> data[0], data -> data[1]));
+
+ return map;
+ }
+
+ public Map createMapUsingStreamObjectArray() {
+ Map map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, })
+ .collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1]));
+
+ return map;
+ }
+
+ public Map createMapUsingStreamSimpleEntry() {
+ Map map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2))
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+
+ return map;
+ }
+
+ public Map createMapUsingStreamSimpleImmutableEntry() {
+ Map map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2))
+ .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+
+ return map;
+ }
+
+ public Map createImmutableMapWithStreams() {
+ Map map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, })
+ .collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections:: unmodifiableMap));
+ return map;
+
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Car.java b/core-java-collections/src/main/java/com/baeldung/java_8_features/Car.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/Car.java
rename to core-java-collections/src/main/java/com/baeldung/java_8_features/Car.java
diff --git a/core-java-8/src/main/java/com/baeldung/java_8_features/Person.java b/core-java-collections/src/main/java/com/baeldung/java_8_features/Person.java
similarity index 100%
rename from core-java-8/src/main/java/com/baeldung/java_8_features/Person.java
rename to core-java-collections/src/main/java/com/baeldung/java_8_features/Person.java
diff --git a/core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Pen.java b/core-java-collections/src/main/java/com/baeldung/list/listoflist/Pen.java
similarity index 100%
rename from core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Pen.java
rename to core-java-collections/src/main/java/com/baeldung/list/listoflist/Pen.java
diff --git a/core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Pencil.java b/core-java-collections/src/main/java/com/baeldung/list/listoflist/Pencil.java
similarity index 100%
rename from core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Pencil.java
rename to core-java-collections/src/main/java/com/baeldung/list/listoflist/Pencil.java
diff --git a/core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Rubber.java b/core-java-collections/src/main/java/com/baeldung/list/listoflist/Rubber.java
similarity index 100%
rename from core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Rubber.java
rename to core-java-collections/src/main/java/com/baeldung/list/listoflist/Rubber.java
diff --git a/core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Stationery.java b/core-java-collections/src/main/java/com/baeldung/list/listoflist/Stationery.java
similarity index 100%
rename from core-java-collections/src/main/java/com/baeldung/list/list/listoflist/Stationery.java
rename to core-java-collections/src/main/java/com/baeldung/list/listoflist/Stationery.java
diff --git a/core-java-collections/src/main/java/com/baeldung/list/removeall/RemoveAll.java b/core-java-collections/src/main/java/com/baeldung/list/removeall/RemoveAll.java
new file mode 100644
index 0000000000..d5f9cf4b4e
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/list/removeall/RemoveAll.java
@@ -0,0 +1,111 @@
+package com.baeldung.list.removeall;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+public class RemoveAll {
+
+ static void removeWithWhileLoopPrimitiveElement(List list, int element) {
+ while (list.contains(element)) {
+ list.remove(element);
+ }
+ }
+
+ static void removeWithWhileLoopNonPrimitiveElement(List list, Integer element) {
+ while (list.contains(element)) {
+ list.remove(element);
+ }
+ }
+
+ static void removeWithWhileLoopStoringFirstOccurrenceIndex(List list, Integer element) {
+ int index;
+ while ((index = list.indexOf(element)) >= 0) {
+ list.remove(index);
+ }
+ }
+
+ static void removeWithCallingRemoveUntilModifies(List list, Integer element) {
+ while (list.remove(element))
+ ;
+ }
+
+ static void removeWithStandardForLoopUsingIndex(List list, int element) {
+ for (int i = 0; i < list.size(); i++) {
+ if (Objects.equals(element, list.get(i))) {
+ list.remove(i);
+ }
+ }
+ }
+
+ static void removeWithForLoopDecrementOnRemove(List list, int element) {
+ for (int i = 0; i < list.size(); i++) {
+ if (Objects.equals(element, list.get(i))) {
+ list.remove(i);
+ i--;
+ }
+ }
+ }
+
+ static void removeWithForLoopIncrementIfRemains(List list, int element) {
+ for (int i = 0; i < list.size();) {
+ if (Objects.equals(element, list.get(i))) {
+ list.remove(i);
+ } else {
+ i++;
+ }
+ }
+ }
+
+ static void removeWithForEachLoop(List list, int element) {
+ for (Integer number : list) {
+ if (Objects.equals(number, element)) {
+ list.remove(number);
+ }
+ }
+ }
+
+ static void removeWithIterator(List list, int element) {
+ for (Iterator i = list.iterator(); i.hasNext();) {
+ Integer number = i.next();
+ if (Objects.equals(number, element)) {
+ i.remove();
+ }
+ }
+ }
+
+ static List removeWithCollectingAndReturningRemainingElements(List list, int element) {
+ List remainingElements = new ArrayList<>();
+ for (Integer number : list) {
+ if (!Objects.equals(number, element)) {
+ remainingElements.add(number);
+ }
+ }
+ return remainingElements;
+ }
+
+ static void removeWithCollectingRemainingElementsAndAddingToOriginalList(List list, int element) {
+ List remainingElements = new ArrayList<>();
+ for (Integer number : list) {
+ if (!Objects.equals(number, element)) {
+ remainingElements.add(number);
+ }
+ }
+
+ list.clear();
+ list.addAll(remainingElements);
+ }
+
+ static List removeWithStreamFilter(List list, Integer element) {
+ return list.stream()
+ .filter(e -> !Objects.equals(e, element))
+ .collect(Collectors.toList());
+ }
+
+ static void removeWithRemoveIf(List list, Integer element) {
+ list.removeIf(n -> Objects.equals(n, element));
+ }
+
+}
diff --git a/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java b/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java
new file mode 100644
index 0000000000..2405c26aac
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java
@@ -0,0 +1,19 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Collection;
+import java.util.stream.Stream;
+import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
+
+public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull {
+
+ /**
+ * This method shows how to make a null safe stream from a collection through the use of
+ * emptyIfNull() method from Apache Commons CollectionUtils library
+ *
+ * @param collection The collection that is to be converted into a stream
+ * @return The stream that has been created from the collection or an empty stream if the collection is null
+ */
+ public Stream collectionAsStream(Collection collection) {
+ return emptyIfNull(collection).stream();
+ }
+}
diff --git a/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java b/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java
new file mode 100644
index 0000000000..da767d4563
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java
@@ -0,0 +1,21 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Collection;
+import java.util.Optional;
+import java.util.stream.Stream;
+
+public class NullSafeCollectionStreamsUsingJava8OptionalContainer {
+
+ /**
+ * This method shows how to make a null safe stream from a collection through the use of
+ * Java SE 8’s Optional Container
+ *
+ * @param collection The collection that is to be converted into a stream
+ * @return The stream that has been created from the collection or an empty stream if the collection is null
+ */
+ public Stream collectionAsStream(Collection collection) {
+ return Optional.ofNullable(collection)
+ .map(Collection::stream)
+ .orElseGet(Stream::empty);
+ }
+}
\ No newline at end of file
diff --git a/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java b/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java
new file mode 100644
index 0000000000..0c10f1cebc
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java
@@ -0,0 +1,19 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Collection;
+import java.util.stream.Stream;
+
+public class NullSafeCollectionStreamsUsingNullDereferenceCheck {
+
+ /**
+ * This method shows how to make a null safe stream from a collection through the use of a check
+ * to prevent null dereferences
+ *
+ * @param collection The collection that is to be converted into a stream
+ * @return The stream that has been created from the collection or an empty stream if the collection is null
+ */
+ public Stream collectionAsStream(Collection collection) {
+ return collection == null ? Stream.empty() : collection.stream();
+ }
+
+}
diff --git a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java
new file mode 100644
index 0000000000..921e1608ea
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java
@@ -0,0 +1,59 @@
+package com.baeldung.performance;
+
+import org.openjdk.jmh.annotations.*;
+import org.openjdk.jmh.runner.Runner;
+import org.openjdk.jmh.runner.options.Options;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@Warmup(iterations = 5)
+public class CollectionsBenchmark {
+
+ @State(Scope.Thread)
+ public static class MyState {
+ private Set employeeSet = new HashSet<>();
+ private List employeeList = new ArrayList<>();
+
+ private long iterations = 10000;
+
+ private Employee employee = new Employee(100L, "Harry");
+
+ @Setup(Level.Trial)
+ public void setUp() {
+
+ for (long i = 0; i < iterations; i++) {
+ employeeSet.add(new Employee(i, "John"));
+ employeeList.add(new Employee(i, "John"));
+ }
+
+ employeeList.add(employee);
+ employeeSet.add(employee);
+ }
+ }
+
+ @Benchmark
+ public boolean testArrayList(MyState state) {
+ return state.employeeList.contains(state.employee);
+ }
+
+ @Benchmark
+ public boolean testHashSet(MyState state) {
+ return state.employeeSet.contains(state.employee);
+ }
+
+ public static void main(String[] args) throws Exception {
+ Options options = new OptionsBuilder()
+ .include(CollectionsBenchmark.class.getSimpleName()).threads(1)
+ .forks(1).shouldFailOnError(true)
+ .shouldDoGC(true)
+ .jvmArgs("-server").build();
+ new Runner(options).run();
+ }
+}
diff --git a/core-java-collections/src/main/java/com/baeldung/performance/Employee.java b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java
new file mode 100644
index 0000000000..daa68ae2f1
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java
@@ -0,0 +1,31 @@
+package com.baeldung.performance;
+
+public class Employee {
+
+ private Long id;
+ private String name;
+
+ public Employee(Long id, String name) {
+ this.name = name;
+ this.id = id;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ Employee employee = (Employee) o;
+
+ if (!id.equals(employee.id)) return false;
+ return name.equals(employee.name);
+
+ }
+
+ @Override
+ public int hashCode() {
+ int result = id.hashCode();
+ result = 31 * result + name.hashCode();
+ return result;
+ }
+}
diff --git a/core-java-collections/src/main/java/com/baeldung/thread_safe_lifo/DequeBasedSynchronizedStack.java b/core-java-collections/src/main/java/com/baeldung/thread_safe_lifo/DequeBasedSynchronizedStack.java
new file mode 100644
index 0000000000..ea1618b0f2
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/thread_safe_lifo/DequeBasedSynchronizedStack.java
@@ -0,0 +1,36 @@
+package com.baeldung.thread_safe_lifo;
+
+import java.util.ArrayDeque;
+
+/**
+ * Deque Based Stack implementation.
+ */
+public class DequeBasedSynchronizedStack {
+
+ // Internal Deque which gets decorated for synchronization.
+ private ArrayDeque dequeStore = new ArrayDeque<>();
+
+ public DequeBasedSynchronizedStack(int initialCapacity) {
+ this.dequeStore = new ArrayDeque<>(initialCapacity);
+ }
+
+ public DequeBasedSynchronizedStack() {
+
+ }
+
+ public synchronized T pop() {
+ return this.dequeStore.pop();
+ }
+
+ public synchronized void push(T element) {
+ this.dequeStore.push(element);
+ }
+
+ public synchronized T peek() {
+ return this.dequeStore.peek();
+ }
+
+ public synchronized int size() {
+ return this.dequeStore.size();
+ }
+}
diff --git a/core-java-collections/src/main/resources/logback.xml b/core-java-collections/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/core-java-collections/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-collections/src/test/java/com/baeldung/collection/CollectionsEmpty.java b/core-java-collections/src/test/java/com/baeldung/collection/CollectionsEmpty.java
new file mode 100644
index 0000000000..86a262107d
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/collection/CollectionsEmpty.java
@@ -0,0 +1,26 @@
+package com.baeldung.collection;
+
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Collections;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class CollectionsEmpty {
+
+ @Test
+ public void givenArrayList_whenAddingElement_addsNewElement() {
+ ArrayList mutableList = new ArrayList<>();
+ mutableList.add("test");
+
+ Assert.assertEquals(mutableList.size(), 1);
+ Assert.assertEquals(mutableList.get(0), "test");
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() {
+ List immutableList = Collections.emptyList();
+ immutableList.add("test");
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java b/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java
new file mode 100644
index 0000000000..9f002c89a2
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java
@@ -0,0 +1,80 @@
+package com.baeldung.collection;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class StreamOperateAndRemoveUnitTest {
+
+ private List- itemList;
+
+ @Before
+ public void setup() {
+
+ itemList = new ArrayList<>();
+ for (int i = 0; i < 10; i++) {
+ itemList.add(new Item(i));
+ }
+ }
+
+ @Test
+ public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() {
+
+ final List
- filteredList = itemList.stream().filter(item -> item.isQualified())
+ .collect(Collectors.toList());
+
+ Assert.assertEquals(5, filteredList.size());
+ }
+
+ @Test
+ public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() {
+
+ final Predicate
- isQualified = item -> item.isQualified();
+ itemList.stream().filter(isQualified).forEach(item -> item.operate());
+ itemList.removeIf(isQualified);
+
+ Assert.assertEquals(5, itemList.size());
+ }
+
+ @Test
+ public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() {
+
+ final List
- operatedList = new ArrayList<>();
+ itemList.stream().filter(item -> item.isQualified()).forEach(item -> {
+ item.operate();
+ operatedList.add(item);
+ });
+ itemList.removeAll(operatedList);
+
+ Assert.assertEquals(5, itemList.size());
+ }
+
+ class Item {
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
+
+ private final int value;
+
+ public Item(final int value) {
+
+ this.value = value;
+ }
+
+ public boolean isQualified() {
+
+ return value % 2 == 0;
+ }
+
+ public void operate() {
+
+ logger.info("Even Number: " + this.value);
+ }
+ }
+}
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java b/core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/findanelement/FindACustomerInGivenListUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java b/core-java-collections/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/hashtable/HashtableUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/iterators/IteratorsUnitTest.java
diff --git a/core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java
similarity index 95%
rename from core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java
index 348747111f..bc1611038c 100644
--- a/core-java-8/src/test/java/com/baeldung/list/CopyListServiceUnitTest.java
+++ b/core-java-collections/src/test/java/com/baeldung/java/list/CopyListServiceUnitTest.java
@@ -1,13 +1,17 @@
-package com.baeldung.list;
+package com.baeldung.java.list;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.*;
+import org.junit.Before;
+import org.junit.Test;
public class CopyListServiceUnitTest {
diff --git a/core-java-collections/src/test/java/com/baeldung/java/map/initialize/MapInitializerUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java/map/initialize/MapInitializerUnitTest.java
new file mode 100644
index 0000000000..80a8983d6f
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/java/map/initialize/MapInitializerUnitTest.java
@@ -0,0 +1,27 @@
+package com.baeldung.java.map.initialize;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.Map;
+
+import org.junit.Test;
+
+public class MapInitializerUnitTest {
+
+ @Test
+ public void givenStaticMap_whenUpdated_thenCorrect() {
+
+ MapInitializer.articleMapOne.put("NewArticle1", "Convert array to List");
+
+ assertEquals(MapInitializer.articleMapOne.get("NewArticle1"), "Convert array to List");
+
+ }
+
+ @Test(expected=UnsupportedOperationException.class)
+ public void givenSingleTonMap_whenEntriesAdded_throwsException() {
+
+ Map map = MapInitializer.createSingletonMap();
+ map.put("username2", "password2");
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java b/core-java-collections/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java
diff --git a/core-java-collections/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java
new file mode 100644
index 0000000000..299a87026f
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/list/listoflist/AddElementsToListUnitTest.java
@@ -0,0 +1,69 @@
+package com.baeldung.list.listoflist;
+
+import com.baeldung.java.list.Flower;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import java.util.*;
+import static org.junit.Assert.*;
+
+public class AddElementsToListUnitTest {
+
+ List flowers;
+
+ @Before
+ public void init() {
+ this.flowers = new ArrayList<>(Arrays.asList(
+ new Flower("Poppy", 12),
+ new Flower("Anemone", 8),
+ new Flower("Catmint", 12)));
+ }
+ @Test
+ public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithNewItems() {
+ List anotherList = new ArrayList<>();
+ anotherList.addAll(flowers);
+ assertEquals(anotherList.size(), flowers.size());
+ Assert.assertTrue(anotherList.containsAll(flowers));
+ }
+ @Test
+ public void givenAList_whenTargetListIsEmpty_thenReturnTargetListWithOneModifiedElementByConstructor() {
+ List anotherList = new ArrayList<>();
+ anotherList.addAll(flowers);
+ Flower flower = anotherList.get(0);
+ flower.setPetals(flowers.get(0).getPetals() * 3);
+ assertEquals(anotherList.size(), flowers.size());
+ Assert.assertTrue(anotherList.containsAll(flowers));
+ }
+ @Test
+ public void givenAListAndElements_whenUseCollectionsAddAll_thenAddElementsToTargetList() {
+ List target = new ArrayList<>();
+ Collections.addAll(target, flowers.get(0), flowers.get(1), flowers.get(2), flowers.get(0));
+ assertEquals(target.size(), 4);
+ }
+ @Test
+ public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListSkipFirstElementByStreamProcess() {
+ List flowerVase = new ArrayList<>();
+ flowers.stream()
+ .skip(1)
+ .forEachOrdered(flowerVase::add);
+ assertEquals(flowerVase.size() + 1, flowers.size());
+ assertFalse(flowerVase.containsAll(flowers));
+ }
+ @Test
+ public void givenTwoList_whenSourceListDoesNotHaveNullElements_thenAddElementsToTargetListFilteringElementsByStreamProcess() {
+ List flowerVase = new ArrayList<>();
+ flowers.stream()
+ .filter(f -> f.getPetals() > 10)
+ .forEachOrdered(flowerVase::add);
+ assertEquals(flowerVase.size() + 1, flowers.size());
+ assertFalse(flowerVase.containsAll(flowers));
+ }
+ @Test
+ public void givenAList_whenListIsNotNull_thenAddElementsToListByStreamProcessWihtOptional() {
+ List target = new ArrayList<>();
+ Optional.ofNullable(flowers)
+ .ifPresent(target::addAll);
+ assertNotNull(target);
+ assertEquals(target.size(), 3);
+ }
+}
diff --git a/core-java-collections/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java
new file mode 100644
index 0000000000..c23121053b
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/list/removeall/RemoveAllUnitTest.java
@@ -0,0 +1,210 @@
+package com.baeldung.list.removeall;
+
+import static com.baeldung.list.removeall.RemoveAll.removeWithCallingRemoveUntilModifies;
+import static com.baeldung.list.removeall.RemoveAll.removeWithCollectingAndReturningRemainingElements;
+import static com.baeldung.list.removeall.RemoveAll.removeWithCollectingRemainingElementsAndAddingToOriginalList;
+import static com.baeldung.list.removeall.RemoveAll.removeWithForEachLoop;
+import static com.baeldung.list.removeall.RemoveAll.removeWithForLoopDecrementOnRemove;
+import static com.baeldung.list.removeall.RemoveAll.removeWithForLoopIncrementIfRemains;
+import static com.baeldung.list.removeall.RemoveAll.removeWithIterator;
+import static com.baeldung.list.removeall.RemoveAll.removeWithRemoveIf;
+import static com.baeldung.list.removeall.RemoveAll.removeWithStandardForLoopUsingIndex;
+import static com.baeldung.list.removeall.RemoveAll.removeWithStreamFilter;
+import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopNonPrimitiveElement;
+import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopPrimitiveElement;
+import static com.baeldung.list.removeall.RemoveAll.removeWithWhileLoopStoringFirstOccurrenceIndex;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.ConcurrentModificationException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class RemoveAllUnitTest {
+
+ private List list(Integer... elements) {
+ return new ArrayList<>(Arrays.asList(elements));
+ }
+
+ @Test
+ public void givenAList_whenRemovingElementsWithWhileLoopUsingPrimitiveElement_thenTheResultCorrect() {
+ // given
+ List list = list(1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ assertThatThrownBy(() -> removeWithWhileLoopPrimitiveElement(list, valueToRemove))
+ .isInstanceOf(IndexOutOfBoundsException.class);
+ }
+
+ @Test
+ public void givenAList_whenRemovingElementsWithWhileLoopUsingNonPrimitiveElement_thenTheResultCorrect() {
+ // given
+ List list = list(1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ removeWithWhileLoopNonPrimitiveElement(list, valueToRemove);
+
+ // then
+ assertThat(list).isEqualTo(list(2, 3));
+ }
+
+ @Test
+ public void givenAList_whenRemovingElementsWithWhileLoopStoringFirstOccurrenceIndex_thenTheResultCorrect() {
+ // given
+ List list = list(1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ removeWithWhileLoopStoringFirstOccurrenceIndex(list, valueToRemove);
+
+ // then
+ assertThat(list).isEqualTo(list(2, 3));
+ }
+
+ @Test
+ public void givenAList_whenRemovingElementsWithCallingRemoveUntilModifies_thenTheResultIsCorrect() {
+ // given
+ List list = list(1, 1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ removeWithCallingRemoveUntilModifies(list, valueToRemove);
+
+ // then
+ assertThat(list).isEqualTo(list(2, 3));
+ }
+
+ @Test
+ public void givenAListWithoutDuplication_whenRemovingElementsWithStandardForLoopUsingIndex_thenTheResultIsCorrect() {
+ // given
+ List list = list(1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ removeWithStandardForLoopUsingIndex(list, valueToRemove);
+
+ // then
+ assertThat(list).isEqualTo(list(2, 3));
+ }
+
+ @Test
+ public void givenAListWithAdjacentElements_whenRemovingElementsWithStandardForLoop_thenTheResultIsInCorrect() {
+ // given
+ List list = list(1, 1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ removeWithStandardForLoopUsingIndex(list, valueToRemove);
+
+ // then
+ assertThat(list).isEqualTo(list(1, 2, 3));
+ }
+
+ @Test
+ public void givenAListWithAdjacentElements_whenRemovingElementsWithForLoopAndDecrementOnRemove_thenTheResultIsCorrect() {
+ // given
+ List list = list(1, 1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ removeWithForLoopDecrementOnRemove(list, valueToRemove);
+
+ // then
+ assertThat(list).isEqualTo(list(2, 3));
+ }
+
+ @Test
+ public void givenAListWithAdjacentElements_whenRemovingElementsWithForLoopAndIncrementIfRemains_thenTheResultIsCorrect() {
+ // given
+ List list = list(1, 1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ removeWithForLoopIncrementIfRemains(list, valueToRemove);
+
+ // then
+ assertThat(list).isEqualTo(list(2, 3));
+ }
+
+ @Test
+ public void givenAList_whenRemovingElementsWithForEachLoop_thenExceptionIsThrown() {
+ // given
+ List list = list(1, 1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ assertThatThrownBy(() -> removeWithForEachLoop(list, valueToRemove))
+ .isInstanceOf(ConcurrentModificationException.class);
+ }
+
+ @Test
+ public void givenAList_whenRemovingElementsWithIterator_thenTheResultIsCorrect() {
+ // given
+ List list = list(1, 1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ removeWithIterator(list, valueToRemove);
+
+ // then
+ assertThat(list).isEqualTo(list(2, 3));
+ }
+
+ @Test
+ public void givenAList_whenRemovingElementsWithCollectingAndReturningRemainingElements_thenTheResultIsCorrect() {
+ // given
+ List list = list(1, 1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ List result = removeWithCollectingAndReturningRemainingElements(list, valueToRemove);
+
+ // then
+ assertThat(result).isEqualTo(list(2, 3));
+ }
+
+ @Test
+ public void givenAList_whenRemovingElementsWithCollectingRemainingAndAddingToOriginalList_thenTheResultIsCorrect() {
+ // given
+ List list = list(1, 1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ removeWithCollectingRemainingElementsAndAddingToOriginalList(list, valueToRemove);
+
+ // then
+ assertThat(list).isEqualTo(list(2, 3));
+ }
+
+ @Test
+ public void givenAList_whenRemovingElementsWithStreamFilter_thenTheResultIsCorrect() {
+ // given
+ List list = list(1, 1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ List result = removeWithStreamFilter(list, valueToRemove);
+
+ // then
+ assertThat(result).isEqualTo(list(2, 3));
+ }
+
+ @Test
+ public void givenAList_whenRemovingElementsWithCallingRemoveIf_thenTheResultIsCorrect() {
+ // given
+ List list = list(1, 1, 2, 3);
+ int valueToRemove = 1;
+
+ // when
+ removeWithRemoveIf(list, valueToRemove);
+
+ // then
+ assertThat(list).isEqualTo(list(2, 3));
+ }
+
+}
diff --git a/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java b/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java
index 09f0bb248c..f2b1bd9d88 100644
--- a/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java
+++ b/core-java-collections/src/test/java/com/baeldung/list/removefirst/RemoveFirstElementUnitTest.java
@@ -4,6 +4,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
@@ -48,4 +49,14 @@ public class RemoveFirstElementUnitTest {
assertThat(linkedList, not(contains("cat")));
}
+ @Test
+ public void givenStringArray_whenRemovingFirstElement_thenArrayIsSmallerAndElementRemoved() {
+ String[] stringArray = {"foo", "bar", "baz"};
+
+ String[] modifiedArray = Arrays.copyOfRange(stringArray, 1, stringArray.length);
+
+ assertThat(modifiedArray.length, is(2));
+ assertThat(modifiedArray[0], is("bar"));
+ }
+
}
diff --git a/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java b/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java
new file mode 100644
index 0000000000..875045946d
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest.java
@@ -0,0 +1,37 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.stream.Stream;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class NullSafeCollectionStreamsUsingCommonsEmptyIfNullUnitTest {
+
+ private final NullSafeCollectionStreamsUsingCommonsEmptyIfNull instance =
+ new NullSafeCollectionStreamsUsingCommonsEmptyIfNull();
+ @Test
+ public void whenCollectionIsNull_thenExpectAnEmptyStream() {
+ Collection collection = null;
+ Stream expResult = Stream.empty();
+ Stream result = instance.collectionAsStream(collection);
+ assertStreamEquals(expResult, result);
+ }
+
+ @Test
+ public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
+ Collection collection = Arrays.asList("a", "b", "c");
+ Stream expResult = Arrays.stream(new String[] { "a", "b", "c" });
+ Stream result = instance.collectionAsStream(collection);
+ assertStreamEquals(expResult, result);
+ }
+
+ private static void assertStreamEquals(Stream> s1, Stream> s2) {
+ Iterator> iter1 = s1.iterator(), iter2 = s2.iterator();
+ while (iter1.hasNext() && iter2.hasNext())
+ assertEquals(iter1.next(), iter2.next());
+ assert !iter1.hasNext() && !iter2.hasNext();
+ }
+
+}
diff --git a/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java b/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java
new file mode 100644
index 0000000000..402f1a6a19
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest.java
@@ -0,0 +1,37 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.stream.Stream;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class NullSafeCollectionStreamsUsingJava8OptionalContainerUnitTest {
+
+ private final NullSafeCollectionStreamsUsingJava8OptionalContainer instance =
+ new NullSafeCollectionStreamsUsingJava8OptionalContainer();
+ @Test
+ public void whenCollectionIsNull_thenExpectAnEmptyStream() {
+ Collection collection = null;
+ Stream expResult = Stream.empty();
+ Stream result = instance.collectionAsStream(collection);
+ assertStreamEquals(expResult, result);
+ }
+
+ @Test
+ public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
+ Collection collection = Arrays.asList("a", "b", "c");
+ Stream expResult = Arrays.stream(new String[] { "a", "b", "c" });
+ Stream result = instance.collectionAsStream(collection);
+ assertStreamEquals(expResult, result);
+ }
+
+ private static void assertStreamEquals(Stream> s1, Stream> s2) {
+ Iterator> iter1 = s1.iterator(), iter2 = s2.iterator();
+ while (iter1.hasNext() && iter2.hasNext())
+ assertEquals(iter1.next(), iter2.next());
+ assert !iter1.hasNext() && !iter2.hasNext();
+ }
+
+}
diff --git a/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java b/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java
new file mode 100644
index 0000000000..bb6152371d
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest.java
@@ -0,0 +1,38 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.stream.Stream;
+import org.junit.Test;
+import static org.junit.Assert.*;
+
+public class NullSafeCollectionStreamsUsingNullDereferenceCheckUnitTest {
+
+ private final NullSafeCollectionStreamsUsingNullDereferenceCheck instance =
+ new NullSafeCollectionStreamsUsingNullDereferenceCheck();
+
+ @Test
+ public void whenCollectionIsNull_thenExpectAnEmptyStream() {
+ Collection collection = null;
+ Stream expResult = Stream.empty();
+ Stream result = instance.collectionAsStream(collection);
+ assertStreamEquals(expResult, result);
+ }
+
+ @Test
+ public void whenCollectionHasElements_thenExpectAStreamOfExactlyTheSameElements() {
+ Collection collection = Arrays.asList("a", "b", "c");
+ Stream expResult = Arrays.stream(new String[] { "a", "b", "c" });
+ Stream result = instance.collectionAsStream(collection);
+ assertStreamEquals(expResult, result);
+ }
+
+ private static void assertStreamEquals(Stream> s1, Stream> s2) {
+ Iterator> iter1 = s1.iterator(), iter2 = s2.iterator();
+ while (iter1.hasNext() && iter2.hasNext())
+ assertEquals(iter1.next(), iter2.next());
+ assert !iter1.hasNext() && !iter2.hasNext();
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java b/core-java-collections/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java
similarity index 100%
rename from core-java-8/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java
rename to core-java-collections/src/test/java/com/baeldung/shufflingcollections/ShufflingCollectionsUnitTest.java
diff --git a/core-java-collections/src/test/java/com/baeldung/stack_tests/MultithreadingCorrectnessStackUnitTest.java b/core-java-collections/src/test/java/com/baeldung/stack_tests/MultithreadingCorrectnessStackUnitTest.java
new file mode 100644
index 0000000000..4550994aa3
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/stack_tests/MultithreadingCorrectnessStackUnitTest.java
@@ -0,0 +1,101 @@
+package com.baeldung.stack_tests;
+
+import com.baeldung.thread_safe_lifo.DequeBasedSynchronizedStack;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.ArrayDeque;
+import java.util.concurrent.ConcurrentLinkedDeque;
+
+import static java.util.stream.IntStream.range;
+
+/**
+ * Correctness tests for Stack in multi threaded environment.
+ */
+public class MultithreadingCorrectnessStackUnitTest {
+
+ @Test
+ public void givenSynchronizedDeque_whenExecutedParallel_thenWorkRight() {
+
+ DequeBasedSynchronizedStack deque = new DequeBasedSynchronizedStack<>();
+
+ // Serial execution of push on ConcurrentLinkedQueue will always result in correct execution.
+ range(1, 10000).forEach(value -> deque.push(value));
+
+ int sum = 0;
+ while(deque.peek() != null) {
+ sum += deque.pop();
+ }
+
+ Assert.assertEquals(49995000, sum);
+
+ // Parallel execution of push on ConcurrentLinkedQueue will always result in correct execution.
+ range(1, 10000).parallel().forEach(value -> deque.push(value));
+
+ sum = 0;
+ while(deque.peek() != null) {
+ sum += deque.pop();
+ }
+
+ Assert.assertEquals(49995000, sum);
+ }
+
+ @Test
+ public void givenConcurrentLinkedQueue_whenExecutedParallel_thenWorkRight() {
+
+ ConcurrentLinkedDeque deque = new ConcurrentLinkedDeque<>();
+
+ // Serial execution of push on ConcurrentLinkedQueue will always result in correct execution.
+ range(1, 10000).forEach(value -> deque.push(value));
+
+ int sum = 0;
+ while(deque.peek() != null) {
+ sum += deque.pop();
+ }
+
+ Assert.assertEquals(49995000, sum);
+
+ // Parallel execution of push on ConcurrentLinkedQueue will always result in correct execution.
+ range(1, 10000).parallel().forEach(value -> deque.push(value));
+
+ sum = 0;
+ while(deque.peek() != null) {
+ sum += deque.pop();
+ }
+
+ Assert.assertEquals(49995000, sum);
+ }
+
+ @Test
+ public void givenArrayDeque_whenExecutedParallel_thenShouldFail() {
+
+ ArrayDeque deque = new ArrayDeque<>();
+
+ // Serial execution of push on ArrayDeque will always result in correct execution.
+ range(1, 10000).forEach(value -> deque.push(value));
+
+ int sum = 0;
+ while(deque.peek() != null) {
+ sum += deque.pop();
+ }
+
+ Assert.assertEquals(49995000, sum);
+
+ // Parallel execution of push on ArrayDeque will not result in correct execution.
+ range(1, 10000).parallel().forEach(value -> deque.push(value));
+
+ sum = 0;
+ while(deque.peek() != null) {
+ sum += deque.pop();
+ }
+
+ // This shouldn't happen.
+ if(sum == 49995000) {
+ System.out.println("Something wrong in the environment, Please try some big value and check");
+ // To safe-guard build without test failures.
+ return;
+ }
+
+ Assert.assertNotEquals(49995000, sum);
+ }
+}
diff --git a/core-java-collections/src/test/java/com/baeldung/stack_tests/StackUnitTest.java b/core-java-collections/src/test/java/com/baeldung/stack_tests/StackUnitTest.java
new file mode 100644
index 0000000000..07c4760186
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/stack_tests/StackUnitTest.java
@@ -0,0 +1,63 @@
+package com.baeldung.stack_tests;
+
+import com.baeldung.thread_safe_lifo.DequeBasedSynchronizedStack;
+import com.google.common.collect.Streams;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.util.ArrayDeque;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Stack;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.stream.Stream;
+
+import static java.util.stream.IntStream.range;
+
+/**
+ * These tests are to understand the Stack implementation in Java Collections.
+ */
+public class StackUnitTest {
+
+ @Test
+ public void givenStack_whenPushPopPeek_thenWorkRight() {
+ Stack namesStack = new Stack<>();
+
+ namesStack.push("Bill Gates");
+ namesStack.push("Elon Musk");
+
+ Assert.assertEquals("Elon Musk", namesStack.peek());
+ Assert.assertEquals("Elon Musk", namesStack.pop());
+ Assert.assertEquals("Bill Gates", namesStack.pop());
+
+ Assert.assertEquals(0, namesStack.size());
+ }
+
+ @Test
+ public void givenSynchronizedDeque_whenPushPopPeek_thenWorkRight() {
+ DequeBasedSynchronizedStack namesStack = new DequeBasedSynchronizedStack<>();
+
+ namesStack.push("Bill Gates");
+ namesStack.push("Elon Musk");
+
+ Assert.assertEquals("Elon Musk", namesStack.peek());
+ Assert.assertEquals("Elon Musk", namesStack.pop());
+ Assert.assertEquals("Bill Gates", namesStack.pop());
+
+ Assert.assertEquals(0, namesStack.size());
+ }
+
+ @Test
+ public void givenConcurrentLinkedDeque_whenPushPopPeek_thenWorkRight() {
+ ConcurrentLinkedDeque namesStack = new ConcurrentLinkedDeque<>();
+
+ namesStack.push("Bill Gates");
+ namesStack.push("Elon Musk");
+
+ Assert.assertEquals("Elon Musk", namesStack.peek());
+ Assert.assertEquals("Elon Musk", namesStack.pop());
+ Assert.assertEquals("Bill Gates", namesStack.pop());
+
+ Assert.assertEquals(0, namesStack.size());
+ }
+}
diff --git a/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java b/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java
new file mode 100644
index 0000000000..09ecebe47b
--- /dev/null
+++ b/core-java-collections/src/test/java/org/baeldung/java/collections/CollectionsEmpty.java
@@ -0,0 +1,26 @@
+package org.baeldung.java.collections;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import org.junit.Assert;
+import org.junit.Test;
+
+class CollectionsEmpty {
+
+ @Test
+ public void givenArrayList_whenAddingElement_addsNewElement() {
+ ArrayList mutableList = new ArrayList<>();
+ mutableList.add("test");
+
+ Assert.assertEquals(mutableList.size(), 1);
+ Assert.assertEquals(mutableList.get(0), "test");
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() {
+ List immutableList = Collections.emptyList();
+ immutableList.add("test");
+ }
+
+}
diff --git a/core-java-concurrency-collections/.gitignore b/core-java-concurrency-collections/.gitignore
new file mode 100644
index 0000000000..3de4cc647e
--- /dev/null
+++ b/core-java-concurrency-collections/.gitignore
@@ -0,0 +1,26 @@
+*.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
+*.txt
+backup-pom.xml
+/bin/
+/temp
+
+#IntelliJ specific
+.idea/
+*.iml
\ No newline at end of file
diff --git a/core-java-concurrency-collections/README.md b/core-java-concurrency-collections/README.md
new file mode 100644
index 0000000000..b982a91861
--- /dev/null
+++ b/core-java-concurrency-collections/README.md
@@ -0,0 +1,15 @@
+=========
+
+## Core Java Concurrency Collections Examples
+
+### Relevant Articles:
+- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
+- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map)
+- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue)
+- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception)
+- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
+- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
+- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
+- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
+- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
+- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
diff --git a/core-java-concurrency-collections/pom.xml b/core-java-concurrency-collections/pom.xml
new file mode 100644
index 0000000000..5e0a80d33c
--- /dev/null
+++ b/core-java-concurrency-collections/pom.xml
@@ -0,0 +1,94 @@
+
+ 4.0.0
+ com.baeldung
+ core-java-concurrency-collections
+ 0.1.0-SNAPSHOT
+ jar
+ core-java-concurrency-collections
+
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-java
+
+
+
+
+ org.apache.commons
+ commons-collections4
+ ${commons-collections4.version}
+
+
+ commons-io
+ commons-io
+ ${commons-io.version}
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+ org.apache.commons
+ commons-math3
+ ${commons-math3.version}
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+ com.jayway.awaitility
+ awaitility
+ ${avaitility.version}
+ test
+
+
+
+
+ core-java-concurrency-collections
+
+
+ src/main/resources
+ true
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+
+
+ copy-dependencies
+ prepare-package
+
+ copy-dependencies
+
+
+ ${project.build.directory}/libs
+
+
+
+
+
+
+
+
+
+
+ 21.0
+ 3.5
+ 3.6.1
+ 4.1
+ 4.01
+
+ 3.6.1
+ 1.7.0
+
+
+
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java
similarity index 79%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java
index 052136bfe4..842d4e630e 100644
--- a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java
+++ b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/BlockingQueueUsage.java
@@ -10,15 +10,18 @@ public class BlockingQueueUsage {
int N_CONSUMERS = Runtime.getRuntime().availableProcessors();
int poisonPill = Integer.MAX_VALUE;
int poisonPillPerProducer = N_CONSUMERS / N_PRODUCERS;
-
+ int mod = N_CONSUMERS % N_PRODUCERS;
BlockingQueue queue = new LinkedBlockingQueue<>(BOUND);
- for (int i = 0; i < N_PRODUCERS; i++) {
+ for (int i = 1; i < N_PRODUCERS; i++) {
new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer)).start();
}
for (int j = 0; j < N_CONSUMERS; j++) {
new Thread(new NumbersConsumer(queue, poisonPill)).start();
}
+
+ new Thread(new NumbersProducer(queue, poisonPill, poisonPillPerProducer+mod)).start();
+
}
}
\ No newline at end of file
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersConsumer.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/blockingqueue/NumbersProducer.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayObject.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueConsumer.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/delayqueue/DelayQueueProducer.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/Event.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/Event.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/Event.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/Event.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java b/core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/concurrent/skiplist/EventWindowSort.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Consumer.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/transferqueue/Consumer.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Consumer.java
diff --git a/core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java b/core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Producer.java
similarity index 100%
rename from core-java-concurrency/src/main/java/com/baeldung/transferqueue/Producer.java
rename to core-java-concurrency-collections/src/main/java/com/baeldung/transferqueue/Producer.java
diff --git a/spring-data-elasticsearch/src/main/resources/logback.xml b/core-java-concurrency-collections/src/main/resources/logback.xml
similarity index 100%
rename from spring-data-elasticsearch/src/main/resources/logback.xml
rename to core-java-concurrency-collections/src/main/resources/logback.xml
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/copyonwrite/CopyOnWriteArrayListUnitTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/delayqueue/DelayQueueIntegrationTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/priorityblockingqueue/PriorityBlockingQueueIntegrationTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/concurrent/skiplist/ConcurrentSkipListSetIntegrationTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapAggregateStatusManualTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapNullKeyValueManualTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentMapPerformanceManualTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurrentNavigableMapManualTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmap/ConcurretMapMemoryConsistencyManualTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/java/concurrentmodification/ConcurrentModificationUnitTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/synchronousqueue/SynchronousQueueIntegrationTest.java
diff --git a/core-java-concurrency/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java b/core-java-concurrency-collections/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java
rename to core-java-concurrency-collections/src/test/java/com/baeldung/transferqueue/TransferQueueIntegrationTest.java
diff --git a/core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java b/core-java-concurrency-collections/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java
similarity index 100%
rename from core-java-concurrency/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java
rename to core-java-concurrency-collections/src/test/java/org/baeldung/java/streams/ThreadPoolInParallelStreamIntegrationTest.java
diff --git a/out/production/main122/.gitignore b/core-java-concurrency-collections/src/test/resources/.gitignore
similarity index 100%
rename from out/production/main122/.gitignore
rename to core-java-concurrency-collections/src/test/resources/.gitignore
diff --git a/core-java-concurrency/README.md b/core-java-concurrency/README.md
index 8192a8e301..d775d24dff 100644
--- a/core-java-concurrency/README.md
+++ b/core-java-concurrency/README.md
@@ -7,22 +7,12 @@
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future)
-- [Guide to java.util.concurrent.BlockingQueue](http://www.baeldung.com/java-blocking-queue)
- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch)
-- [A Guide to ConcurrentMap](http://www.baeldung.com/java-concurrent-map)
-- [Guide to PriorityBlockingQueue in Java](http://www.baeldung.com/java-priority-blocking-queue)
-- [Avoiding the ConcurrentModificationException in Java](http://www.baeldung.com/java-concurrentmodificationexception)
-- [Custom Thread Pools In Java 8 Parallel Streams](http://www.baeldung.com/java-8-parallel-streams-custom-threadpool)
- [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks)
- [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal)
-- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
-- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
-- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
-- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
- [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers)
-- [Guide to CopyOnWriteArrayList](http://www.baeldung.com/java-copy-on-write-arraylist)
- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
- [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables)
@@ -38,3 +28,4 @@
- [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule)
- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer)
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
+- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
diff --git a/core-java-concurrency/src/main/resources/logback.xml b/core-java-concurrency/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/core-java-concurrency/src/main/resources/logback.xml
+++ b/core-java-concurrency/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/core-java-io/pom.xml b/core-java-io/pom.xml
index 35bc43921c..bc71fb8838 100644
--- a/core-java-io/pom.xml
+++ b/core-java-io/pom.xml
@@ -183,6 +183,7 @@
org.springframework.boot
spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
@@ -316,6 +317,7 @@
2.1.0.1
1.19
2.4.5
+ 2.0.4.RELEASE
\ No newline at end of file
diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java
new file mode 100644
index 0000000000..45ff486a79
--- /dev/null
+++ b/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java
@@ -0,0 +1,24 @@
+package com.baeldung.fileparser;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+
+public class BufferedReaderExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ ArrayList result = new ArrayList<>();
+
+ try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
+
+ while (br.ready()) {
+ result.add(br.readLine());
+ }
+ return result;
+ }
+
+ }
+
+}
diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java
new file mode 100644
index 0000000000..f9dd2a9ec5
--- /dev/null
+++ b/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java
@@ -0,0 +1,31 @@
+package com.baeldung.fileparser;
+
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+
+public class FileReaderExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ ArrayList result = new ArrayList<>();
+
+ try (FileReader f = new FileReader(filename)) {
+ StringBuffer sb = new StringBuffer();
+ while (f.ready()) {
+ char c = (char) f.read();
+ if (c == '\n') {
+ result.add(sb.toString());
+ sb = new StringBuffer();
+ } else {
+ sb.append(c);
+ }
+ }
+ if (sb.length() > 0) {
+ result.add(sb.toString());
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java
new file mode 100644
index 0000000000..8e74f7d386
--- /dev/null
+++ b/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java
@@ -0,0 +1,18 @@
+package com.baeldung.fileparser;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+
+public class FilesReadLinesExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ List result = Files.readAllLines(Paths.get(filename));
+
+ return (ArrayList) result;
+ }
+
+}
diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java
new file mode 100644
index 0000000000..25d17af4ea
--- /dev/null
+++ b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java
@@ -0,0 +1,24 @@
+package com.baeldung.fileparser;
+
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Scanner;
+
+public class ScannerIntExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ ArrayList result = new ArrayList<>();
+
+ try (Scanner s = new Scanner(new FileReader(filename))) {
+
+ while (s.hasNext()) {
+ result.add(s.nextInt());
+ }
+ return result;
+ }
+
+ }
+
+}
diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java
new file mode 100644
index 0000000000..ec213c9490
--- /dev/null
+++ b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java
@@ -0,0 +1,24 @@
+package com.baeldung.fileparser;
+
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Scanner;
+
+public class ScannerStringExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ ArrayList result = new ArrayList<>();
+
+ try (Scanner s = new Scanner(new FileReader(filename))) {
+
+ while (s.hasNext()) {
+ result.add(s.nextLine());
+ }
+ return result;
+ }
+
+ }
+
+}
diff --git a/core-java-io/src/main/resources/logback.xml b/core-java-io/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/core-java-io/src/main/resources/logback.xml
+++ b/core-java-io/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java
new file mode 100644
index 0000000000..f9a2ce972d
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java
@@ -0,0 +1,48 @@
+package com.baeldung.file;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.util.Arrays;
+import java.util.List;
+import java.util.function.Predicate;
+import java.util.stream.Collectors;
+
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class FilenameFilterManualTest {
+
+ private static File directory;
+
+ @BeforeClass
+ public static void setupClass() {
+ directory = new File(FilenameFilterManualTest.class.getClassLoader()
+ .getResource("fileNameFilterManualTestFolder")
+ .getFile());
+ }
+
+ @Test
+ public void whenFilteringFilesEndingWithJson_thenEqualExpectedFiles() {
+ FilenameFilter filter = (dir, name) -> name.endsWith(".json");
+
+ String[] expectedFiles = { "people.json", "students.json" };
+ String[] actualFiles = directory.list(filter);
+
+ Assert.assertArrayEquals(expectedFiles, actualFiles);
+ }
+
+ @Test
+ public void whenFilteringFilesEndingWithXml_thenEqualExpectedFiles() {
+ Predicate predicate = (name) -> name.endsWith(".xml");
+
+ String[] expectedFiles = { "teachers.xml", "workers.xml" };
+ List files = Arrays.stream(directory.list())
+ .filter(predicate)
+ .collect(Collectors.toList());
+ String[] actualFiles = files.toArray(new String[files.size()]);
+
+ Assert.assertArrayEquals(expectedFiles, actualFiles);
+ }
+
+}
diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java
new file mode 100644
index 0000000000..78f900d796
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class BufferedReaderUnitTest {
+
+ protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
+ List lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME);
+ assertTrue("File does not has 2 lines", lines.size() == 2);
+ }
+}
diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java
new file mode 100644
index 0000000000..a38e58d348
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class FileReaderUnitTest {
+
+ protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
+ List lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME);
+ assertTrue("File does not has 2 lines", lines.size() == 2);
+ }
+}
diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java
new file mode 100644
index 0000000000..c0b742fd47
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class FilesReadAllLinesUnitTest {
+
+ protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
+ List lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME);
+ assertTrue("File does not has 2 lines", lines.size() == 2);
+ }
+}
diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java
new file mode 100644
index 0000000000..0a398ba7c6
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ScannerIntUnitTest {
+
+ protected static final String NUMBER_FILENAME = "src/test/resources/sampleNumberFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetIntArrayList() throws IOException {
+ List numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME);
+ assertTrue("File does not has 2 lines", numbers.size() == 2);
+ }
+}
diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java
new file mode 100644
index 0000000000..8f9b0a56c0
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ScannerStringUnitTest {
+
+ protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
+ List lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME);
+ assertTrue("File does not has 2 lines", lines.size() == 2);
+ }
+}
diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java
index 08a4c673cd..6604d75ed1 100644
--- a/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java
+++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java
@@ -1,10 +1,12 @@
package org.baeldung.java.io;
import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.io.SequenceInputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
@@ -74,6 +76,28 @@ public class JavaXToInputStreamUnitTest {
IOUtils.closeQuietly(targetStream);
}
+ @Test
+ public final void givenUsingPlainJava_whenConvertingFileToDataInputStream_thenCorrect() throws IOException {
+ final File initialFile = new File("src/test/resources/sample.txt");
+ final InputStream targetStream = new DataInputStream(new FileInputStream(initialFile));
+
+ IOUtils.closeQuietly(targetStream);
+ }
+
+ @Test
+ public final void givenUsingPlainJava_whenConvertingFileToSequenceInputStream_thenCorrect() throws IOException {
+ final File initialFile = new File("src/test/resources/sample.txt");
+ final File anotherFile = new File("src/test/resources/anothersample.txt");
+ final InputStream targetStream = new FileInputStream(initialFile);
+ final InputStream anotherTargetStream = new FileInputStream(anotherFile);
+
+ InputStream sequenceTargetStream = new SequenceInputStream(targetStream, anotherTargetStream);
+
+ IOUtils.closeQuietly(targetStream);
+ IOUtils.closeQuietly(anotherTargetStream);
+ IOUtils.closeQuietly(sequenceTargetStream);
+ }
+
@Test
public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
final File initialFile = new File("src/test/resources/sample.txt");
diff --git a/core-java-io/src/test/resources/anothersample.txt b/core-java-io/src/test/resources/anothersample.txt
new file mode 100644
index 0000000000..f06f18ce02
--- /dev/null
+++ b/core-java-io/src/test/resources/anothersample.txt
@@ -0,0 +1 @@
+...Continues
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json
new file mode 100644
index 0000000000..9e26dfeeb6
--- /dev/null
+++ b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json
@@ -0,0 +1 @@
+{}
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json
new file mode 100644
index 0000000000..9e26dfeeb6
--- /dev/null
+++ b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json
@@ -0,0 +1 @@
+{}
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml
new file mode 100644
index 0000000000..19b16cc72c
--- /dev/null
+++ b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml
new file mode 100644
index 0000000000..19b16cc72c
--- /dev/null
+++ b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/sampleNumberFile.txt b/core-java-io/src/test/resources/sampleNumberFile.txt
new file mode 100644
index 0000000000..7787faa3c1
--- /dev/null
+++ b/core-java-io/src/test/resources/sampleNumberFile.txt
@@ -0,0 +1,2 @@
+111
+222
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/sampleTextFile.txt b/core-java-io/src/test/resources/sampleTextFile.txt
new file mode 100644
index 0000000000..75cb50aafa
--- /dev/null
+++ b/core-java-io/src/test/resources/sampleTextFile.txt
@@ -0,0 +1,2 @@
+Hello
+World
\ No newline at end of file
diff --git a/core-java-persistence/README.md b/core-java-persistence/README.md
new file mode 100644
index 0000000000..08afcadb72
--- /dev/null
+++ b/core-java-persistence/README.md
@@ -0,0 +1,8 @@
+=========
+
+## Core Java Persistence Examples
+
+### Relevant Articles:
+- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
+- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
+- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
\ No newline at end of file
diff --git a/core-java-persistence/pom.xml b/core-java-persistence/pom.xml
index 0cb142c7b8..7279fd763b 100644
--- a/core-java-persistence/pom.xml
+++ b/core-java-persistence/pom.xml
@@ -39,6 +39,16 @@
c3p0
${c3p0.version}
+
+ org.springframework
+ spring-web
+ ${springframework.spring-web.version}
+
+
+ org.springframework.boot
+ spring-boot-starter
+ ${springframework.boot.spring-boot-starter.version}
+
core-java-persistence
@@ -55,5 +65,7 @@
2.4.0
3.2.0
0.9.5.2
+ 1.5.8.RELEASE
+ 4.3.4.RELEASE
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/jdbc/BatchProcessing.java b/core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/jdbc/BatchProcessing.java
rename to core-java-persistence/src/main/java/com/baeldung/jdbc/BatchProcessing.java
diff --git a/core-java/src/main/java/com/baeldung/jdbc/Employee.java b/core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/jdbc/Employee.java
rename to core-java-persistence/src/main/java/com/baeldung/jdbc/Employee.java
diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java
rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java
diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java
rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/ExampleListener.java
diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/FilterExample.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/FilterExample.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/jdbcrowset/FilterExample.java
rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/FilterExample.java
diff --git a/core-java/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java b/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java
similarity index 100%
rename from core-java/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java
rename to core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java
diff --git a/core-java-persistence/src/main/resources/logback.xml b/core-java-persistence/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/core-java-persistence/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java b/core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java
similarity index 100%
rename from core-java/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java
rename to core-java-persistence/src/test/java/com/baeldung/jdbc/BatchProcessingLiveTest.java
diff --git a/core-java/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java b/core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java
similarity index 100%
rename from core-java/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java
rename to core-java-persistence/src/test/java/com/baeldung/jdbc/JdbcLiveTest.java
diff --git a/core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java b/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java
similarity index 100%
rename from core-java/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java
rename to core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java
diff --git a/core-java-sun/pom.xml b/core-java-sun/pom.xml
index f489f3b030..7292335232 100644
--- a/core-java-sun/pom.xml
+++ b/core-java-sun/pom.xml
@@ -303,7 +303,7 @@
1.7.0
- 2.19.1
+ 2.21.0
1.8.0
3.0.2
diff --git a/core-java-sun/src/main/resources/logback.xml b/core-java-sun/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/core-java-sun/src/main/resources/logback.xml
+++ b/core-java-sun/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/core-java/README.md b/core-java/README.md
index e22ee505ba..e74f6cf815 100644
--- a/core-java/README.md
+++ b/core-java/README.md
@@ -3,18 +3,14 @@
## Core Java Cookbooks and Examples
### Relevant Articles:
-- [Java – Generate Random String](http://www.baeldung.com/java-random-string)
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
- [How to Run a Shell Command in Java](http://www.baeldung.com/run-shell-command-in-java)
- [MD5 Hashing in Java](http://www.baeldung.com/java-md5)
- [Guide to Java Reflection](http://www.baeldung.com/java-reflection)
- [A Guide to Java Sockets](http://www.baeldung.com/a-guide-to-java-sockets)
-- [Convert char to String in Java](http://www.baeldung.com/java-convert-char-to-string)
-- [Convert String to int or Integer in Java](http://www.baeldung.com/java-convert-string-to-int-or-integer)
- [Java – Try with Resources](http://www.baeldung.com/java-try-with-resources)
- [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)
-- [How to Convert String to different data types in Java](http://www.baeldung.com/java-string-conversions)
- [Introduction to Java Generics](http://www.baeldung.com/java-generics)
- [Generate equals() and hashCode() with Eclipse](http://www.baeldung.com/java-eclipse-equals-and-hashcode)
- [A Guide To Java Regular Expressions API](http://www.baeldung.com/regular-expressions-java)
@@ -37,8 +33,6 @@
- [A Quick JUnit vs TestNG Comparison](http://www.baeldung.com/junit-vs-testng)
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
-- [Converting Strings to Enums in Java](http://www.baeldung.com/java-string-to-enum)
-- [Quick Guide to the Java StringTokenizer](http://www.baeldung.com/java-stringtokenizer)
- [JVM Log Forging](http://www.baeldung.com/jvm-log-forging)
- [Guide to sun.misc.Unsafe](http://www.baeldung.com/java-unsafe)
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
@@ -53,44 +47,33 @@
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
- [Dynamic Proxies in Java](http://www.baeldung.com/java-dynamic-proxies)
- [How to Copy an Array in Java](http://www.baeldung.com/java-array-copy)
-- [Introduction to JDBC](http://www.baeldung.com/java-jdbc)
-- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
- [Converting a Stack Trace to a String in Java](http://www.baeldung.com/java-stacktrace-to-string)
-- [Count Occurrences of a Char in a String](http://www.baeldung.com/java-count-chars)
- [Java Double Brace Initialization](http://www.baeldung.com/java-double-brace-initialization)
- [The StackOverflowError in Java](http://www.baeldung.com/java-stack-overflow-error)
-- [Split a String in Java](http://www.baeldung.com/java-split-string)
- [Introduction to Java Serialization](http://www.baeldung.com/java-serialization)
-- [How to Remove the Last Character of a String?](http://www.baeldung.com/java-remove-last-character-of-string)
- [ClassNotFoundException vs NoClassDefFoundError](http://www.baeldung.com/java-classnotfoundexception-and-noclassdeffounderror)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Guide to Escaping Characters in Java RegExps](http://www.baeldung.com/java-regexp-escape-char)
- [Guide to hashCode() in Java](http://www.baeldung.com/java-hashcode)
- [Difference between URL and URI](http://www.baeldung.com/java-url-vs-uri)
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
-- [CharSequence vs. String in Java](http://www.baeldung.com/java-char-sequence-string)
- [Period and Duration in Java](http://www.baeldung.com/java-period-duration)
- [Guide to the Diamond Operator in Java](http://www.baeldung.com/java-diamond-operator)
- [“Sneaky Throws” in Java](http://www.baeldung.com/java-sneaky-throws)
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
-- [StringBuilder and StringBuffer in Java](http://www.baeldung.com/java-string-builder-string-buffer)
- [Creating a Java Compiler Plugin](http://www.baeldung.com/java-build-compiler-plugin)
- [A Guide to the Static Keyword in Java](http://www.baeldung.com/java-static)
- [Initializing Arrays in Java](http://www.baeldung.com/java-initialize-array)
-- [Guide to Java String Pool](http://www.baeldung.com/java-string-pool)
- [Quick Example - Comparator vs Comparable in Java](http://www.baeldung.com/java-comparator-comparable)
- [Quick Guide to Java Stack](http://www.baeldung.com/java-stack)
- [The Java continue and break Keywords](http://www.baeldung.com/java-continue-and-break)
- [Guide to java.util.Formatter](http://www.baeldung.com/java-string-formatter)
-- [Batch Processing in JDBC](http://www.baeldung.com/jdbc-batch-processing)
- [Check if a Java Array Contains a Value](http://www.baeldung.com/java-array-contains-value)
- [How to Invert an Array in Java](http://www.baeldung.com/java-invert-array)
- [Guide to the Cipher Class](http://www.baeldung.com/java-cipher-class)
- [A Guide to Java Initialization](http://www.baeldung.com/java-initialization)
- [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)
-- [RegEx for matching Date Pattern in Java](http://www.baeldung.com/java-date-regular-expressions)
-- [Introduction to the JDBC RowSet Interface in Java](http://www.baeldung.com/java-jdbc-rowset)
- [Nested Classes in Java](http://www.baeldung.com/java-nested-classes)
- [A Guide to Java Loops](http://www.baeldung.com/java-loops)
- [Varargs in Java](http://www.baeldung.com/java-varargs)
@@ -105,16 +88,12 @@
- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java)
- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
- [How to Make a Deep Copy of an Object in Java](http://www.baeldung.com/java-deep-copy)
-- [Check if a String is a Palindrome](http://www.baeldung.com/java-palindrome)
-- [Comparing Strings in Java](http://www.baeldung.com/java-compare-strings)
- [Guide to Inheritance in Java](http://www.baeldung.com/java-inheritance)
- [Guide to Externalizable Interface in Java](http://www.baeldung.com/java-externalizable)
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
- [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)
-- [An Advanced Tagging Implementation with JPA](http://www.baeldung.com/jpa-tagging-advanced)
-- [Handling Daylight Savings Time in Java](http://www.baeldung.com/java-daylight-savings)
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [The "final" Keyword in Java](http://www.baeldung.com/java-final)
@@ -128,7 +107,6 @@
- [Find Sum and Average in a Java Array](http://www.baeldung.com/java-array-sum-average)
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure)
-- [Display All Time Zones With GMT And UTC in Java](http://www.baeldung.com/java-time-zones)
- [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)
@@ -139,11 +117,9 @@
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
- [Using Java Assertions](http://www.baeldung.com/java-assert)
- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
-- [Check If a String Is Numeric in Java](http://www.baeldung.com/java-check-string-number)
- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding)
- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers)
- [Infinite Loops in Java](http://www.baeldung.com/infinite-loops-java)
-- [Why Use char[] Array Over a String for Storing Passwords in Java?](http://www.baeldung.com/java-storing-passwords)
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
- [Singletons in Java](http://www.baeldung.com/java-singleton)
@@ -155,16 +131,17 @@
- [Guide to the this Java Keyword](http://www.baeldung.com/java-this)
- [Jagged Arrays In Java](http://www.baeldung.com/java-jagged-arrays)
- [Importance of Main Manifest Attribute in a Self-Executing JAR](http://www.baeldung.com/java-jar-executable-manifest-main-class)
-- [Extracting Year, Month and Day from Date in Java](http://www.baeldung.com/java-year-month-day)
-- [Get Date Without Time in Java](http://www.baeldung.com/java-date-without-time)
-- [Convert a String to Title Case](http://www.baeldung.com/java-string-title-case)
- [How to Get the File Extension of a File in Java](http://www.baeldung.com/java-file-extension)
- [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object)
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
- [Guide to the java.util.Arrays Class](http://www.baeldung.com/java-util-arrays)
- [Create a Custom Exception in Java](http://www.baeldung.com/java-new-custom-exception)
-- [Guide to java.util.GregorianCalendar](http://www.baeldung.com/java-gregorian-calendar)
- [Java Global Exception Handler](http://www.baeldung.com/java-global-exception-handler)
- [Encrypting and Decrypting Files in Java](http://www.baeldung.com/java-cipher-input-output-stream)
- [How to Get the Size of an Object in Java](http://www.baeldung.com/java-size-of-object)
- [Exception Handling in Java](http://www.baeldung.com/java-exceptions)
+- [Guide to Java Instrumentation](http://www.baeldung.com/java-instrumentation)
+- [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)
+- [Differences Between Final, Finally and Finalize in Java](https://www.baeldung.com/java-final-finally-finalize)
diff --git a/core-java/pom.xml b/core-java/pom.xml
index b83cb478d4..477a01375d 100644
--- a/core-java/pom.xml
+++ b/core-java/pom.xml
@@ -127,11 +127,6 @@
spring-web
${springframework.spring-web.version}
-
- org.springframework.boot
- spring-boot-starter
- ${springframework.boot.spring-boot-starter.version}
-
com.h2database
h2
@@ -142,11 +137,6 @@
mail
${javax.mail.version}
-
- com.ibm.icu
- icu4j
- ${icu4j.version}
-
org.apache.tika
@@ -530,9 +520,8 @@
3.10.0
- 2.19.1
+ 2.21.0
4.3.4.RELEASE
- 1.5.8.RELEASE
1.1
1.4.197
diff --git a/core-java/src/main/java/com/baeldung/binding/Animal.java b/core-java/src/main/java/com/baeldung/binding/Animal.java
new file mode 100644
index 0000000000..12eaa2a7a3
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/binding/Animal.java
@@ -0,0 +1,23 @@
+package com.baeldung.binding;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Created by madhumita.g on 25-07-2018.
+ */
+public class Animal {
+
+ final static Logger logger = LoggerFactory.getLogger(Animal.class);
+
+ public void makeNoise() {
+ logger.info("generic animal noise");
+ }
+
+ public void makeNoise(Integer repetitions) {
+ while(repetitions != 0) {
+ logger.info("generic animal noise countdown " + repetitions);
+ repetitions -= 1;
+ }
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java b/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java
new file mode 100644
index 0000000000..1bd36123e3
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java
@@ -0,0 +1,43 @@
+package com.baeldung.binding;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Created by madhumita.g on 25-07-2018.
+ */
+public class AnimalActivity {
+
+ final static Logger logger = LoggerFactory.getLogger(AnimalActivity.class);
+
+
+ public static void sleep(Animal animal) {
+ logger.info("Animal is sleeping");
+ }
+
+ public static void sleep(Cat cat) {
+ logger.info("Cat is sleeping");
+ }
+
+ public static void main(String[] args) {
+
+ Animal animal = new Animal();
+
+ //calling methods of animal object
+ animal.makeNoise();
+
+ animal.makeNoise(3);
+
+
+ //assigning a dog object to reference of type Animal
+ Animal catAnimal = new Cat();
+
+ catAnimal.makeNoise();
+
+ // calling static function
+ AnimalActivity.sleep(catAnimal);
+
+ return;
+
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/binding/Cat.java b/core-java/src/main/java/com/baeldung/binding/Cat.java
new file mode 100644
index 0000000000..bbe740e412
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/binding/Cat.java
@@ -0,0 +1,18 @@
+package com.baeldung.binding;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Created by madhumita.g on 25-07-2018.
+ */
+public class Cat extends Animal {
+
+ final static Logger logger = LoggerFactory.getLogger(Cat.class);
+
+ public void makeNoise() {
+
+ logger.info("meow");
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java b/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java
new file mode 100644
index 0000000000..26e5bf0c6b
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/classcastexception/ClassCastException.java
@@ -0,0 +1,21 @@
+package com.baeldung.classcastexception;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class ClassCastException {
+
+ public static void main(String[] args) {
+
+ String p1 = new String("John");
+ String p2 = new String("Snow");
+ String[] strArray = new String[] { p1, p2 };
+ ArrayList strList = (ArrayList) Arrays.asList(strArray);
+ // To fix the ClassCastException at above line, modify the code as:
+ // List strList = Arrays.asList(strArray);
+ System.out.println("String list: " + strList);
+
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java
new file mode 100644
index 0000000000..d19772072f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/application/Application.java
@@ -0,0 +1,12 @@
+package com.baeldung.constructorsstaticfactorymethods.application;
+
+import com.baeldung.constructorsstaticfactorymethods.entities.User;
+
+public class Application {
+
+ public static void main(String[] args) {
+ User user1 = User.createWithDefaultCountry("John", "john@domain.com");
+ User user2 = User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina");
+ User user3 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java
new file mode 100644
index 0000000000..4036b622c6
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/constructorsstaticfactorymethods/entities/User.java
@@ -0,0 +1,63 @@
+package com.baeldung.constructorsstaticfactorymethods.entities;
+
+import java.time.LocalTime;
+import java.util.logging.ConsoleHandler;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.logging.SimpleFormatter;
+
+public class User {
+
+ private static volatile User instance = null;
+ private static final Logger LOGGER = Logger.getLogger(User.class.getName());
+ private final String name;
+ private final String email;
+ private final String country;
+
+ public static User createWithDefaultCountry(String name, String email) {
+ return new User(name, email, "Argentina");
+ }
+
+ public static User createWithLoggedInstantiationTime(String name, String email, String country) {
+ setLoggerProperties();
+ LOGGER.log(Level.INFO, "Creating User instance at : {0}", LocalTime.now());
+ return new User(name, email, country);
+ }
+
+ public static User getSingletonInstance(String name, String email, String country) {
+ if (instance == null) {
+ synchronized (User.class) {
+ if (instance == null) {
+ instance = new User(name, email, country);
+ }
+ }
+ }
+ return instance;
+
+ }
+
+ private User(String name, String email, String country) {
+ this.name = name;
+ this.email = email;
+ this.country = country;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public String getCountry() {
+ return country;
+ }
+
+ private static void setLoggerProperties() {
+ ConsoleHandler handler = new ConsoleHandler();
+ handler.setLevel(Level.INFO);
+ handler.setFormatter(new SimpleFormatter());
+ LOGGER.addHandler(handler);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java b/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java
new file mode 100644
index 0000000000..9690648386
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java
@@ -0,0 +1,212 @@
+package com.baeldung.exceptionhandling;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.List;
+import java.util.Scanner;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+
+public class Exceptions {
+
+ private final static Logger logger = Logger.getLogger("ExceptionLogging");
+
+ public static List getPlayers() throws IOException {
+ Path path = Paths.get("players.dat");
+ List players = Files.readAllLines(path);
+
+ return players.stream()
+ .map(Player::new)
+ .collect(Collectors.toList());
+ }
+
+ public List loadAllPlayers(String playersFile) throws IOException{
+ try {
+ throw new IOException();
+ } catch(IOException ex) {
+ throw new IllegalStateException();
+ }
+ }
+
+ public int getPlayerScoreThrows(String playerFile) throws FileNotFoundException {
+ Scanner contents = new Scanner(new File(playerFile));
+ return Integer.parseInt(contents.nextLine());
+ }
+
+ public int getPlayerScoreTryCatch(String playerFile) {
+ try {
+ Scanner contents = new Scanner(new File(playerFile));
+ return Integer.parseInt(contents.nextLine());
+ } catch (FileNotFoundException noFile) {
+ throw new IllegalArgumentException("File not found");
+ }
+ }
+
+ public int getPlayerScoreTryCatchRecovery(String playerFile) {
+ try {
+ Scanner contents = new Scanner(new File(playerFile));
+ return Integer.parseInt(contents.nextLine());
+ } catch ( FileNotFoundException noFile ) {
+ logger.warning("File not found, resetting score.");
+ return 0;
+ }
+ }
+
+ public int getPlayerScoreFinally(String playerFile) throws FileNotFoundException {
+ Scanner contents = null;
+ try {
+ contents = new Scanner(new File(playerFile));
+ return Integer.parseInt(contents.nextLine());
+ } finally {
+ if (contents != null) {
+ contents.close();
+ }
+ }
+ }
+
+ public int getPlayerScoreTryWithResources(String playerFile) {
+ try (Scanner contents = new Scanner(new File(playerFile))) {
+ return Integer.parseInt(contents.nextLine());
+ } catch (FileNotFoundException e ) {
+ logger.warning("File not found, resetting score.");
+ return 0;
+ }
+ }
+
+ public int getPlayerScoreMultipleCatchBlocks(String playerFile) {
+ try (Scanner contents = new Scanner(new File(playerFile))) {
+ return Integer.parseInt(contents.nextLine());
+ } catch (IOException e) {
+ logger.warning("Player file wouldn't load!");
+ return 0;
+ } catch (NumberFormatException e) {
+ logger.warning("Player file was corrupted!");
+ return 0;
+ }
+ }
+
+ public int getPlayerScoreMultipleCatchBlocksAlternative(String playerFile) {
+ try (Scanner contents = new Scanner(new File(playerFile)) ) {
+ return Integer.parseInt(contents.nextLine());
+ } catch (FileNotFoundException e) {
+ logger.warning("Player file not found!");
+ return 0;
+ } catch (IOException e) {
+ logger.warning("Player file wouldn't load!");
+ return 0;
+ } catch (NumberFormatException e) {
+ logger.warning("Player file was corrupted!");
+ return 0;
+ }
+ }
+
+ public int getPlayerScoreUnionCatchBlocks(String playerFile) {
+ try (Scanner contents = new Scanner(new File(playerFile))) {
+ return Integer.parseInt(contents.nextLine());
+ } catch (IOException | NumberFormatException e) {
+ logger.warning("Failed to load score!");
+ return 0;
+ }
+ }
+
+ public List loadAllPlayersThrowingChecked(String playersFile) throws TimeoutException {
+ boolean tooLong = true;
+
+ while (!tooLong) {
+ // ... potentially long operation
+ }
+ throw new TimeoutException("This operation took too long");
+ }
+
+ public List loadAllPlayersThrowingUnchecked(String playersFile) throws TimeoutException {
+ if(!isFilenameValid(playersFile)) {
+ throw new IllegalArgumentException("Filename isn't valid!");
+ }
+ return null;
+
+ // ...
+ }
+
+ public List loadAllPlayersWrapping(String playersFile) throws IOException {
+ try {
+ throw new IOException();
+ } catch (IOException io) {
+ throw io;
+ }
+ }
+
+ public List loadAllPlayersRethrowing(String playersFile) throws PlayerLoadException {
+ try {
+ throw new IOException();
+ } catch (IOException io) {
+ throw new PlayerLoadException(io);
+ }
+ }
+
+ public List loadAllPlayersThrowable(String playersFile) {
+ try {
+ throw new NullPointerException();
+ } catch ( Throwable t ) {
+ throw t;
+ }
+ }
+
+ class FewerExceptions extends Exceptions {
+ @Override
+ public List loadAllPlayers(String playersFile) { //can't add "throws MyCheckedException
+ return null;
+ // overridden
+ }
+ }
+
+ public void throwAsGotoAntiPattern() throws MyException {
+ try {
+ // bunch of code
+ throw new MyException();
+ // second bunch of code
+ } catch ( MyException e ) {
+ // third bunch of code
+ }
+ }
+
+ public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) {
+ try {
+ // ...
+ } catch (Exception e) {} // <== catch and swallow
+ return 0;
+ }
+
+ public int getPlayerScoreSwallowingExceptionAntiPatternAlternative(String playerFile) {
+ try {
+ // ...
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return 0;
+ }
+
+ public int getPlayerScoreSwallowingExceptionAntiPatternAlternative2(String playerFile) throws PlayerScoreException {
+ try {
+ throw new IOException();
+ } catch (IOException e) {
+ throw new PlayerScoreException(e);
+ }
+ }
+
+ public int getPlayerScoreReturnInFinallyAntiPattern(String playerFile) {
+ int score = 0;
+ try {
+ throw new IOException();
+ } finally {
+ return score; // <== the IOException is dropped
+ }
+ }
+
+ private boolean isFilenameValid(String name) {
+ return false;
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/MyException.java b/core-java/src/main/java/com/baeldung/exceptionhandling/MyException.java
new file mode 100644
index 0000000000..5a50acc4de
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/exceptionhandling/MyException.java
@@ -0,0 +1,5 @@
+package com.baeldung.exceptionhandling;
+
+public class MyException extends Throwable {
+
+}
diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/Player.java b/core-java/src/main/java/com/baeldung/exceptionhandling/Player.java
new file mode 100644
index 0000000000..4efd37134f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/exceptionhandling/Player.java
@@ -0,0 +1,12 @@
+package com.baeldung.exceptionhandling;
+
+public class Player {
+
+ public int id;
+ public String name;
+
+ public Player(String name) {
+ this.name = name;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/PlayerLoadException.java b/core-java/src/main/java/com/baeldung/exceptionhandling/PlayerLoadException.java
new file mode 100644
index 0000000000..5302fd8e7d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/exceptionhandling/PlayerLoadException.java
@@ -0,0 +1,11 @@
+package com.baeldung.exceptionhandling;
+
+import java.io.IOException;
+
+public class PlayerLoadException extends Exception {
+
+ public PlayerLoadException(IOException io) {
+ super(io);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/PlayerScoreException.java b/core-java/src/main/java/com/baeldung/exceptionhandling/PlayerScoreException.java
new file mode 100644
index 0000000000..d11159217e
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/exceptionhandling/PlayerScoreException.java
@@ -0,0 +1,8 @@
+package com.baeldung.exceptionhandling;
+
+public class PlayerScoreException extends Exception {
+
+ public PlayerScoreException(Exception e) {
+ super(e);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/TimeoutException.java b/core-java/src/main/java/com/baeldung/exceptionhandling/TimeoutException.java
new file mode 100644
index 0000000000..294ad542d3
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/exceptionhandling/TimeoutException.java
@@ -0,0 +1,8 @@
+package com.baeldung.exceptionhandling;
+
+public class TimeoutException extends Exception {
+
+ public TimeoutException(String message) {
+ super(message);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java b/core-java/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java
new file mode 100644
index 0000000000..45ff486a79
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java
@@ -0,0 +1,24 @@
+package com.baeldung.fileparser;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+
+public class BufferedReaderExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ ArrayList result = new ArrayList<>();
+
+ try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
+
+ while (br.ready()) {
+ result.add(br.readLine());
+ }
+ return result;
+ }
+
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/fileparser/FileReaderExample.java b/core-java/src/main/java/com/baeldung/fileparser/FileReaderExample.java
new file mode 100644
index 0000000000..f9dd2a9ec5
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/fileparser/FileReaderExample.java
@@ -0,0 +1,31 @@
+package com.baeldung.fileparser;
+
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+
+public class FileReaderExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ ArrayList result = new ArrayList<>();
+
+ try (FileReader f = new FileReader(filename)) {
+ StringBuffer sb = new StringBuffer();
+ while (f.ready()) {
+ char c = (char) f.read();
+ if (c == '\n') {
+ result.add(sb.toString());
+ sb = new StringBuffer();
+ } else {
+ sb.append(c);
+ }
+ }
+ if (sb.length() > 0) {
+ result.add(sb.toString());
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java b/core-java/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java
new file mode 100644
index 0000000000..8e74f7d386
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java
@@ -0,0 +1,18 @@
+package com.baeldung.fileparser;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+
+public class FilesReadLinesExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ List result = Files.readAllLines(Paths.get(filename));
+
+ return (ArrayList) result;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/fileparser/ScannerIntExample.java b/core-java/src/main/java/com/baeldung/fileparser/ScannerIntExample.java
new file mode 100644
index 0000000000..25d17af4ea
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/fileparser/ScannerIntExample.java
@@ -0,0 +1,24 @@
+package com.baeldung.fileparser;
+
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Scanner;
+
+public class ScannerIntExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ ArrayList result = new ArrayList<>();
+
+ try (Scanner s = new Scanner(new FileReader(filename))) {
+
+ while (s.hasNext()) {
+ result.add(s.nextInt());
+ }
+ return result;
+ }
+
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/fileparser/ScannerStringExample.java b/core-java/src/main/java/com/baeldung/fileparser/ScannerStringExample.java
new file mode 100644
index 0000000000..ec213c9490
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/fileparser/ScannerStringExample.java
@@ -0,0 +1,24 @@
+package com.baeldung.fileparser;
+
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Scanner;
+
+public class ScannerStringExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ ArrayList result = new ArrayList<>();
+
+ try (Scanner s = new Scanner(new FileReader(filename))) {
+
+ while (s.hasNext()) {
+ result.add(s.nextLine());
+ }
+ return result;
+ }
+
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java
index c46c3de65a..524f176e6b 100644
--- a/core-java/src/main/java/com/baeldung/hashcode/entities/User.java
+++ b/core-java/src/main/java/com/baeldung/hashcode/entities/User.java
@@ -25,7 +25,7 @@ public class User {
if (this.getClass() != o.getClass())
return false;
User user = (User) o;
- return id != user.id && (!name.equals(user.name) && !email.equals(user.email));
+ return id == user.id && (name.equals(user.name) && email.equals(user.email));
}
@Override
@@ -38,4 +38,5 @@ public class User {
return hash;
}
// getters and setters here
+
}
diff --git a/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java b/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java
new file mode 100644
index 0000000000..af0449c0da
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java
@@ -0,0 +1,18 @@
+package com.baeldung.keywords.finalize;
+
+public class FinalizeObject {
+
+ @Override
+ protected void finalize() throws Throwable {
+ System.out.println("Execute finalize method");
+ super.finalize();
+ }
+
+ public static void main(String[] args) throws Exception {
+ FinalizeObject object = new FinalizeObject();
+ object = null;
+ System.gc();
+ Thread.sleep(1000);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java
new file mode 100644
index 0000000000..8615c78652
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java
@@ -0,0 +1,15 @@
+package com.baeldung.keywords.finalkeyword;
+
+public final class Child extends Parent {
+
+ @Override
+ void method1(int arg1, final int arg2) {
+ // OK
+ }
+
+/* @Override
+ void method2() {
+ // Compilation error
+ }*/
+
+}
diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java
new file mode 100644
index 0000000000..1530c5037f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java
@@ -0,0 +1,5 @@
+package com.baeldung.keywords.finalkeyword;
+
+/*public class GrandChild extends Child {
+ // Compilation error
+}*/
diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java
new file mode 100644
index 0000000000..5cd2996e7a
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java
@@ -0,0 +1,23 @@
+package com.baeldung.keywords.finalkeyword;
+
+public class Parent {
+
+ int field1 = 1;
+ final int field2 = 2;
+
+ Parent() {
+ field1 = 2; // OK
+// field2 = 3; // Compilation error
+ }
+
+ void method1(int arg1, final int arg2) {
+ arg1 = 2; // OK
+// arg2 = 3; // Compilation error
+ }
+
+ final void method2() {
+ final int localVar = 2; // OK
+// localVar = 3; // Compilation error
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java b/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java
new file mode 100644
index 0000000000..3c0aee3196
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java
@@ -0,0 +1,29 @@
+package com.baeldung.keywords.finallykeyword;
+
+public class FinallyExample {
+
+ public static void main(String args[]) throws Exception {
+ try {
+ System.out.println("Execute try block");
+ throw new Exception();
+ } catch (Exception e) {
+ System.out.println("Execute catch block");
+ } finally {
+ System.out.println("Execute finally block");
+ }
+
+ try {
+ System.out.println("Execute try block");
+ } finally {
+ System.out.println("Execute finally block");
+ }
+
+ try {
+ System.out.println("Execute try block");
+ throw new Exception();
+ } finally {
+ System.out.println("Execute finally block");
+ }
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/objectsize/InstrumentationAgent.java b/core-java/src/main/java/com/baeldung/objectsize/InstrumentationAgent.java
new file mode 100644
index 0000000000..66e9a44af8
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/objectsize/InstrumentationAgent.java
@@ -0,0 +1,18 @@
+package com.baeldung.objectsize;
+
+import java.lang.instrument.Instrumentation;
+
+public class InstrumentationAgent {
+ private static volatile Instrumentation globalInstrumentation;
+
+ public static void premain(final String agentArgs, final Instrumentation inst) {
+ globalInstrumentation = inst;
+ }
+
+ public static long getObjectSize(final Object object) {
+ if (globalInstrumentation == null) {
+ throw new IllegalStateException("Agent not initialized.");
+ }
+ return globalInstrumentation.getObjectSize(object);
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/objectsize/InstrumentationExample.java b/core-java/src/main/java/com/baeldung/objectsize/InstrumentationExample.java
new file mode 100644
index 0000000000..f751d954c8
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/objectsize/InstrumentationExample.java
@@ -0,0 +1,59 @@
+package com.baeldung.objectsize;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class InstrumentationExample {
+
+ public static void printObjectSize(Object object) {
+ System.out.println("Object type: " + object.getClass() + ", size: " + InstrumentationAgent.getObjectSize(object) + " bytes");
+ }
+
+ public static void main(String[] arguments) {
+ String emptyString = "";
+ String string = "Estimating Object Size Using Instrumentation";
+ String[] stringArray = { emptyString, string, "com.baeldung" };
+ String[] anotherStringArray = new String[100];
+ List stringList = new ArrayList<>();
+ StringBuilder stringBuilder = new StringBuilder(100);
+ int maxIntPrimitive = Integer.MAX_VALUE;
+ int minIntPrimitive = Integer.MIN_VALUE;
+ Integer maxInteger = Integer.MAX_VALUE;
+ Integer minInteger = Integer.MIN_VALUE;
+ long zeroLong = 0L;
+ double zeroDouble = 0.0;
+ boolean falseBoolean = false;
+ Object object = new Object();
+
+ class EmptyClass {
+ }
+ EmptyClass emptyClass = new EmptyClass();
+
+ class StringClass {
+ public String s;
+ }
+ StringClass stringClass = new StringClass();
+
+ printObjectSize(emptyString);
+ printObjectSize(string);
+ printObjectSize(stringArray);
+ printObjectSize(anotherStringArray);
+ printObjectSize(stringList);
+ printObjectSize(stringBuilder);
+ printObjectSize(maxIntPrimitive);
+ printObjectSize(minIntPrimitive);
+ printObjectSize(maxInteger);
+ printObjectSize(minInteger);
+ printObjectSize(zeroLong);
+ printObjectSize(zeroDouble);
+ printObjectSize(falseBoolean);
+ printObjectSize(Day.TUESDAY);
+ printObjectSize(object);
+ printObjectSize(emptyClass);
+ printObjectSize(stringClass);
+ }
+
+ public enum Day {
+ MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/objectsize/MANIFEST.MF b/core-java/src/main/java/com/baeldung/objectsize/MANIFEST.MF
new file mode 100644
index 0000000000..b814f624d0
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/objectsize/MANIFEST.MF
@@ -0,0 +1 @@
+Premain-class: com.baeldung.objectsize.InstrumentationAgent
diff --git a/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java b/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java
new file mode 100644
index 0000000000..bebffe52f1
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/string/AppendCharAtPositionX.java
@@ -0,0 +1,45 @@
+/**
+ *
+ */
+package com.baeldung.string;
+
+/**
+ * @author swpraman
+ *
+ */
+public class AppendCharAtPositionX {
+
+ public String addCharUsingCharArray(String str, char ch, int position) {
+ validate(str, position);
+ int len = str.length();
+ char[] updatedArr = new char[len + 1];
+ str.getChars(0, position, updatedArr, 0);
+ updatedArr[position] = ch;
+ str.getChars(position, len, updatedArr, position + 1);
+ return new String(updatedArr);
+ }
+
+ public String addCharUsingSubstring(String str, char ch, int position) {
+ validate(str, position);
+ return str.substring(0, position) + ch + str.substring(position);
+ }
+
+ public String addCharUsingStringBuilder(String str, char ch, int position) {
+ validate(str, position);
+ StringBuilder sb = new StringBuilder(str);
+ sb.insert(position, ch);
+ return sb.toString();
+ }
+
+ private void validate(String str, int position) {
+ if (str == null) {
+ throw new IllegalArgumentException("Str should not be null");
+ }
+ int len = str.length();
+ if (position < 0 || position > len) {
+ throw new IllegalArgumentException("position[" + position + "] should be "
+ + "in the range 0.." + len + " for string " + str);
+ }
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java b/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java
new file mode 100644
index 0000000000..bdf6684f78
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/synthetic/BridgeMethodDemo.java
@@ -0,0 +1,23 @@
+package com.baeldung.synthetic;
+
+import java.util.Comparator;
+
+/**
+ * Class which contains a synthetic bridge method.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class BridgeMethodDemo implements Comparator {
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
+ */
+ @Override
+ public int compare(Integer o1, Integer o2) {
+ return 0;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java
new file mode 100644
index 0000000000..d3d75ac05e
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticConstructorDemo.java
@@ -0,0 +1,34 @@
+package com.baeldung.synthetic;
+
+/**
+ * Wrapper for a class which contains a synthetic constructor.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class SyntheticConstructorDemo {
+
+ /**
+ * We need to instantiate the {@link NestedClass} using a private
+ * constructor from the enclosing instance in order to generate a synthetic
+ * constructor.
+ */
+ private NestedClass nestedClass = new NestedClass();
+
+ /**
+ * Class which contains a synthetic constructor.
+ *
+ * @author Donato Rimenti
+ *
+ */
+ class NestedClass {
+
+ /**
+ * In order to generate a synthetic constructor, this class must have a
+ * private constructor.
+ */
+ private NestedClass() {
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java
new file mode 100644
index 0000000000..1813e03953
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticFieldDemo.java
@@ -0,0 +1,22 @@
+package com.baeldung.synthetic;
+
+/**
+ * Wrapper for a class which contains a synthetic field reference to the outer
+ * class.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class SyntheticFieldDemo {
+
+ /**
+ * Class which contains a synthetic field reference to the outer class.
+ *
+ * @author Donato Rimenti
+ *
+ */
+ class NestedClass {
+
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java b/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java
new file mode 100644
index 0000000000..59be4e1429
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/synthetic/SyntheticMethodDemo.java
@@ -0,0 +1,48 @@
+package com.baeldung.synthetic;
+
+/**
+ * Wrapper for a class which contains two synthetic methods accessors to a
+ * private field.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class SyntheticMethodDemo {
+
+ /**
+ * Class which contains two synthetic methods accessors to a private field.
+ *
+ * @author Donato Rimenti
+ *
+ */
+ class NestedClass {
+
+ /**
+ * Field for which will be generated synthetic methods accessors. It's
+ * important that this field is private for this purpose.
+ */
+ private String nestedField;
+ }
+
+ /**
+ * Gets the private nested field. We need to read the nested field in order
+ * to generate the synthetic getter.
+ *
+ * @return the {@link NestedClass#nestedField}
+ */
+ public String getNestedField() {
+ return new NestedClass().nestedField;
+ }
+
+ /**
+ * Sets the private nested field. We need to write the nested field in order
+ * to generate the synthetic setter.
+ *
+ * @param nestedField
+ * the {@link NestedClass#nestedField}
+ */
+ public void setNestedField(String nestedField) {
+ new NestedClass().nestedField = nestedField;
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java b/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java
new file mode 100644
index 0000000000..50dbc9c774
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/Calculator.java
@@ -0,0 +1,15 @@
+package com.baeldung.throwsexception;
+
+public class Calculator {
+
+ public double divide(double a, double b) {
+ if (b == 0) {
+ throw new DivideByZeroException("Divider cannot be equal to zero!");
+ }
+ return a/b;
+ }
+
+}
+
+
+
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java b/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java
new file mode 100644
index 0000000000..0b371dcedb
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/DataAccessException.java
@@ -0,0 +1,9 @@
+package com.baeldung.throwsexception;
+
+public class DataAccessException extends RuntimeException {
+
+ public DataAccessException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java b/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java
new file mode 100644
index 0000000000..4413374c99
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/DivideByZeroException.java
@@ -0,0 +1,9 @@
+package com.baeldung.throwsexception;
+
+public class DivideByZeroException extends RuntimeException {
+
+ public DivideByZeroException(String message) {
+ super(message);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/Main.java b/core-java/src/main/java/com/baeldung/throwsexception/Main.java
new file mode 100644
index 0000000000..17fbf5a582
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/Main.java
@@ -0,0 +1,41 @@
+package com.baeldung.throwsexception;
+
+import com.sun.mail.iap.ConnectionException;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.net.SocketException;
+
+public class Main {
+
+ public static void main(String[] args) throws FileNotFoundException {
+ TryCatch tryCatch = new TryCatch();
+
+ try {
+ tryCatch.execute();
+ } catch (ConnectionException | SocketException ex) {
+ System.out.println("IOException");
+ } catch (Exception ex) {
+ System.out.println("General exception");
+ }
+
+ checkedException();
+ checkedExceptionWithThrows();
+ }
+
+ private static void checkedExceptionWithThrows() throws FileNotFoundException {
+ File file = new File("not_existing_file.txt");
+ FileInputStream stream = new FileInputStream(file);
+ }
+
+ private static void checkedException() {
+ File file = new File("not_existing_file.txt");
+ try {
+ FileInputStream stream = new FileInputStream(file);
+ } catch (FileNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java b/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java
new file mode 100644
index 0000000000..7d8345c3c1
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/PersonRepository.java
@@ -0,0 +1,12 @@
+package com.baeldung.throwsexception;
+
+import java.sql.SQLException;
+import java.util.List;
+
+public class PersonRepository {
+
+ public List findAll() throws SQLException {
+ throw new SQLException();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java b/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java
new file mode 100644
index 0000000000..6bb8b90bf1
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/SimpleService.java
@@ -0,0 +1,22 @@
+package com.baeldung.throwsexception;
+
+import java.sql.SQLException;
+
+public class SimpleService {
+
+ private PersonRepository personRepository = new PersonRepository();
+
+ public void wrappingException() {
+ try {
+ personRepository.findAll();
+ } catch (SQLException e) {
+ throw new DataAccessException("SQL Exception", e);
+ }
+ }
+
+ public void runtimeNullPointerException() {
+ String a = null;
+ a.length();
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java b/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java
new file mode 100644
index 0000000000..2fd87f124d
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/throwsexception/TryCatch.java
@@ -0,0 +1,13 @@
+package com.baeldung.throwsexception;
+
+import com.sun.mail.iap.ConnectionException;
+
+import java.net.SocketException;
+
+public class TryCatch {
+
+ public void execute() throws SocketException, ConnectionException, Exception {
+ //code that would throw any of: SocketException, ConnectionException, Exception
+ }
+
+}
diff --git a/core-java/src/main/resources/logback.xml b/core-java/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/core-java/src/main/resources/logback.xml
+++ b/core-java/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java
new file mode 100644
index 0000000000..41c67ff389
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java
@@ -0,0 +1,95 @@
+package com.baeldung.binding;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.LoggingEvent;
+import ch.qos.logback.core.Appender;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.LoggerFactory;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.verify;
+
+/**
+ *https://gist.github.com/bloodredsun/a041de13e57bf3c6c040
+ */
+@RunWith(MockitoJUnitRunner.class)
+
+public class AnimalActivityUnitTest {
+
+ @Mock
+ private Appender mockAppender;
+ @Captor
+ private ArgumentCaptor captorLoggingEvent;
+
+ @Before
+ public void setup() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.addAppender(mockAppender);
+ }
+
+ @After
+ public void teardown() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.detachAppender(mockAppender);
+ }
+
+ @Test
+ public void givenAnimalReference__whenRefersAnimalObject_shouldCallFunctionWithAnimalParam() {
+
+ Animal animal = new Animal();
+
+ AnimalActivity.sleep(animal);
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("Animal is sleeping"));
+ }
+
+ @Test
+ public void givenDogReference__whenRefersCatObject_shouldCallFunctionWithAnimalParam() {
+
+ Cat cat = new Cat();
+
+ AnimalActivity.sleep(cat);
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("Cat is sleeping"));
+ }
+
+ @Test
+ public void givenAnimaReference__whenRefersDogObject_shouldCallFunctionWithAnimalParam() {
+
+ Animal cat = new Cat();
+
+ AnimalActivity.sleep(cat);
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("Animal is sleeping"));
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java
new file mode 100644
index 0000000000..a34640b58a
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java
@@ -0,0 +1,87 @@
+package com.baeldung.binding;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.LoggingEvent;
+import ch.qos.logback.core.Appender;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.LoggerFactory;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import java.util.List;
+
+/**
+ * Created by madhumita.g on 01-08-2018.
+ */
+
+@RunWith(MockitoJUnitRunner.class)
+public class AnimalUnitTest {
+ @Mock
+ private Appender mockAppender;
+ @Captor
+ private ArgumentCaptor captorLoggingEvent;
+
+ @Before
+ public void setup() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.addAppender(mockAppender);
+ }
+
+ @After
+ public void teardown() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.detachAppender(mockAppender);
+ }
+
+ @Test
+ public void whenCalledWithoutParameters_shouldCallFunctionMakeNoiseWithoutParameters() {
+
+ Animal animal = new Animal();
+
+ animal.makeNoise();
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("generic animal noise"));
+ }
+
+ @Test
+ public void whenCalledWithParameters_shouldCallFunctionMakeNoiseWithParameters() {
+
+ Animal animal = new Animal();
+
+ int testValue = 3;
+ animal.makeNoise(testValue);
+
+ verify(mockAppender,times(3)).doAppend(captorLoggingEvent.capture());
+
+ final List loggingEvents = captorLoggingEvent.getAllValues();
+
+ for(LoggingEvent loggingEvent : loggingEvents)
+ {
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("generic animal noise countdown "+testValue));
+
+ testValue--;
+ }
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java b/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java
new file mode 100644
index 0000000000..76ccfb7719
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java
@@ -0,0 +1,62 @@
+package com.baeldung.binding;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.LoggingEvent;
+import ch.qos.logback.core.Appender;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.LoggerFactory;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.verify;
+
+/**
+ * Created by madhumita.g on 01-08-2018.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class CatUnitTest {
+
+ @Mock
+ private Appender mockAppender;
+
+ @Captor
+ private ArgumentCaptor captorLoggingEvent;
+
+ @Before
+ public void setup() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.addAppender(mockAppender);
+ }
+
+ @After
+ public void teardown() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.detachAppender(mockAppender);
+ }
+
+ @Test
+ public void makeNoiseTest() {
+
+ Cat cat = new Cat();
+
+ cat.makeNoise();
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("meow"));
+
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java b/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java
new file mode 100644
index 0000000000..0c0266a111
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/constructorsstaticfactorymethods/UserUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.constructorsstaticfactorymethods;
+
+import com.baeldung.constructorsstaticfactorymethods.entities.User;
+import static org.assertj.core.api.Assertions.assertThat;
+import org.junit.Test;
+
+public class UserUnitTest {
+
+ @Test
+ public void givenUserClass_whenCalledcreateWithDefaultCountry_thenCorrect() {
+ assertThat(User.createWithDefaultCountry("John", "john@domain.com")).isInstanceOf(User.class);
+ }
+
+ @Test
+ public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetName_thenCorrect() {
+ User user = User.createWithDefaultCountry("John", "john@domain.com");
+ assertThat(user.getName()).isEqualTo("John");
+ }
+
+ @Test
+ public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetEmail_thenCorrect() {
+ User user = User.createWithDefaultCountry("John", "john@domain.com");
+ assertThat(user.getEmail()).isEqualTo("john@domain.com");
+ }
+
+ @Test
+ public void givenUserIntanceCreatedWithcreateWithDefaultCountry_whenCalledgetCountry_thenCorrect() {
+ User user = User.createWithDefaultCountry("John", "john@domain.com");
+ assertThat(user.getCountry()).isEqualTo("Argentina");
+ }
+
+ @Test
+ public void givenUserInstanceCreatedWithcreateWithInstantiationTime_whenCalledcreateWithInstantiationTime_thenCorrect() {
+ assertThat(User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina")).isInstanceOf(User.class);
+ }
+
+ @Test
+ public void givenUserInstanceCreatedWithgetSingletonIntance_whenCalledgetSingletonInstance_thenCorrect() {
+ User user1 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
+ User user2 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
+ assertThat(user1).isEqualTo(user2);
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
index 35aa07821c..70bfe168dd 100644
--- a/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/enums/PizzaUnitTest.java
@@ -75,26 +75,5 @@ public class PizzaUnitTest {
pz.setStatus(Pizza.PizzaStatusEnum.READY);
pz.deliver();
assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
- }
-
- @Test
- public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() {
- String pizzaEnumValue = "READY";
- PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
- assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void whenConvertedIntoEnum_thenThrowsException() {
- String pizzaEnumValue = "rEAdY";
- PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void givenInvalidEnumValueContentWiseAsString_whenConvertedIntoEnum_thenThrowsException() {
- String pizzaEnumValue = "invalid";
- PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
- }
-
-
+ }
}
diff --git a/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java b/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java
new file mode 100644
index 0000000000..b3f585cfe4
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/exceptionhandling/ExceptionsUnitTest.java
@@ -0,0 +1,80 @@
+package com.baeldung.exceptionhandling;
+
+import org.junit.Test;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.nio.file.NoSuchFileException;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+public class ExceptionsUnitTest {
+
+ Exceptions exceptions = new Exceptions();
+
+ @Test
+ public void getPlayers() {
+ assertThatThrownBy(() -> exceptions.getPlayers())
+ .isInstanceOf(NoSuchFileException.class);
+ }
+
+ @Test
+ public void loadAllPlayers() {
+ assertThatThrownBy(() -> exceptions.loadAllPlayers(""))
+ .isInstanceOf(IllegalStateException.class);
+ }
+
+ @Test
+ public void getPlayerScoreThrows() {
+ assertThatThrownBy(() -> exceptions.getPlayerScoreThrows(""))
+ .isInstanceOf(FileNotFoundException.class);
+ }
+
+ @Test
+ public void getPlayerScoreTryCatch() {
+ assertThatThrownBy(() -> exceptions.getPlayerScoreTryCatch(""))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void getPlayerScoreFinally() {
+ assertThatThrownBy(() -> exceptions.getPlayerScoreFinally(""))
+ .isInstanceOf(FileNotFoundException.class);
+ }
+
+ @Test
+ public void loadAllPlayersThrowingChecked() {
+ assertThatThrownBy(() -> exceptions.loadAllPlayersThrowingChecked(""))
+ .isInstanceOf(TimeoutException.class);
+ }
+
+ @Test
+ public void loadAllPlayersThrowingUnchecked() {
+ assertThatThrownBy(() -> exceptions.loadAllPlayersThrowingUnchecked(""))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void loadAllPlayersWrapping() {
+ assertThatThrownBy(() -> exceptions.loadAllPlayersWrapping(""))
+ .isInstanceOf(IOException.class);
+ }
+
+ @Test
+ public void loadAllPlayersRethrowing() {
+ assertThatThrownBy(() -> exceptions.loadAllPlayersRethrowing(""))
+ .isInstanceOf(PlayerLoadException.class);
+ }
+
+ @Test
+ public void loadAllPlayersThrowable() {
+ assertThatThrownBy(() -> exceptions.loadAllPlayersThrowable(""))
+ .isInstanceOf(NullPointerException.class);
+ }
+
+ @Test
+ public void getPlayerScoreSwallowingExceptionAntiPatternAlternative2() {
+ assertThatThrownBy(() -> exceptions.getPlayerScoreSwallowingExceptionAntiPatternAlternative2(""))
+ .isInstanceOf(PlayerScoreException.class);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java
new file mode 100644
index 0000000000..78f900d796
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class BufferedReaderUnitTest {
+
+ protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
+ List lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME);
+ assertTrue("File does not has 2 lines", lines.size() == 2);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java
new file mode 100644
index 0000000000..a38e58d348
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class FileReaderUnitTest {
+
+ protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
+ List lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME);
+ assertTrue("File does not has 2 lines", lines.size() == 2);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java
new file mode 100644
index 0000000000..c0b742fd47
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class FilesReadAllLinesUnitTest {
+
+ protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
+ List lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME);
+ assertTrue("File does not has 2 lines", lines.size() == 2);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java
new file mode 100644
index 0000000000..0a398ba7c6
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ScannerIntUnitTest {
+
+ protected static final String NUMBER_FILENAME = "src/test/resources/sampleNumberFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetIntArrayList() throws IOException {
+ List numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME);
+ assertTrue("File does not has 2 lines", numbers.size() == 2);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java b/core-java/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java
new file mode 100644
index 0000000000..8f9b0a56c0
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ScannerStringUnitTest {
+
+ protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
+ List lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME);
+ assertTrue("File does not has 2 lines", lines.size() == 2);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java b/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java
new file mode 100644
index 0000000000..b484eecef7
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java
@@ -0,0 +1,59 @@
+package com.baeldung.java.listInitialization;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import lombok.extern.java.Log;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+@Log
+public class ListInitializationUnitTest {
+
+ @Test
+ public void givenAnonymousInnerClass_thenInitialiseList() {
+ List cities = new ArrayList() {
+ {
+ add("New York");
+ add("Rio");
+ add("Tokyo");
+ }
+ };
+
+ Assert.assertTrue(cities.contains("New York"));
+ }
+
+ @Test
+ public void givenArraysAsList_thenInitialiseList() {
+ List list = Arrays.asList("foo", "bar");
+
+ Assert.assertTrue(list.contains("foo"));
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void givenArraysAsList_whenAdd_thenUnsupportedException() {
+ List list = Arrays.asList("foo", "bar");
+
+ list.add("baz");
+ }
+
+ @Test
+ public void givenArrayAsList_whenCreated_thenShareReference() {
+ String[] array = { "foo", "bar" };
+ List list = Arrays.asList(array);
+ array[0] = "baz";
+ Assert.assertEquals("baz", list.get(0));
+ }
+
+ @Test
+ public void givenStream_thenInitializeList() {
+ List list = Stream.of("foo", "bar")
+ .collect(Collectors.toList());
+
+ Assert.assertTrue(list.contains("foo"));
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java
new file mode 100644
index 0000000000..f21a755b01
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java
@@ -0,0 +1,109 @@
+package com.baeldung.regexp.optmization;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.junit.Assert.assertTrue;
+
+public class OptimizedMatcherUnitTest {
+
+ private long time;
+ private long mstimePreCompiled;
+ private long mstimeNotPreCompiled;
+
+ private String action;
+
+ private List items;
+
+ @Before
+ public void setup() {
+ Random random = new Random();
+ items = new ArrayList();
+ long average = 0;
+
+ for (int i = 0; i < 100000; ++i) {
+ StringBuilder s = new StringBuilder();
+ int characters = random.nextInt(7) + 1;
+ for (int k = 0; k < characters; ++ k) {
+ char c = (char)(random.nextInt('Z' - 'A') + 'A');
+ int rep = random.nextInt(95) + 5;
+ for (int j = 0; j < rep; ++ j)
+ s.append(c);
+ average += rep;
+ }
+ items.add(s.toString());
+ }
+
+ average /= 100000;
+ System.out.println("generated data, average length: " + average);
+ }
+
+
+ @Test
+ public void givenANotPreCompiledAndAPreCompiledPatternA_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
+
+ testPatterns("A*");
+ assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
+ }
+
+ @Test
+ public void givenANotPreCompiledAndAPreCompiledPatternABC_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
+
+ testPatterns("A*B*C*");
+ assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
+ }
+
+ @Test
+ public void givenANotPreCompiledAndAPreCompiledPatternECWF_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
+
+ testPatterns("E*C*W*F*");
+ assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
+ }
+
+ private void testPatterns(String regex) {
+ time = System.nanoTime();
+ int matched = 0;
+ int unmatched = 0;
+
+ for (String item : this.items) {
+ if (item.matches(regex)) {
+ ++matched;
+ }
+ else {
+ ++unmatched;
+ }
+ }
+
+ this.action = "uncompiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched;
+
+ this.mstimeNotPreCompiled = (System.nanoTime() - time) / 1000000;
+ System.out.println(this.action + ": " + mstimeNotPreCompiled + "ms");
+
+ time = System.nanoTime();
+
+ Matcher matcher = Pattern.compile(regex).matcher("");
+ matched = 0;
+ unmatched = 0;
+
+ for (String item : this.items) {
+ if (matcher.reset(item).matches()) {
+ ++matched;
+ }
+ else {
+ ++unmatched;
+ }
+ }
+
+ this.action = "compiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched;
+
+ this.mstimePreCompiled = (System.nanoTime() - time) / 1000000;
+ System.out.println(this.action + ": " + mstimePreCompiled + "ms");
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java b/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java
new file mode 100644
index 0000000000..2cdf6145d3
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/string/AppendCharAtPositionXUnitTest.java
@@ -0,0 +1,110 @@
+/**
+ *
+ */
+package com.baeldung.string;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+/**
+ * @author swpraman
+ *
+ */
+public class AppendCharAtPositionXUnitTest {
+
+ private AppendCharAtPositionX appendCharAtPosition = new AppendCharAtPositionX();
+ private String word = "Titanc";
+ private char letter = 'i';
+
+ @Test
+ public void whenUsingCharacterArrayAndCharacterAddedAtBeginning_shouldAddCharacter() {
+ assertEquals("iTitanc", appendCharAtPosition.addCharUsingCharArray(word, letter, 0));
+ }
+
+ @Test
+ public void whenUsingSubstringAndCharacterAddedAtBeginning_shouldAddCharacter() {
+ assertEquals("iTitanc", appendCharAtPosition.addCharUsingSubstring(word, letter, 0));
+ }
+
+ @Test
+ public void whenUsingStringBuilderAndCharacterAddedAtBeginning_shouldAddCharacter() {
+ assertEquals("iTitanc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 0));
+ }
+
+ @Test
+ public void whenUsingCharacterArrayAndCharacterAddedAtMiddle_shouldAddCharacter() {
+ assertEquals("Titianc", appendCharAtPosition.addCharUsingCharArray(word, letter, 3));
+ }
+
+ @Test
+ public void whenUsingSubstringAndCharacterAddedAtMiddle_shouldAddCharacter() {
+ assertEquals("Titianc", appendCharAtPosition.addCharUsingSubstring(word, letter, 3));
+ }
+
+ @Test
+ public void whenUsingStringBuilderAndCharacterAddedAtMiddle_shouldAddCharacter() {
+ assertEquals("Titianc", appendCharAtPosition.addCharUsingStringBuilder(word, letter, 3));
+ }
+
+ @Test
+ public void whenUsingCharacterArrayAndCharacterAddedAtEnd_shouldAddCharacter() {
+ assertEquals("Titanci", appendCharAtPosition.addCharUsingCharArray(word, letter, word.length()));
+ }
+
+ @Test
+ public void whenUsingSubstringAndCharacterAddedAtEnd_shouldAddCharacter() {
+ assertEquals("Titanci", appendCharAtPosition.addCharUsingSubstring(word, letter, word.length()));
+ }
+
+ @Test
+ public void whenUsingStringBuilderAndCharacterAddedAtEnd_shouldAddCharacter() {
+ assertEquals("Titanci", appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length()));
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingCharacterArrayAndCharacterAddedAtNegativePosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingSubstringAndCharacterAddedAtNegativePosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingStringBuilderAndCharacterAddedAtNegativePosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, -1);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingCharacterArrayAndCharacterAddedAtInvalidPosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingSubstringAndCharacterAddedAtInvalidPosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingStringBuilderAndCharacterAddedAtInvalidPosition_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(word, letter, word.length() + 2);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingCharacterArrayAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingSubstringAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void whenUsingStringBuilderAndCharacterAddedAtPositionXAndStringIsNull_shouldThrowException() {
+ appendCharAtPosition.addCharUsingStringBuilder(null, letter, 3);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/synthetic/SyntheticUnitTest.java b/core-java/src/test/java/com/baeldung/synthetic/SyntheticUnitTest.java
new file mode 100644
index 0000000000..20f7647f48
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/synthetic/SyntheticUnitTest.java
@@ -0,0 +1,99 @@
+package com.baeldung.synthetic;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Unit test for {@link SyntheticFieldDemo}, {@link SyntheticMethodDemo},
+ * {@link SyntheticConstructorDemo} and {@link BridgeMethodDemo} classes.
+ *
+ * @author Donato Rimenti
+ *
+ */
+public class SyntheticUnitTest {
+
+ /**
+ * Tests that the {@link SyntheticMethodDemo.NestedClass} contains two synthetic
+ * methods.
+ */
+ @Test
+ public void givenSyntheticMethod_whenIsSinthetic_thenTrue() {
+ // Checks that the nested class contains exactly two synthetic methods.
+ Method[] methods = SyntheticMethodDemo.NestedClass.class.getDeclaredMethods();
+ Assert.assertEquals("This class should contain only two methods", 2, methods.length);
+
+ for (Method m : methods) {
+ System.out.println("Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic());
+ Assert.assertTrue("All the methods of this class should be synthetic", m.isSynthetic());
+ }
+ }
+
+ /**
+ * Tests that {@link SyntheticConstructorDemo.NestedClass} contains a synthetic
+ * constructor.
+ */
+ @Test
+ public void givenSyntheticConstructor_whenIsSinthetic_thenTrue() {
+ // Checks that the nested class contains exactly a synthetic
+ // constructor.
+ int syntheticConstructors = 0;
+ Constructor>[] constructors = SyntheticConstructorDemo.NestedClass.class.getDeclaredConstructors();
+ Assert.assertEquals("This class should contain only two constructors", 2, constructors.length);
+
+ for (Constructor> c : constructors) {
+ System.out.println("Constructor: " + c.getName() + ", isSynthetic: " + c.isSynthetic());
+
+ // Counts the synthetic constructors.
+ if (c.isSynthetic()) {
+ syntheticConstructors++;
+ }
+ }
+
+ // Checks that there's exactly one synthetic constructor.
+ Assert.assertEquals(1, syntheticConstructors);
+ }
+
+ /**
+ * Tests that {@link SyntheticFieldDemo.NestedClass} contains a synthetic field.
+ */
+ @Test
+ public void givenSyntheticField_whenIsSinthetic_thenTrue() {
+ // This class should contain exactly one synthetic field.
+ Field[] fields = SyntheticFieldDemo.NestedClass.class.getDeclaredFields();
+ Assert.assertEquals("This class should contain only one field", 1, fields.length);
+
+ for (Field f : fields) {
+ System.out.println("Field: " + f.getName() + ", isSynthetic: " + f.isSynthetic());
+ Assert.assertTrue("All the fields of this class should be synthetic", f.isSynthetic());
+ }
+ }
+
+ /**
+ * Tests that {@link BridgeMethodDemo} contains a synthetic bridge method.
+ */
+ @Test
+ public void givenBridgeMethod_whenIsBridge_thenTrue() {
+ // This class should contain exactly one synthetic bridge method.
+ int syntheticMethods = 0;
+ Method[] methods = BridgeMethodDemo.class.getDeclaredMethods();
+ for (Method m : methods) {
+ System.out.println(
+ "Method: " + m.getName() + ", isSynthetic: " + m.isSynthetic() + ", isBridge: " + m.isBridge());
+
+ // Counts the synthetic methods and checks that they are also bridge
+ // methods.
+ if (m.isSynthetic()) {
+ syntheticMethods++;
+ Assert.assertTrue("The synthetic method in this class should also be a bridge method", m.isBridge());
+ }
+ }
+
+ // Checks that there's exactly one synthetic bridge method.
+ Assert.assertEquals("There should be exactly 1 synthetic bridge method in this class", 1, syntheticMethods);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java b/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java
new file mode 100644
index 0000000000..ef838ed304
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/throwsexception/CalculatorUnitTest.java
@@ -0,0 +1,17 @@
+package com.baeldung.throwsexception;
+
+import org.junit.Test;
+
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class CalculatorUnitTest {
+
+ @Test
+ public void whenDividerIsZero_thenDivideByZeroExceptionIsThrown() {
+ Calculator calculator = new Calculator();
+
+ assertThrows(DivideByZeroException.class,
+ () -> calculator.divide(10, 0));
+ }
+
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java b/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java
new file mode 100644
index 0000000000..b9a658a960
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/throwsexception/SimpleServiceUnitTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.throwsexception;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class SimpleServiceUnitTest {
+
+ SimpleService simpleService = new SimpleService();
+
+ @Test
+ void whenSQLExceptionIsThrown_thenShouldBeRethrownWithWrappedException() {
+ assertThrows(DataAccessException.class,
+ () -> simpleService.wrappingException());
+ }
+
+ @Test
+ void whenCalled_thenNullPointerExceptionIsThrown() {
+ assertThrows(NullPointerException.class,
+ () -> simpleService.runtimeNullPointerException());
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java b/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java
index 6aa59e68d0..22fe0f5e57 100644
--- a/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/unsafe/UnsafeUnitTest.java
@@ -1,6 +1,7 @@
package com.baeldung.unsafe;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import sun.misc.Unsafe;
@@ -56,6 +57,7 @@ public class UnsafeUnitTest {
}
@Test
+ @Ignore // Uncomment for local
public void givenArrayBiggerThatMaxInt_whenAllocateItOffHeapMemory_thenSuccess() throws NoSuchFieldException, IllegalAccessException {
//given
long SUPER_SIZE = (long) Integer.MAX_VALUE * 2;
diff --git a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java b/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java
deleted file mode 100644
index bb3abff28d..0000000000
--- a/core-java/src/test/java/org/baeldung/java/enums/PizzaUnitTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package org.baeldung.java.enums;
-
-import static junit.framework.TestCase.assertTrue;
-
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.List;
-
-import org.junit.Test;
-
-import com.baeldung.enums.Pizza;
-
-public class PizzaUnitTest {
-
- @Test
- public void givenPizaOrder_whenReady_thenDeliverable() {
- Pizza testPz = new Pizza();
- testPz.setStatus(Pizza.PizzaStatusEnum.READY);
- assertTrue(testPz.isDeliverable());
- }
-
- @Test
- public void givenPizaOrders_whenRetrievingUnDeliveredPzs_thenCorrectlyRetrieved() {
- List pzList = new ArrayList<>();
- Pizza pz1 = new Pizza();
- pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
-
- Pizza pz2 = new Pizza();
- pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
-
- Pizza pz3 = new Pizza();
- pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
-
- Pizza pz4 = new Pizza();
- pz4.setStatus(Pizza.PizzaStatusEnum.READY);
-
- pzList.add(pz1);
- pzList.add(pz2);
- pzList.add(pz3);
- pzList.add(pz4);
-
- List undeliveredPzs = Pizza.getAllUndeliveredPizzas(pzList);
- assertTrue(undeliveredPzs.size() == 3);
- }
-
- @Test
- public void givenPizaOrders_whenGroupByStatusCalled_thenCorrectlyGrouped() {
-
- List pzList = new ArrayList<>();
- Pizza pz1 = new Pizza();
- pz1.setStatus(Pizza.PizzaStatusEnum.DELIVERED);
-
- Pizza pz2 = new Pizza();
- pz2.setStatus(Pizza.PizzaStatusEnum.ORDERED);
-
- Pizza pz3 = new Pizza();
- pz3.setStatus(Pizza.PizzaStatusEnum.ORDERED);
-
- Pizza pz4 = new Pizza();
- pz4.setStatus(Pizza.PizzaStatusEnum.READY);
-
- pzList.add(pz1);
- pzList.add(pz2);
- pzList.add(pz3);
- pzList.add(pz4);
-
- EnumMap> map = Pizza.groupPizzaByStatus(pzList);
- assertTrue(map.get(Pizza.PizzaStatusEnum.DELIVERED).size() == 1);
- assertTrue(map.get(Pizza.PizzaStatusEnum.ORDERED).size() == 2);
- assertTrue(map.get(Pizza.PizzaStatusEnum.READY).size() == 1);
- }
-
- @Test
- public void givenPizaOrder_whenDelivered_thenPizzaGetsDeliveredAndStatusChanges() {
- Pizza pz = new Pizza();
- pz.setStatus(Pizza.PizzaStatusEnum.READY);
- pz.deliver();
- assertTrue(pz.getStatus() == Pizza.PizzaStatusEnum.DELIVERED);
- }
-
-}
diff --git a/core-java/src/test/resources/sampleNumberFile.txt b/core-java/src/test/resources/sampleNumberFile.txt
new file mode 100644
index 0000000000..7787faa3c1
--- /dev/null
+++ b/core-java/src/test/resources/sampleNumberFile.txt
@@ -0,0 +1,2 @@
+111
+222
\ No newline at end of file
diff --git a/core-java/src/test/resources/sampleTextFile.txt b/core-java/src/test/resources/sampleTextFile.txt
new file mode 100644
index 0000000000..75cb50aafa
--- /dev/null
+++ b/core-java/src/test/resources/sampleTextFile.txt
@@ -0,0 +1,2 @@
+Hello
+World
\ No newline at end of file
diff --git a/core-kotlin/README.md b/core-kotlin/README.md
index 51a99ea20c..734b2c08b3 100644
--- a/core-kotlin/README.md
+++ b/core-kotlin/README.md
@@ -36,3 +36,5 @@
- [Working with Enums in Kotlin](http://www.baeldung.com/kotlin-enum)
- [Create a Java and Kotlin Project with Maven](http://www.baeldung.com/kotlin-maven-java-project)
- [Reflection with Kotlin](http://www.baeldung.com/kotlin-reflection)
+- [Get a Random Number in Kotlin](http://www.baeldung.com/kotlin-random-number)
+- [Idiomatic Logging in Kotlin](http://www.baeldung.com/kotlin-logging)
diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml
index afa7d8a963..6fdc7c7c1a 100644
--- a/core-kotlin/pom.xml
+++ b/core-kotlin/pom.xml
@@ -3,69 +3,24 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-kotlin
- 1.0-SNAPSHOT
jar
com.baeldung
- parent-modules
+ parent-kotlin
1.0.0-SNAPSHOT
+ ../parent-kotlin
- jcenter
- http://jcenter.bintray.com
-
-
- kotlin-ktor
- https://dl.bintray.com/kotlin/ktor/
+ exposed
+ exposed
+ https://dl.bintray.com/kotlin/exposed
-
- org.apache.commons
- commons-math3
- ${commons-math3.version}
-
-
- org.junit.platform
- junit-platform-runner
- ${junit.platform.version}
- test
-
-
- org.jetbrains.kotlin
- kotlin-stdlib
- ${kotlin-stdlib.version}
-
-
- org.jetbrains.kotlin
- kotlin-stdlib-jdk8
- ${kotlin-stdlib.version}
-
-
- khttp
- khttp
- ${khttp.version}
-
-
- org.jetbrains.kotlin
- kotlin-test-junit
- ${kotlin-test-junit.version}
- test
-
-
- org.jetbrains.kotlin
- kotlin-reflect
- ${kotlin-reflect.version}
-
-
- org.jetbrains.kotlinx
- kotlinx-coroutines-core
- ${kotlinx.version}
-
org.jetbrains.spek
spek-api
@@ -84,6 +39,22 @@
1.1.5
test
+
+ org.apache.commons
+ commons-math3
+ ${commons-math3.version}
+
+
+ org.junit.platform
+ junit-platform-runner
+ ${junit.platform.version}
+ test
+
+
+ khttp
+ khttp
+ ${khttp.version}
+
com.nhaarman
mockito-kotlin
@@ -106,138 +77,29 @@
klaxon
${klaxon.version}
-
- io.ktor
- ktor-server-netty
- ${ktor.io.version}
-
-
- io.ktor
- ktor-gson
- ${ktor.io.version}
-
-
- ch.qos.logback
- logback-classic
- 1.2.1
- test
-
+
+ org.jetbrains.exposed
+ exposed
+ ${exposed.version}
+
+
+ com.h2database
+ h2
+ ${h2database.version}
+
-
-
-
- org.jetbrains.kotlin
- kotlin-maven-plugin
- ${kotlin-maven-plugin.version}
-
-
- compile
-
- compile
-
-
-
- ${project.basedir}/src/main/kotlin
- ${project.basedir}/src/main/java
-
-
-
-
- test-compile
-
- test-compile
-
-
-
- ${project.basedir}/src/test/kotlin
- ${project.basedir}/src/test/java
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- ${java.version}
- ${java.version}
-
-
-
-
- default-compile
- none
-
-
-
- default-testCompile
- none
-
-
- java-compile
- compile
-
- compile
-
-
-
- java-test-compile
- test-compile
-
- testCompile
-
-
-
-
-
- maven-failsafe-plugin
- ${maven-failsafe-plugin.version}
-
-
- org.junit.platform
- junit-platform-surefire-provider
- ${junit.platform.version}
-
-
-
-
- junit5
-
- integration-test
- verify
-
-
-
- **/*Test5.java
-
-
-
-
-
-
-
-
- UTF-8
- 1.2.51
- 1.2.51
- 1.2.51
- 1.2.51
- 0.22.5
- 0.9.2
1.5.0
4.1.0
3.0.4
0.1.0
3.6.1
- 1.0.0
+ 1.1.1
5.2.0
3.10.0
+ 1.4.197
+ 0.10.4
-
+
\ No newline at end of file
diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt b/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt
new file mode 100644
index 0000000000..72b8d330e8
--- /dev/null
+++ b/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt
@@ -0,0 +1,17 @@
+package com.baeldung.constructor
+
+class Car {
+ val id: String
+ val type: String
+
+ constructor(id: String, type: String) {
+ this.id = id
+ this.type = type
+ }
+
+}
+
+fun main(args: Array) {
+ val car = Car("1", "sport")
+ val s= Car("2", "suv")
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt b/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt
new file mode 100644
index 0000000000..4483bfcf08
--- /dev/null
+++ b/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt
@@ -0,0 +1,3 @@
+package com.baeldung.constructor
+
+class Employee(name: String, val salary: Int): Person(name)
\ No newline at end of file
diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Person.java b/core-kotlin/src/main/java/com/baeldung/constructor/Person.java
new file mode 100644
index 0000000000..57911b24ee
--- /dev/null
+++ b/core-kotlin/src/main/java/com/baeldung/constructor/Person.java
@@ -0,0 +1,19 @@
+package com.baeldung.constructor;
+
+class PersonJava {
+ final String name;
+ final String surname;
+ final Integer age;
+
+ public PersonJava(String name, String surname) {
+ this.name = name;
+ this.surname = surname;
+ this.age = null;
+ }
+
+ public PersonJava(String name, String surname, Integer age) {
+ this.name = name;
+ this.surname = surname;
+ this.age = age;
+ }
+}
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt
new file mode 100644
index 0000000000..1384cd9937
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrder.kt
@@ -0,0 +1,22 @@
+package com.baeldung.builder
+
+class FoodOrder(
+ val bread: String?,
+ val condiments: String?,
+ val meat: String?,
+ val fish: String?
+) {
+ data class Builder(
+ var bread: String? = null,
+ var condiments: String? = null,
+ var meat: String? = null,
+ var fish: String? = null) {
+
+ fun bread(bread: String) = apply { this.bread = bread }
+ fun condiments(condiments: String) = apply { this.condiments = condiments }
+ fun meat(meat: String) = apply { this.meat = meat }
+ fun fish(fish: String) = apply { this.fish = fish }
+ fun build() = FoodOrder(bread, condiments, meat, fish)
+ }
+}
+
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt
new file mode 100644
index 0000000000..0a68832b00
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderApply.kt
@@ -0,0 +1,8 @@
+package com.baeldung.builder
+
+class FoodOrderApply {
+ var bread: String? = null
+ var condiments: String? = null
+ var meat: String? = null
+ var fish: String? = null
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt
new file mode 100644
index 0000000000..0e4219b40e
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/FoodOrderNamed.kt
@@ -0,0 +1,7 @@
+package com.baeldung.builder
+
+data class FoodOrderNamed(
+ val bread: String? = null,
+ val condiments: String? = null,
+ val meat: String? = null,
+ val fish: String? = null)
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt b/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt
new file mode 100644
index 0000000000..cc348e3fbf
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/builder/Main.kt
@@ -0,0 +1,9 @@
+package com.baeldung.builder
+
+fun main(args: Array) {
+ FoodOrder.Builder()
+ .bread("bread")
+ .condiments("condiments")
+ .meat("meat")
+ .fish("bread").let { println(it) }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt b/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt
new file mode 100644
index 0000000000..3779d74541
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt
@@ -0,0 +1,26 @@
+package com.baeldung.constructor
+
+open class Person(
+ val name: String,
+ val age: Int? = null
+) {
+ val upperCaseName: String = name.toUpperCase()
+
+ init {
+ println("Hello, I'm $name")
+
+ if (age != null && age < 0) {
+ throw IllegalArgumentException("Age cannot be less than zero!")
+ }
+ }
+
+ init {
+ println("upperCaseName is $upperCaseName")
+ }
+
+}
+
+fun main(args: Array) {
+ val person = Person("John")
+ val personWithAge = Person("John", 22)
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt b/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt
new file mode 100644
index 0000000000..ee01c06646
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt
@@ -0,0 +1,75 @@
+package com.baeldung.nested
+
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+class Computer(val model: String) {
+
+ companion object {
+ const val originCountry = "China"
+ fun getBuiltDate(): String {
+ return "2018-05-23"
+ }
+
+ val log: Logger = LoggerFactory.getLogger(Computer::class.java)
+ }
+
+ //Nested class
+ class MotherBoard(val manufacturer: String) {
+ fun getInfo() = "Made by $manufacturer installed in $originCountry - ${getBuiltDate()}"
+ }
+
+ //Inner class
+ inner class HardDisk(val sizeInGb: Int) {
+ fun getInfo() = "Installed on ${this@Computer} with $sizeInGb GB"
+ }
+
+ interface Switcher {
+ fun on(): String
+ }
+
+ interface Protector {
+ fun smart()
+ }
+
+ fun powerOn(): String {
+ //Local class
+ var defaultColor = "Blue"
+
+ class Led(val color: String) {
+ fun blink(): String {
+ return "blinking $color"
+ }
+
+ fun changeDefaultPowerOnColor() {
+ defaultColor = "Violet"
+ }
+ }
+
+ val powerLed = Led("Green")
+ log.debug("defaultColor is $defaultColor")
+ powerLed.changeDefaultPowerOnColor()
+ log.debug("defaultColor changed inside Led class to $defaultColor")
+ //Anonymous object
+ val powerSwitch = object : Switcher, Protector {
+ override fun on(): String {
+ return powerLed.blink()
+ }
+
+ override fun smart() {
+ log.debug("Smart protection is implemented")
+ }
+
+ fun changeDefaultPowerOnColor() {
+ defaultColor = "Yellow"
+ }
+ }
+ powerSwitch.changeDefaultPowerOnColor()
+ log.debug("defaultColor changed inside powerSwitch anonymous object to $defaultColor")
+ return powerSwitch.on()
+ }
+
+ override fun toString(): String {
+ return "Computer(model=$model)"
+ }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/resources/logback.xml b/core-kotlin/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/core-kotlin/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt
new file mode 100644
index 0000000000..17f5a43479
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/builder/BuilderPatternUnitTest.kt
@@ -0,0 +1,139 @@
+package com.baeldung.builder
+
+import org.junit.jupiter.api.Assertions
+import org.junit.jupiter.api.Test
+
+internal class BuilderPatternUnitTest {
+
+ @Test
+ fun whenBuildingFoodOrderSettingValues_thenFieldsNotNull() {
+
+ val foodOrder = FoodOrder.Builder()
+ .bread("white bread")
+ .meat("bacon")
+ .fish("salmon")
+ .condiments("olive oil")
+ .build()
+
+ Assertions.assertNotNull(foodOrder.bread)
+ Assertions.assertNotNull(foodOrder.meat)
+ Assertions.assertNotNull(foodOrder.condiments)
+ Assertions.assertNotNull(foodOrder.fish)
+ }
+
+ @Test
+ fun whenBuildingFoodOrderSettingValues_thenFieldsContainsValues() {
+
+ val foodOrder = FoodOrder.Builder()
+ .bread("white bread")
+ .meat("bacon")
+ .fish("salmon")
+ .condiments("olive oil")
+ .build()
+
+ Assertions.assertEquals("white bread", foodOrder.bread)
+ Assertions.assertEquals("bacon", foodOrder.meat)
+ Assertions.assertEquals("olive oil", foodOrder.condiments)
+ Assertions.assertEquals("salmon", foodOrder.fish)
+ }
+
+ @Test
+ fun whenBuildingFoodOrderWithoutSettingValues_thenFieldsNull() {
+
+ val foodOrder = FoodOrder.Builder()
+ .build()
+
+ Assertions.assertNull(foodOrder.bread)
+ Assertions.assertNull(foodOrder.meat)
+ Assertions.assertNull(foodOrder.condiments)
+ Assertions.assertNull(foodOrder.fish)
+ }
+
+
+ @Test
+ fun whenBuildingFoodOrderNamedSettingValues_thenFieldsNotNull() {
+
+ val foodOrder = FoodOrderNamed(
+ meat = "bacon",
+ fish = "salmon",
+ condiments = "olive oil",
+ bread = "white bread"
+ )
+
+ Assertions.assertNotNull(foodOrder.bread)
+ Assertions.assertNotNull(foodOrder.meat)
+ Assertions.assertNotNull(foodOrder.condiments)
+ Assertions.assertNotNull(foodOrder.fish)
+ }
+
+ @Test
+ fun whenBuildingFoodOrderNamedSettingValues_thenFieldsContainsValues() {
+
+ val foodOrder = FoodOrderNamed(
+ meat = "bacon",
+ fish = "salmon",
+ condiments = "olive oil",
+ bread = "white bread"
+ )
+
+ Assertions.assertEquals("white bread", foodOrder.bread)
+ Assertions.assertEquals("bacon", foodOrder.meat)
+ Assertions.assertEquals("olive oil", foodOrder.condiments)
+ Assertions.assertEquals("salmon", foodOrder.fish)
+ }
+
+ @Test
+ fun whenBuildingFoodOrderNamedWithoutSettingValues_thenFieldsNull() {
+
+ val foodOrder = FoodOrderNamed()
+
+ Assertions.assertNull(foodOrder.bread)
+ Assertions.assertNull(foodOrder.meat)
+ Assertions.assertNull(foodOrder.condiments)
+ Assertions.assertNull(foodOrder.fish)
+ }
+
+ @Test
+ fun whenBuildingFoodOrderApplySettingValues_thenFieldsNotNull() {
+
+ val foodOrder = FoodOrderApply().apply {
+ meat = "bacon"
+ fish = "salmon"
+ condiments = "olive oil"
+ bread = "white bread"
+ }
+
+ Assertions.assertNotNull(foodOrder.bread)
+ Assertions.assertNotNull(foodOrder.meat)
+ Assertions.assertNotNull(foodOrder.condiments)
+ Assertions.assertNotNull(foodOrder.fish)
+ }
+
+ @Test
+ fun whenBuildingFoodOrderApplySettingValues_thenFieldsContainsValues() {
+
+ val foodOrder = FoodOrderApply().apply {
+ meat = "bacon"
+ fish = "salmon"
+ condiments = "olive oil"
+ bread = "white bread"
+ }
+
+ Assertions.assertEquals("white bread", foodOrder.bread)
+ Assertions.assertEquals("bacon", foodOrder.meat)
+ Assertions.assertEquals("olive oil", foodOrder.condiments)
+ Assertions.assertEquals("salmon", foodOrder.fish)
+ }
+
+ @Test
+ fun whenBuildingFoodOrderApplyWithoutSettingValues_thenFieldsNull() {
+
+ val foodOrder = FoodOrderApply()
+
+ Assertions.assertNull(foodOrder.bread)
+ Assertions.assertNull(foodOrder.meat)
+ Assertions.assertNull(foodOrder.condiments)
+ Assertions.assertNull(foodOrder.fish)
+ }
+
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt
index 54fafdb3e1..d724933654 100644
--- a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/CoroutinesTest.kt
@@ -103,7 +103,7 @@ class CoroutinesTest {
//given
val job = launch(CommonPool) {
while (isActive) {
- println("is working")
+ //println("is working")
}
}
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt
new file mode 100644
index 0000000000..29fa18ef7a
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/kotlin/exposed/ExposedTest.kt
@@ -0,0 +1,333 @@
+package com.baeldung.kotlin.exposed
+
+import org.jetbrains.exposed.dao.*
+import org.jetbrains.exposed.sql.*
+import org.jetbrains.exposed.sql.transactions.TransactionManager
+import org.jetbrains.exposed.sql.transactions.transaction
+import org.junit.Test
+import java.sql.DriverManager
+import kotlin.test.*
+
+class ExposedTest {
+
+ @Test
+ fun whenH2Database_thenConnectionSuccessful() {
+ val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ transaction {
+ assertEquals(1.4.toBigDecimal(), database.version)
+ assertEquals("h2", database.vendor)
+ }
+ }
+
+ @Test
+ fun whenH2DatabaseWithCredentials_thenConnectionSuccessful() {
+ Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver", user = "myself", password = "secret")
+ }
+
+ @Test
+ fun whenH2DatabaseWithManualConnection_thenConnectionSuccessful() {
+ var connected = false
+ Database.connect({ connected = true; DriverManager.getConnection("jdbc:h2:mem:test;MODE=MySQL") })
+ assertEquals(false, connected)
+ transaction {
+ addLogger(StdOutSqlLogger)
+ assertEquals(false, connected)
+ SchemaUtils.create(Cities)
+ assertEquals(true, connected)
+ }
+ }
+
+ @Test
+ fun whenManualCommit_thenOk() {
+ Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ transaction {
+ assertTrue(this is Transaction)
+ commit()
+ commit()
+ commit()
+ }
+ }
+
+ @Test
+ fun whenInsert_thenGeneratedKeys() {
+ Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ transaction {
+ SchemaUtils.create(StarWarsFilms)
+ val id = StarWarsFilms.insertAndGetId {
+ it[name] = "The Last Jedi"
+ it[sequelId] = 8
+ it[director] = "Rian Johnson"
+ }
+ assertEquals(1, id.value)
+ val insert = StarWarsFilms.insert {
+ it[name] = "The Force Awakens"
+ it[sequelId] = 7
+ it[director] = "J.J. Abrams"
+ }
+ assertEquals(2, insert[StarWarsFilms.id]?.value)
+ val selectAll = StarWarsFilms.selectAll()
+ selectAll.forEach {
+ assertTrue { it[StarWarsFilms.sequelId] >= 7 }
+ }
+ StarWarsFilms.slice(StarWarsFilms.name, StarWarsFilms.director).selectAll()
+ .forEach {
+ assertTrue { it[StarWarsFilms.name].startsWith("The") }
+ }
+ val select = StarWarsFilms.select { (StarWarsFilms.director like "J.J.%") and (StarWarsFilms.sequelId eq 7) }
+ assertEquals(1, select.count())
+ StarWarsFilms.update ({ StarWarsFilms.sequelId eq 8 }) {
+ it[name] = "Episode VIII – The Last Jedi"
+ with(SqlExpressionBuilder) {
+ it.update(StarWarsFilms.sequelId, StarWarsFilms.sequelId + 1)
+ }
+ }
+ }
+ }
+
+ @Test
+ fun whenForeignKey_thenAutoJoin() {
+ Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ transaction {
+ addLogger(StdOutSqlLogger)
+ SchemaUtils.create(StarWarsFilms, Players)
+ StarWarsFilms.insert {
+ it[name] = "The Last Jedi"
+ it[sequelId] = 8
+ it[director] = "Rian Johnson"
+ }
+ StarWarsFilms.insert {
+ it[name] = "The Force Awakens"
+ it[sequelId] = 7
+ it[director] = "J.J. Abrams"
+ }
+ Players.insert {
+ it[name] = "Mark Hamill"
+ it[sequelId] = 7
+ }
+ Players.insert {
+ it[name] = "Mark Hamill"
+ it[sequelId] = 8
+ }
+ val simpleInnerJoin = (StarWarsFilms innerJoin Players).selectAll()
+ assertEquals(2, simpleInnerJoin.count())
+ simpleInnerJoin.forEach {
+ assertNotNull(it[StarWarsFilms.name])
+ assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
+ assertEquals("Mark Hamill", it[Players.name])
+ }
+ val innerJoinWithCondition = (StarWarsFilms innerJoin Players)
+ .select { StarWarsFilms.sequelId eq Players.sequelId }
+ assertEquals(2, innerJoinWithCondition.count())
+ innerJoinWithCondition.forEach {
+ assertNotNull(it[StarWarsFilms.name])
+ assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
+ assertEquals("Mark Hamill", it[Players.name])
+ }
+ val complexInnerJoin = Join(StarWarsFilms, Players, joinType = JoinType.INNER, onColumn = StarWarsFilms.sequelId, otherColumn = Players.sequelId, additionalConstraint = {
+ StarWarsFilms.sequelId eq 8
+ }).selectAll()
+ assertEquals(1, complexInnerJoin.count())
+ complexInnerJoin.forEach {
+ assertNotNull(it[StarWarsFilms.name])
+ assertEquals(it[StarWarsFilms.sequelId], it[Players.sequelId])
+ assertEquals("Mark Hamill", it[Players.name])
+ }
+
+ }
+ }
+
+ @Test
+ fun whenJoinWithAlias_thenFun() {
+ Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ transaction {
+ addLogger(StdOutSqlLogger)
+ SchemaUtils.create(StarWarsFilms, Players)
+ StarWarsFilms.insert {
+ it[name] = "The Last Jedi"
+ it[sequelId] = 8
+ it[director] = "Rian Johnson"
+ }
+ StarWarsFilms.insert {
+ it[name] = "The Force Awakens"
+ it[sequelId] = 7
+ it[director] = "J.J. Abrams"
+ }
+ val sequel = StarWarsFilms.alias("sequel")
+ Join(StarWarsFilms, sequel,
+ additionalConstraint = { sequel[StarWarsFilms.sequelId] eq StarWarsFilms.sequelId + 1 })
+ .selectAll().forEach {
+ assertEquals(it[sequel[StarWarsFilms.sequelId]], it[StarWarsFilms.sequelId] + 1)
+ }
+ }
+ }
+
+ @Test
+ fun whenEntity_thenDAO() {
+ val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ val connection = database.connector.invoke() //Keep a connection open so the DB is not destroyed after the first transaction
+ val inserted = transaction {
+ addLogger(StdOutSqlLogger)
+ SchemaUtils.create(StarWarsFilms, Players)
+ val theLastJedi = StarWarsFilm.new {
+ name = "The Last Jedi"
+ sequelId = 8
+ director = "Rian Johnson"
+ }
+ assertFalse(TransactionManager.current().entityCache.inserts.isEmpty())
+ assertEquals(1, theLastJedi.id.value) //Reading this causes a flush
+ assertTrue(TransactionManager.current().entityCache.inserts.isEmpty())
+ theLastJedi
+ }
+ transaction {
+ val theLastJedi = StarWarsFilm.findById(1)
+ assertNotNull(theLastJedi)
+ assertEquals(inserted.id, theLastJedi?.id)
+ }
+ connection.close()
+ }
+
+ @Test
+ fun whenManyToOne_thenNavigation() {
+ val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ val connection = database.connector.invoke()
+ transaction {
+ addLogger(StdOutSqlLogger)
+ SchemaUtils.create(StarWarsFilms, Players, Users, UserRatings)
+ val theLastJedi = StarWarsFilm.new {
+ name = "The Last Jedi"
+ sequelId = 8
+ director = "Rian Johnson"
+ }
+ val someUser = User.new {
+ name = "Some User"
+ }
+ val rating = UserRating.new {
+ value = 9
+ user = someUser
+ film = theLastJedi
+ }
+ assertEquals(theLastJedi, rating.film)
+ assertEquals(someUser, rating.user)
+ assertEquals(rating, theLastJedi.ratings.first())
+ }
+ transaction {
+ val theLastJedi = StarWarsFilm.find { StarWarsFilms.sequelId eq 8 }.first()
+ val ratings = UserRating.find { UserRatings.film eq theLastJedi.id }
+ assertEquals(1, ratings.count())
+ val rating = ratings.first()
+ assertEquals("Some User", rating.user.name)
+ assertEquals(rating, theLastJedi.ratings.first())
+ UserRating.new {
+ value = 8
+ user = rating.user
+ film = theLastJedi
+ }
+ assertEquals(2, theLastJedi.ratings.count())
+ }
+ connection.close()
+ }
+
+ @Test
+ fun whenManyToMany_thenAssociation() {
+ val database = Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
+ val connection = database.connector.invoke()
+ val film = transaction {
+ SchemaUtils.create(StarWarsFilms)
+ StarWarsFilm.new {
+ name = "The Last Jedi"
+ sequelId = 8
+ director = "Rian Johnson"
+ }
+ }
+
+ val actor = transaction {
+ SchemaUtils.create(Actors)
+ Actor.new {
+ firstname = "Daisy"
+ lastname = "Ridley"
+ }
+ }
+
+ transaction {
+ SchemaUtils.create(StarWarsFilmActors)
+ film.actors = SizedCollection(listOf(actor))
+ }
+ connection.close()
+ }
+
+}
+
+object Cities: IntIdTable() {
+ val name = varchar("name", 50)
+}
+
+object StarWarsFilms_Simple : Table() {
+ val id = integer("id").autoIncrement().primaryKey()
+ val sequelId = integer("sequel_id").uniqueIndex()
+ val name = varchar("name", 50)
+ val director = varchar("director", 50)
+}
+
+object StarWarsFilms : IntIdTable() {
+ val sequelId = integer("sequel_id").uniqueIndex()
+ val name = varchar("name", 50)
+ val director = varchar("director", 50)
+}
+
+object Players : Table() {
+ //val sequelId = integer("sequel_id").uniqueIndex().references(StarWarsFilms.sequelId)
+ val sequelId = reference("sequel_id", StarWarsFilms.sequelId).uniqueIndex()
+ //val filmId = reference("film_id", StarWarsFilms).nullable()
+ val name = varchar("name", 50)
+}
+
+class StarWarsFilm(id: EntityID) : Entity(id) {
+ companion object : EntityClass(StarWarsFilms)
+
+ var sequelId by StarWarsFilms.sequelId
+ var name by StarWarsFilms.name
+ var director by StarWarsFilms.director
+ var actors by Actor via StarWarsFilmActors
+ val ratings by UserRating referrersOn UserRatings.film
+}
+
+object Users: IntIdTable() {
+ val name = varchar("name", 50)
+}
+
+object UserRatings: IntIdTable() {
+ val value = long("value")
+ val film = reference("film", StarWarsFilms)
+ val user = reference("user", Users)
+}
+
+class User(id: EntityID): IntEntity(id) {
+ companion object : IntEntityClass(Users)
+
+ var name by Users.name
+}
+
+class UserRating(id: EntityID): IntEntity(id) {
+ companion object : IntEntityClass(UserRatings)
+
+ var value by UserRatings.value
+ var film by StarWarsFilm referencedOn UserRatings.film
+ var user by User referencedOn UserRatings.user
+}
+
+object Actors: IntIdTable() {
+ val firstname = varchar("firstname", 50)
+ val lastname = varchar("lastname", 50)
+}
+
+class Actor(id: EntityID): IntEntity(id) {
+ companion object : IntEntityClass(Actors)
+
+ var firstname by Actors.firstname
+ var lastname by Actors.lastname
+}
+
+object StarWarsFilmActors : Table() {
+ val starWarsFilm = reference("starWarsFilm", StarWarsFilms).primaryKey(0)
+ val actor = reference("actor", Actors).primaryKey(1)
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt
new file mode 100644
index 0000000000..7882d85b3c
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt
@@ -0,0 +1,28 @@
+package com.baeldung.nested
+
+import org.assertj.core.api.Assertions.assertThat
+import org.junit.jupiter.api.Test
+
+class ComputerUnitTest {
+
+ @Test
+ fun givenComputer_whenPowerOn_thenBlink() {
+ val computer = Computer("Desktop")
+
+ assertThat(computer.powerOn()).isEqualTo("blinking Green")
+ }
+
+ @Test
+ fun givenMotherboard_whenGetInfo_thenGetInstalledAndBuiltDetails() {
+ val motherBoard = Computer.MotherBoard("MotherBoard Inc.")
+
+ assertThat(motherBoard.getInfo()).isEqualTo("Made by MotherBoard Inc. installed in China - 2018-05-23")
+ }
+
+ @Test
+ fun givenHardDisk_whenGetInfo_thenGetComputerModelAndDiskSizeInGb() {
+ val hardDisk = Computer("Desktop").HardDisk(1000)
+
+ assertThat(hardDisk.getInfo()).isEqualTo("Installed on Computer(model=Desktop) with 1000 GB")
+ }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt
new file mode 100644
index 0000000000..2956a35f8a
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomNumberTest.kt
@@ -0,0 +1,55 @@
+
+import org.junit.jupiter.api.Test
+import java.util.concurrent.ThreadLocalRandom
+import kotlin.test.assertTrue
+
+class RandomNumberTest {
+
+ @Test
+ fun whenRandomNumberWithJavaUtilMath_thenResultIsBetween0And1() {
+ val randomNumber = Math.random()
+ assertTrue { randomNumber >=0 }
+ assertTrue { randomNumber <= 1 }
+ }
+
+ @Test
+ fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInDefaultRanges() {
+ val randomDouble = ThreadLocalRandom.current().nextDouble()
+ val randomInteger = ThreadLocalRandom.current().nextInt()
+ val randomLong = ThreadLocalRandom.current().nextLong()
+ assertTrue { randomDouble >= 0 }
+ assertTrue { randomDouble <= 1 }
+ assertTrue { randomInteger >= Integer.MIN_VALUE }
+ assertTrue { randomInteger <= Integer.MAX_VALUE }
+ assertTrue { randomLong >= Long.MIN_VALUE }
+ assertTrue { randomLong <= Long.MAX_VALUE }
+ }
+
+ @Test
+ fun whenRandomNumberWithKotlinJSMath_thenResultIsBetween0And1() {
+ val randomDouble = Math.random()
+ assertTrue { randomDouble >=0 }
+ assertTrue { randomDouble <= 1 }
+ }
+
+ @Test
+ fun whenRandomNumberWithKotlinNumberRange_thenResultInGivenRange() {
+ val randomInteger = (1..12).shuffled().first()
+ assertTrue { randomInteger >= 1 }
+ assertTrue { randomInteger <= 12 }
+ }
+
+ @Test
+ fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInGivenRanges() {
+ val randomDouble = ThreadLocalRandom.current().nextDouble(1.0, 10.0)
+ val randomInteger = ThreadLocalRandom.current().nextInt(1, 10)
+ val randomLong = ThreadLocalRandom.current().nextLong(1, 10)
+ assertTrue { randomDouble >= 1 }
+ assertTrue { randomDouble <= 10 }
+ assertTrue { randomInteger >= 1 }
+ assertTrue { randomInteger <= 10 }
+ assertTrue { randomLong >= 1 }
+ assertTrue { randomLong <= 10 }
+ }
+
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/resources/Kotlin.out b/core-kotlin/src/test/resources/Kotlin.out
new file mode 100644
index 0000000000..63d15d2528
--- /dev/null
+++ b/core-kotlin/src/test/resources/Kotlin.out
@@ -0,0 +1,2 @@
+Kotlin
+Concise, Safe, Interoperable, Tool-friendly
\ No newline at end of file
diff --git a/couchbase/pom.xml b/couchbase/pom.xml
index f6397fe309..4f0f8787ca 100644
--- a/couchbase/pom.xml
+++ b/couchbase/pom.xml
@@ -3,11 +3,11 @@
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
- couchbase-sdk
+ couchbase
0.1-SNAPSHOT
jar
couchbase
- Couchbase SDK Tutorials
+ Couchbase Tutorials
com.baeldung
diff --git a/couchbase/src/main/resources/logback.xml b/couchbase/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/couchbase/src/main/resources/logback.xml
+++ b/couchbase/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/couchbase/src/test/resources/logback.xml b/couchbase/src/test/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/couchbase/src/test/resources/logback.xml
+++ b/couchbase/src/test/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/custom-pmd/src/main/resources/logback.xml b/custom-pmd/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/custom-pmd/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/dagger/src/main/resources/logback.xml b/dagger/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/dagger/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
index e3179dca32..f435e41afa 100644
--- a/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
+++ b/data-structures/src/main/java/com/baeldung/tree/BinaryTree.java
@@ -57,7 +57,7 @@ public class BinaryTree {
}
public void delete(int value) {
- deleteRecursive(root, value);
+ root = deleteRecursive(root, value);
}
private Node deleteRecursive(Node current, int value) {
diff --git a/data-structures/src/main/resources/logback.xml b/data-structures/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/data-structures/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
similarity index 90%
rename from data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java
rename to data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
index 99e656fe28..f81247b74d 100644
--- a/data-structures/src/test/java/com/baeldung/tree/BinaryTreeTest.java
+++ b/data-structures/src/test/java/com/baeldung/tree/BinaryTreeUnitTest.java
@@ -6,7 +6,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test;
-public class BinaryTreeTest {
+public class BinaryTreeUnitTest {
@Test
public void givenABinaryTree_WhenAddingElements_ThenTreeNotEmpty() {
@@ -70,6 +70,17 @@ public class BinaryTreeTest {
assertEquals(initialSize, bt.getSize());
}
+ @Test
+ public void it_deletes_the_root() {
+ int value = 12;
+ BinaryTree bt = new BinaryTree();
+ bt.add(value);
+
+ assertTrue(bt.containsNode(value));
+ bt.delete(value);
+ assertFalse(bt.containsNode(value));
+ }
+
@Test
public void givenABinaryTree_WhenTraversingInOrder_ThenPrintValues() {
diff --git a/data-structures/src/test/java/com/baeldung/trie/TrieTest.java b/data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java
similarity index 98%
rename from data-structures/src/test/java/com/baeldung/trie/TrieTest.java
rename to data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java
index 6f7073651e..bf9555315c 100644
--- a/data-structures/src/test/java/com/baeldung/trie/TrieTest.java
+++ b/data-structures/src/test/java/com/baeldung/trie/TrieUnitTest.java
@@ -6,7 +6,7 @@ import org.junit.jupiter.api.Assertions;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-public class TrieTest {
+public class TrieUnitTest {
@Test
public void whenEmptyTrie_thenNoElements() {
diff --git a/deeplearning4j/src/main/resources/logback.xml b/deeplearning4j/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/deeplearning4j/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/deltaspike/src/main/resources/logback.xml b/deltaspike/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/deltaspike/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/disruptor/pom.xml b/disruptor/pom.xml
index 6f3a8d9bfd..d3cef3bd9b 100644
--- a/disruptor/pom.xml
+++ b/disruptor/pom.xml
@@ -112,6 +112,7 @@
com.jolira
onejar-maven-plugin
+ ${onejar-maven-plugin.version}
@@ -138,6 +139,7 @@
2.4.3
3.0.2
+ 1.4.4
\ No newline at end of file
diff --git a/disruptor/src/main/resources/logback.xml b/disruptor/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/disruptor/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/dozer/src/main/resources/logback.xml b/dozer/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/dozer/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/drools/src/main/resources/logback.xml b/drools/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/drools/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/dubbo/src/main/resources/logback.xml b/dubbo/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/dubbo/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/eclipse/formatter.xml b/eclipse/formatter.xml
index 808f65cda9..6887946a4c 100644
--- a/eclipse/formatter.xml
+++ b/eclipse/formatter.xml
@@ -1,297 +1,5 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/ejb/README.md b/ejb/README.md
index 994781b064..f47277bf8f 100644
--- a/ejb/README.md
+++ b/ejb/README.md
@@ -3,3 +3,4 @@
- [Guide to EJB Set-up](http://www.baeldung.com/ejb-intro)
- [Java EE Session Beans](http://www.baeldung.com/ejb-session-beans)
- [Introduction to EJB JNDI Lookup on WildFly Application Server](http://www.baeldung.com/wildfly-ejb-jndi)
+- [A Guide to Message Driven Beans in EJB](http://www.baeldung.com/ejb-message-driven-beans)
diff --git a/ejb/ejb-client/src/main/resources/logback.xml b/ejb/ejb-client/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/ejb/ejb-client/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ejb/ejb-remote/src/main/resources/logback.xml b/ejb/ejb-remote/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/ejb/ejb-remote/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ejb/ejb-session-beans/src/main/resources/logback.xml b/ejb/ejb-session-beans/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/ejb/ejb-session-beans/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ejb/wildfly/pom.xml b/ejb/wildfly/pom.xml
index 7159096f3c..53d10a90ed 100644
--- a/ejb/wildfly/pom.xml
+++ b/ejb/wildfly/pom.xml
@@ -2,9 +2,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.wildfly
- wildfly-example
+ wildfly
0.0.1-SNAPSHOT
pom
+ wildfly
com.baeldung.ejb
diff --git a/ejb/wildfly/widlfly-web/src/main/resources/logback.xml b/ejb/wildfly/widlfly-web/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/ejb/wildfly/widlfly-web/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ejb/wildfly/wildfly-ejb-interfaces/src/main/resources/logback.xml b/ejb/wildfly/wildfly-ejb-interfaces/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/ejb/wildfly/wildfly-ejb-interfaces/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ejb/wildfly/wildfly-ejb/src/main/resources/logback.xml b/ejb/wildfly/wildfly-ejb/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/ejb/wildfly/wildfly-ejb/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ejb/wildfly/wildfly-jpa/src/main/resources/logback.xml b/ejb/wildfly/wildfly-jpa/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/ejb/wildfly/wildfly-jpa/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ejb/wildfly/wildfly-mdb/pom.xml b/ejb/wildfly/wildfly-mdb/pom.xml
index 0b2ec7d5a3..186ddc50c0 100644
--- a/ejb/wildfly/wildfly-mdb/pom.xml
+++ b/ejb/wildfly/wildfly-mdb/pom.xml
@@ -1,8 +1,9 @@
4.0.0
- widlfly-mdb
-
+ wildfly-mdb
+ wildfly-mdb
+
com.baeldung.wildfly
wildfly-example
diff --git a/enterprise-patterns/intercepting-filter-pattern/src/main/resources/logback.xml b/enterprise-patterns/intercepting-filter-pattern/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/enterprise-patterns/intercepting-filter-pattern/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ethereum/pom.xml b/ethereum/pom.xml
index f07ed2c6a0..bd1bacb221 100644
--- a/ethereum/pom.xml
+++ b/ethereum/pom.xml
@@ -184,6 +184,7 @@
org.springframework.boot
spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
org.apache.maven.plugins
@@ -213,7 +214,7 @@
3.3.1
5.0.5.RELEASE
1.5.6.RELEASE
- 1.10.19
+ 2.21.0
2.5.0
1.3
2.9.3
@@ -224,6 +225,7 @@
4.12
1.2.3
1.7.25
+ 2.0.4.RELEASE
diff --git a/ethereum/src/main/resources/logback.xml b/ethereum/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/ethereum/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/ethereumj/src/main/resources/logback.xml b/ethereumj/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/ethereumj/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/feign/pom.xml b/feign/pom.xml
index 29c2a784bc..ea645383c1 100644
--- a/feign/pom.xml
+++ b/feign/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
com.baeldung.feign
- feign-client
+ feign
+ feign
com.baeldung
diff --git a/feign/src/main/resources/logback.xml b/feign/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/feign/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/flips/src/main/resources/logback.xml b/flips/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/flips/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/flyway/src/main/resources/logback.xml b/flyway/src/main/resources/logback.xml
index 7f4aa46e0d..56af2d397e 100644
--- a/flyway/src/main/resources/logback.xml
+++ b/flyway/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/geotools/src/main/resources/logback.xml b/geotools/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/geotools/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/google-cloud/src/main/resources/logback.xml b/google-cloud/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/google-cloud/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/google-web-toolkit/README.md b/google-web-toolkit/README.md
index 3526fe9962..65264375bc 100644
--- a/google-web-toolkit/README.md
+++ b/google-web-toolkit/README.md
@@ -1,2 +1,3 @@
### Relevant Articles:
- [Introduction to GWT](http://www.baeldung.com/gwt)
+- [Quick Use of FilenameFilter](http://www.baeldung.com/java-filename-filter)
diff --git a/google-web-toolkit/pom.xml b/google-web-toolkit/pom.xml
index b2f7cab355..db9ce2eac0 100644
--- a/google-web-toolkit/pom.xml
+++ b/google-web-toolkit/pom.xml
@@ -6,10 +6,11 @@
4.0.0
com.baeldung
- google_web_toolkit
+ google-web-toolkit
war
1.0-SNAPSHOT
-
+ google-web-toolkit
+
com.baeldung
parent-modules
diff --git a/google-web-toolkit/src/main/resources/logback.xml b/google-web-toolkit/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/google-web-toolkit/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/graphql/graphql-java/src/main/resources/logback.xml b/graphql/graphql-java/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/graphql/graphql-java/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/grpc/pom.xml b/grpc/pom.xml
index 218e2df008..949f26d376 100644
--- a/grpc/pom.xml
+++ b/grpc/pom.xml
@@ -1,11 +1,11 @@
4.0.0
- grpc
- grpc-demo
+ grpc
0.0.1-SNAPSHOT
jar
-
+ grpc
+
com.baeldung
parent-modules
diff --git a/grpc/src/main/resources/logback.xml b/grpc/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/grpc/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/gson/src/main/java/org/baeldung/gson/entities/User.java b/gson/src/main/java/org/baeldung/gson/entities/User.java
new file mode 100644
index 0000000000..b413f3300e
--- /dev/null
+++ b/gson/src/main/java/org/baeldung/gson/entities/User.java
@@ -0,0 +1,19 @@
+package org.baeldung.gson.entities;
+
+public class User {
+
+ private int id;
+ private String name;
+ private transient String nationality;
+
+ public User(int id, String name, String nationality) {
+ this.id = id;
+ this.name = name;
+ this.nationality = nationality;
+ }
+
+ public User(int id, String name) {
+ this(id, name, null);
+ }
+
+}
diff --git a/gson/src/main/resources/logback.xml b/gson/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/gson/src/main/resources/logback.xml
+++ b/gson/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java b/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java
new file mode 100644
index 0000000000..f6a8de080c
--- /dev/null
+++ b/gson/src/test/java/org/baeldung/gson/serialization/test/JsonFileUnitTest.java
@@ -0,0 +1,43 @@
+package org.baeldung.gson.serialization.test;
+
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.Writer;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
+import org.baeldung.gson.entities.User;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+@RunWith(Parameterized.class)
+public class JsonFileUnitTest {
+
+ @Parameter
+ public Object object;
+
+ @Parameters
+ public static Object[] data() {
+ return new Object[] { 123.45, new User(1, "Tom", "American") };
+ }
+
+ @Test
+ public void givenProperData_whenStoredInFile_shouldSaveJsonSuccessfully() {
+ String filePath = "target/output.json";
+ try (Writer writer = new FileWriter(filePath)) {
+ Gson gson = new GsonBuilder().setPrettyPrinting().create();
+ gson.toJson(object, writer);
+ Assert.assertTrue(Files.exists(Paths.get(filePath)));
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/guava-modules/guava-18/src/main/resources/logback.xml b/guava-modules/guava-18/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guava-modules/guava-18/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guava-modules/guava-19/src/main/resources/logback.xml b/guava-modules/guava-19/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guava-modules/guava-19/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guava-modules/guava-21/src/main/resources/logback.xml b/guava-modules/guava-21/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guava-modules/guava-21/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guava/src/main/resources/logback.xml b/guava/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/guava/src/main/resources/logback.xml
+++ b/guava/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java b/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java
new file mode 100644
index 0000000000..69a7505316
--- /dev/null
+++ b/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java
@@ -0,0 +1,30 @@
+package org.baeldung.guava;
+
+import static org.hamcrest.core.IsEqual.equalTo;
+import static org.junit.Assert.*;
+
+import java.util.Map;
+import org.junit.Test;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Maps;
+
+public class GuavaMapInitializeUnitTest {
+
+ @Test
+ public void givenKeyValuesShoudInitializeMap() {
+ Map articles = ImmutableMap.of("Title", "My New Article", "Title2", "Second Article");
+
+ assertThat(articles.get("Title"), equalTo("My New Article"));
+ assertThat(articles.get("Title2"), equalTo("Second Article"));
+
+ }
+
+
+ @Test
+ public void givenKeyValuesShouldCreateMutableMap() {
+ Map articles = Maps.newHashMap(ImmutableMap.of("Title", "My New Article", "Title2", "Second Article"));
+
+ assertThat(articles.get("Title"), equalTo("My New Article"));
+ assertThat(articles.get("Title2"), equalTo("Second Article"));
+ }
+}
diff --git a/guest/core-java-9/src/main/resources/logback.xml b/guest/core-java-9/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guest/core-java-9/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/core-kotlin/.gitignore b/guest/core-kotlin/.gitignore
new file mode 100644
index 0000000000..0c017e8f8c
--- /dev/null
+++ b/guest/core-kotlin/.gitignore
@@ -0,0 +1,14 @@
+/bin/
+
+#ignore gradle
+.gradle/
+
+
+#ignore build and generated files
+build/
+node/
+out/
+
+#ignore installed node modules and package lock file
+node_modules/
+package-lock.json
diff --git a/guest/core-kotlin/pom.xml b/guest/core-kotlin/pom.xml
new file mode 100644
index 0000000000..6b189143a4
--- /dev/null
+++ b/guest/core-kotlin/pom.xml
@@ -0,0 +1,199 @@
+
+
+ 4.0.0
+ core-kotlin
+ 1.0-SNAPSHOT
+ com.stackify
+ jar
+
+
+
+ jcenter
+ http://jcenter.bintray.com
+
+
+
+
+
+ org.junit.platform
+ junit-platform-runner
+ ${junit.platform.version}
+ test
+
+
+ org.jetbrains.kotlin
+ kotlin-stdlib
+ ${kotlin-stdlib.version}
+
+
+ org.jetbrains.kotlin
+ kotlin-stdlib-jdk8
+ ${kotlin-stdlib.version}
+
+
+ org.jetbrains.kotlin
+ kotlin-test-junit
+ ${kotlin-test-junit.version}
+ test
+
+
+ org.jetbrains.kotlin
+ kotlin-reflect
+ ${kotlin-reflect.version}
+
+
+ org.jetbrains.spek
+ spek-api
+ 1.1.5
+ test
+
+
+ org.jetbrains.spek
+ spek-subject-extension
+ 1.1.5
+ test
+
+
+ org.jetbrains.spek
+ spek-junit-platform-engine
+ 1.1.5
+ test
+
+
+ com.nhaarman
+ mockito-kotlin
+ ${mockito-kotlin.version}
+ test
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ org.apache.maven.plugins
+ maven-failsafe-plugin
+ ${maven-failsafe-plugin.version}
+ test
+
+
+ org.jetbrains.kotlin
+ kotlin-maven-plugin
+ ${kotlin-maven-plugin.version}
+ provided
+
+
+
+
+
+
+ org.jetbrains.kotlin
+ kotlin-maven-plugin
+ ${kotlin-maven-plugin.version}
+
+
+ compile
+
+ compile
+
+
+
+ ${project.basedir}/src/main/kotlin
+
+
+
+
+ test-compile
+
+ test-compile
+
+
+
+ ${project.basedir}/src/test/kotlin
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+ ${java.version}
+ ${java.version}
+
+
+
+
+ default-compile
+ none
+
+
+
+ default-testCompile
+ none
+
+
+ java-compile
+ compile
+
+ compile
+
+
+
+
+
+ maven-failsafe-plugin
+ ${maven-failsafe-plugin.version}
+
+
+ org.junit.platform
+ junit-platform-surefire-provider
+ ${junit.platform.version}
+
+
+
+
+ junit5
+
+ integration-test
+ verify
+
+
+
+ **/*Test5.java
+
+
+
+
+
+
+
+
+
+ 2.22.0
+ UTF-8
+ 1.2.60
+ 1.2.51
+ 1.2.51
+ 1.2.51
+ 0.22.5
+ 1.5.0
+ 3.6.1
+ 1.0.0
+ 5.2.0
+ 3.10.0
+ 3.7.0
+
+
+
diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt
new file mode 100644
index 0000000000..69573fb75b
--- /dev/null
+++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/CompanionObjectTest.kt
@@ -0,0 +1,21 @@
+package com.baeldung.kotlinvsjava
+
+import org.junit.Test
+import kotlin.test.assertEquals
+
+class CompanionObjectTest {
+
+ @Test
+ fun givenAClassWithCompanionObject_whenCallingMethodTheSameAsStaticOne_thenWeGetAResult() {
+ assertEquals("A", A.returnClassName())
+ }
+
+}
+
+class A {
+ companion object {
+ fun returnClassName(): String {
+ return "A"
+ }
+ }
+}
\ No newline at end of file
diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt
new file mode 100644
index 0000000000..fdb5d05db5
--- /dev/null
+++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ConstructorTest.kt
@@ -0,0 +1,18 @@
+package com.baeldung.kotlinvsjava
+
+import org.junit.Test
+import kotlin.test.assertEquals
+
+class ConstructorTests {
+
+ @Test
+ fun givenAClassWithPrimaryConstructor_whenCreatingAnInstance_thenWeGetObject() {
+ var example = Example(1, "Example")
+
+ assertEquals(1, example.id)
+ assertEquals("Example", example.name)
+ }
+
+}
+
+class Example constructor(val id: Int, var name: String)
\ No newline at end of file
diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt
new file mode 100644
index 0000000000..ad79538d3c
--- /dev/null
+++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DataClassTest.kt
@@ -0,0 +1,33 @@
+package com.baeldung.kotlinvsjava
+
+import org.junit.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertFalse
+
+class DataClassTest {
+
+ @Test
+ fun givenASampleDataClass_whenCallingToStringMethod_thenItReturnsAllProperties() {
+ val student = Student(1, "John", "Smith")
+
+ assertEquals(1, student.id)
+ assertEquals("John", student.name)
+ assertEquals("Smith", student.lastName)
+ assertEquals("Student(id=1, name=John, lastName=Smith)", student.toString())
+ }
+
+ @Test
+ fun givenASampleDataClass_whenCreatingACopyWithGeneratedFunction_thenItReturnsACopyWithRequestedChanges() {
+ val student = Student(1, "John", "Smith")
+ val student2 = student.copy(id = 2, name = "Anne")
+
+ assertEquals(2, student2.id)
+ assertEquals("Anne", student2.name)
+ assertEquals("Smith", student2.lastName)
+ assertEquals("Student(id=2, name=Anne, lastName=Smith)", student2.toString())
+ assertFalse(student.equals(student2))
+ }
+
+}
+
+data class Student(val id: Int, val name: String, val lastName: String)
\ No newline at end of file
diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt
new file mode 100644
index 0000000000..2da824c2db
--- /dev/null
+++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/DelegationTest.kt
@@ -0,0 +1,27 @@
+package com.baeldung.kotlinvsjava
+
+import org.junit.Test
+import kotlin.test.assertEquals
+
+class DelegationTest {
+
+ @Test
+ fun givenAClassWithDelegation_whenCallDelegatedMethod_thenWeGetAResultDefinedInPassedObject() {
+ val car = Car(V6Engine())
+
+ assertEquals("Vroom", car.makeSound())
+ }
+
+}
+
+interface Engine {
+ fun makeSound(): String
+}
+
+class V6Engine: Engine {
+ override fun makeSound(): String {
+ return "Vroom"
+ }
+}
+
+class Car(e: Engine) : Engine by e
\ No newline at end of file
diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt
new file mode 100644
index 0000000000..073c4dd890
--- /dev/null
+++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExceptionsTest.kt
@@ -0,0 +1,34 @@
+package com.baeldung.kotlinvsjava
+
+import java.io.IOException
+import kotlin.test.Test
+import kotlin.test.assertEquals
+
+class ExceptionsTest {
+
+ @Test
+ fun givenATryExpression_whenReturning5InLastExpressionOfTryBlock_thenWeGet5() {
+ val value: Int = try { 5 } catch (e: IOException) { 6 }
+
+ assertEquals(5, value)
+ }
+
+ @Test
+ fun givenATryExpression_whenReturning6InLastExpressionOfCatchBlock_thenWeGet6() {
+ val value: Int = try { funThrowingException() } catch (e: IOException) { 6 }
+
+ assertEquals(6, value)
+ }
+
+ @org.junit.Test(expected = IllegalArgumentException::class)
+ fun givenANullString_whenUsingElvisOperator_thenExceptionIsThrown() {
+ val sampleString: String? = null
+
+ sampleString?.length ?: throw IllegalArgumentException("String must not be null")
+ }
+
+ private fun funThrowingException(): Nothing {
+ throw IOException()
+ }
+
+}
\ No newline at end of file
diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt
new file mode 100644
index 0000000000..3db73b6d2d
--- /dev/null
+++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/ExtensionFunctionsTest.kt
@@ -0,0 +1,30 @@
+package com.baeldung.kotlinvsjava
+
+import org.junit.Test
+import kotlin.test.assertEquals
+
+class ExtensionFunctionsTest {
+
+ @Test
+ fun givenAStringWithAnExtensionFunction_whenCallingThatFunction_thenItConcatenatesStrings() {
+ val sampleString = "ABC"
+ val concatenatedString = sampleString.appendString("DEF")
+
+ assertEquals("ABCDEF", concatenatedString)
+ }
+
+ @Test
+ fun givenAStringWithAnExtensionProperty_whenReadingProperty_thenItReturnsLengthOfString() {
+ val sampleString = "ABC"
+
+ assertEquals(3, sampleString.size)
+ }
+
+ fun String.appendString(str : String): String {
+ return plus(str)
+ }
+
+ val String.size: Int
+ get() = length
+
+}
\ No newline at end of file
diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt
new file mode 100644
index 0000000000..6176478dfe
--- /dev/null
+++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/FunctionsTest.kt
@@ -0,0 +1,70 @@
+package com.baeldung.kotlinvsjava
+
+import org.junit.Test
+import kotlin.test.assertEquals
+
+class FunctionsTest {
+
+ @Test
+ fun givenALambdaExpressionConcatenatingString_whenUsingTheFunctionWithAAndBString_thenWeGetAB() {
+ val concat: (String, String) -> String = { a, b -> a + b }
+
+ assertEquals("AB", concat("A","B"))
+ }
+
+ @Test
+ fun givenAnAnonymousFunctionConcatenatingString_whenUsingTheFunctionWithAAndBString_thenWeGetAB() {
+ val concat: (String, String) -> String = fun(a: String, b: String): String { return a + b }
+
+ assertEquals("AB", concat("A","B"))
+ }
+
+ @Test
+ fun givenAnPlusMethodOfString_whenUsingTheFunctionWithAAndBString_thenWeGetAB() {
+ val concat = String::plus
+
+ assertEquals("AB", concat("A","B"))
+ }
+
+ @Test
+ fun givenAStringConstractorAssignedToFunction_whenUsingFunctionReference_thenWeGetNewString() {
+ val concat = ::String
+
+ assertEquals("A", concat().plus("A"))
+ }
+
+ @Test
+ fun givenAClassImplementingAFunctionType_whenUsingTheFunctionWithAAndBString_thenWeGetAB() {
+ val concat = StringConcatenation()
+
+ assertEquals("AB", concat("A", "B"))
+ }
+
+ @Test
+ fun givenALambdaExpressionWithReceiver_whenUsingTheFunctionWithReceiver_thenWeGetABC() {
+ val concat: String.(String, String) -> String = { a, b -> plus(a).plus(b) }
+
+ assertEquals("ABC", "A".concat("B", "C"))
+ }
+
+ @Test
+ fun givenALambdaExpressionWithinLambdaExpression_whenUsingTheFunction_thenWeGetAB() {
+ val concat: (String) -> ((String) -> String) = { a -> {b -> a + b} }
+
+ assertEquals("AB", (concat("A")("B")))
+ }
+
+ @Test
+ fun given3NestedLambdaExpression_whenUsingTheFunction_thenWeGetABC() {
+ val concat: (String) -> (String) -> (String) -> String = { a -> {b -> { c -> a + b + c} } }
+
+ assertEquals("ABC", concat("A")("B")("C"))
+ }
+
+}
+
+class StringConcatenation: (String, String) -> String {
+ override fun invoke(p1: String, p2: String): String {
+ return p1 + p2
+ }
+}
\ No newline at end of file
diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt
new file mode 100644
index 0000000000..1817602cdf
--- /dev/null
+++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/IsOperatorTest.kt
@@ -0,0 +1,36 @@
+package com.baeldung.kotlinvsjava
+
+import org.junit.Test
+import kotlin.math.absoluteValue
+import kotlin.test.assertEquals
+import kotlin.test.assertTrue
+
+class IsOperatorTest {
+
+ @Test
+ fun givenSampleValue_whenUsingIsOperatorInIfStatement_thenItCastsAutomaticallyToString() {
+ val value: Any = "string"
+
+ if(value is String) {
+ assertEquals(6, value.length)
+ }
+ }
+
+ @Test
+ fun givenSampleValue_whenUsingIsOperatorWithAndOperator_thenItCastsAutomaticallyToString() {
+ val value: Any = "string"
+
+ assertTrue(value is String && value.length == 6)
+ }
+
+ @Test
+ fun givenSampleValue_whenUsingWithWhenOperator_thenItCastsAutomaticallyToString() {
+ val value: Any = "string"
+
+ when(value) {
+ is String -> assertEquals(6, value.length)
+ is Int -> assertEquals(6, value.absoluteValue)
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt
new file mode 100644
index 0000000000..8cb3cbc761
--- /dev/null
+++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/NullSafetyTest.kt
@@ -0,0 +1,67 @@
+package com.baeldung.kotlinvsjava
+
+import kotlin.test.Test
+import java.lang.NullPointerException
+import kotlin.test.assertEquals
+import kotlin.test.assertNotNull
+import kotlin.test.assertNull
+
+class NullSafetyTest {
+
+ @Test
+ fun givenStringAndNull_whenUsingSafeCallOperatorWithLengthMethod_thenReturnsLengthForStringAndNullForNull() {
+ val stringValue: String? = "string"
+ val nullValue: String? = null
+
+ assertNotNull(stringValue?.length)
+ assertNull(nullValue?.length)
+ }
+
+ @Test(expected = NullPointerException::class)
+ fun givenNullReference_whenUsingTheNotNullAssertionOperator_thenItThrowsNullPointerException() {
+ val stringValue: String? = "string"
+ val nullValue: String? = null
+
+ assertNotNull(stringValue!!.length)
+ nullValue!!.length
+ }
+
+ @Test
+ fun givenStringAndNull_whenUsingElvisOperator_thenItTestsAgainstNullAndReturnsTheProperValue() {
+ val stringValue: String? = "string"
+ val nullValue: String? = null
+
+ val shouldBeLength: Int = stringValue?.length ?: -1
+ val souldBeMinusOne: Int = nullValue?.length ?: -1
+
+ assertEquals(6, shouldBeLength)
+ assertEquals(-1, souldBeMinusOne)
+ }
+
+ @Test
+ fun givenString_whenCastingToInt_thenItReturnsNull() {
+ val stringValue: String? = "string"
+
+ val intValue: Int? = stringValue as? Int
+
+ assertNull(intValue)
+ }
+
+ @Test
+ fun givenCollectionWithNulls_whenFilterNonNull_thenItReturnsCollectionWithoutNulls() {
+ val list: List = listOf("a", "b", null)
+ val nonNullList = list.filterNotNull()
+
+ assertEquals(2, nonNullList.size)
+ assertEquals(nonNullList, listOf("a", "b"))
+ }
+
+ @Test
+ fun givenCollectionWithNulls_whenLetWithSafeCallOperator_thenItOmitsNulls() {
+ val list: List = listOf("a", "b", null)
+ for(elem in list) {
+ elem?.let { assertNotNull(it) }
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt
new file mode 100644
index 0000000000..a28008da20
--- /dev/null
+++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/OperatorsOverloadingTest.kt
@@ -0,0 +1,61 @@
+package com.baeldung.kotlinvsjava
+
+import org.junit.Test
+import kotlin.test.assertEquals
+import kotlin.test.assertTrue
+
+class OperatorsOverloadingTest {
+
+ @Test
+ fun givenThePlaneClassWithOverloadedIncrementationOperator_whenCallingTheOperator_thenItIncreasesSpeed(){
+ var plane = Plane(0.0)
+
+ plane++
+ assertEquals(50.0, plane.currentSpeed)
+ }
+
+ @Test
+ fun givenThePlaneClassWithOverloadedMinusOperator_whenCallingTheOperator_thenItDecreaseSpeed(){
+ var plane = Plane(1000.0)
+
+ plane - 500.0
+ assertEquals(500.0, plane.currentSpeed)
+ }
+
+ @Test
+ fun givenThePlaneClassWithOverloadedInvokeOperator_whenCallingTheOperator_thenItSetSpeed(){
+ var plane = Plane(0.0)
+
+ plane(150.0)
+ assertEquals(150.0, plane.currentSpeed)
+ }
+
+ @Test
+ fun given2PlaneObjectWithOverloadedComparisonOperator_whenCallingTheOperator_thenItComparesSpeedValues(){
+ var plane = Plane(0.0)
+ var plane2 = Plane(150.0)
+
+ assertTrue(plane < (plane2))
+ }
+
+}
+
+class Plane(var currentSpeed: Double) {
+
+ operator fun inc(): Plane {
+ currentSpeed += 50.0
+ return this
+ }
+
+ operator fun minus(number: Double) {
+ currentSpeed = if(currentSpeed < number) 0.0 else currentSpeed - number
+ }
+
+ operator fun invoke(speed: Double) {
+ currentSpeed = speed
+ }
+
+ operator fun compareTo(plane: Plane): Int {
+ return currentSpeed.compareTo(plane.currentSpeed)
+ }
+}
\ No newline at end of file
diff --git a/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt
new file mode 100644
index 0000000000..95abcd68a2
--- /dev/null
+++ b/guest/core-kotlin/src/test/kotlin/com/baeldung/kotlinvsjava/PropertiesTest.kt
@@ -0,0 +1,32 @@
+package com.baeldung.kotlinvsjava
+
+import org.junit.Test
+import java.math.BigDecimal
+import kotlin.test.assertEquals
+
+class PropertiesTest {
+
+ @Test
+ fun givenASampleClassWithValAndVarProperties_whenSettingPrice_thenWeGetZeroOrOne() {
+ val product = Product()
+ product.price = BigDecimal(10)
+
+ val product2 = Product()
+ product2.price = null
+
+ assertEquals("empty", product.id)
+ assertEquals("empty", product2.id)
+ assertEquals(BigDecimal(10), product.price)
+ assertEquals(BigDecimal(1), product2.price)
+ }
+
+}
+
+class Product {
+
+ val id: String? = "empty"
+
+ var price: BigDecimal? = BigDecimal.ZERO
+ set(value) = if(value == null) { field = BigDecimal.ONE} else { field = value }
+
+}
\ No newline at end of file
diff --git a/guest/deep-jsf/src/main/resources/logback.xml b/guest/deep-jsf/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guest/deep-jsf/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/remote-debugging/pom.xml b/guest/remote-debugging/pom.xml
index 67fed3f1a1..974421de97 100644
--- a/guest/remote-debugging/pom.xml
+++ b/guest/remote-debugging/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.stackify
- java-remote-debugging
+ remote-debugging
0.0.1-SNAPSHOT
war
+ remote-debugging
org.springframework.boot
diff --git a/guest/remote-debugging/src/main/resources/logback.xml b/guest/remote-debugging/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guest/remote-debugging/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/spring-boot-app/src/main/resources/logback.xml b/guest/spring-boot-app/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guest/spring-boot-app/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/spring-mvc/src/main/resources/logback.xml b/guest/spring-mvc/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guest/spring-mvc/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/spring-security/src/main/resources/logback.xml b/guest/spring-security/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guest/spring-security/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/thread-pools/src/main/resources/logback.xml b/guest/thread-pools/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guest/thread-pools/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/tomcat-app/src/main/resources/logback.xml b/guest/tomcat-app/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guest/tomcat-app/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/webservices/rest-server/src/main/resources/logback.xml b/guest/webservices/rest-server/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guest/webservices/rest-server/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/webservices/soap_client/src/main/resources/logback.xml b/guest/webservices/soap_client/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guest/webservices/soap_client/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/webservices/soap_example/src/main/resources/logback.xml b/guest/webservices/soap_example/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guest/webservices/soap_example/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guest/webservices/spring-rest-service/src/main/resources/logback.xml b/guest/webservices/spring-rest-service/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guest/webservices/spring-rest-service/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/guice/src/main/resources/logback.xml b/guice/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/guice/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml
index cc366cd0a6..705792ad05 100644
--- a/hazelcast/pom.xml
+++ b/hazelcast/pom.xml
@@ -13,16 +13,12 @@
-
- com.hazelcast
- hazelcast
- ${hazelcast.version}
-
-
- com.hazelcast
- hazelcast-client
- ${hazelcast.version}
-
+
+
+ com.hazelcast.jet
+ hazelcast-jet
+ ${hazelcast.jet.version}
+
@@ -36,8 +32,8 @@
-
- 3.8.4
+
+ 0.6
\ No newline at end of file
diff --git a/hazelcast/src/main/java/com/baeldung/hazelcast/jet/WordCounter.java b/hazelcast/src/main/java/com/baeldung/hazelcast/jet/WordCounter.java
new file mode 100644
index 0000000000..971986bcae
--- /dev/null
+++ b/hazelcast/src/main/java/com/baeldung/hazelcast/jet/WordCounter.java
@@ -0,0 +1,51 @@
+package com.baeldung.hazelcast.jet;
+
+import java.util.List;
+import java.util.Map;
+
+import static com.hazelcast.jet.Traversers.traverseArray;
+import static com.hazelcast.jet.aggregate.AggregateOperations.counting;
+import static com.hazelcast.jet.function.DistributedFunctions.wholeItem;
+
+import com.hazelcast.jet.Jet;
+import com.hazelcast.jet.JetInstance;
+import com.hazelcast.jet.pipeline.Pipeline;
+import com.hazelcast.jet.pipeline.Sinks;
+import com.hazelcast.jet.pipeline.Sources;
+
+public class WordCounter {
+
+ private static final String LIST_NAME = "textList";
+
+ private static final String MAP_NAME = "countMap";
+
+ private Pipeline createPipeLine() {
+ Pipeline p = Pipeline.create();
+ p.drawFrom(Sources. list(LIST_NAME))
+ .flatMap(word -> traverseArray(word.toLowerCase()
+ .split("\\W+")))
+ .filter(word -> !word.isEmpty())
+ .groupingKey(wholeItem())
+ .aggregate(counting())
+ .drainTo(Sinks.map(MAP_NAME));
+ return p;
+ }
+
+ public Long countWord(List sentences, String word) {
+ long count = 0;
+ JetInstance jet = Jet.newJetInstance();
+ try {
+ List textList = jet.getList(LIST_NAME);
+ textList.addAll(sentences);
+ Pipeline p = createPipeLine();
+ jet.newJob(p)
+ .join();
+ Map counts = jet.getMap(MAP_NAME);
+ count = counts.get(word);
+ } finally {
+ Jet.shutdownAll();
+ }
+ return count;
+ }
+
+}
diff --git a/hazelcast/src/main/resources/logback.xml b/hazelcast/src/main/resources/logback.xml
index ec0dc2469a..56af2d397e 100644
--- a/hazelcast/src/main/resources/logback.xml
+++ b/hazelcast/src/main/resources/logback.xml
@@ -2,7 +2,7 @@
- web - %date [%thread] %-5level %logger{36} - %message%n
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
diff --git a/hazelcast/src/test/java/com/baeldung/hazelcast/jet/WordCounterUnitTest.java b/hazelcast/src/test/java/com/baeldung/hazelcast/jet/WordCounterUnitTest.java
new file mode 100644
index 0000000000..95596b3860
--- /dev/null
+++ b/hazelcast/src/test/java/com/baeldung/hazelcast/jet/WordCounterUnitTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.hazelcast.jet;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+public class WordCounterUnitTest {
+
+ @Test
+ public void whenGivenSentencesAndWord_ThenReturnCountOfWord() {
+ List sentences = new ArrayList<>();
+ sentences.add("The first second was alright, but the second second was tough.");
+ WordCounter wordCounter = new WordCounter();
+ long countSecond = wordCounter.countWord(sentences, "second");
+ assertTrue(countSecond == 3);
+ }
+
+}
diff --git a/hbase/src/main/resources/logback.xml b/hbase/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/hbase/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java
new file mode 100644
index 0000000000..8b0a51858d
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Address.java
@@ -0,0 +1,34 @@
+package com.baeldung.hibernate.joincolumn;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+@Entity
+public class Address {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+ @Column(name = "ZIP")
+ private String zipCode;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getZipCode() {
+ return zipCode;
+ }
+
+ public void setZipCode(String zipCode) {
+ this.zipCode = zipCode;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java
new file mode 100644
index 0000000000..a91fb3b4c9
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Email.java
@@ -0,0 +1,47 @@
+package com.baeldung.hibernate.joincolumn;
+
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+@Entity
+public class Email {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+ private String address;
+
+ @ManyToOne(fetch = FetchType.LAZY)
+ @JoinColumn(name = "employee_id")
+ private Employee employee;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getAddress() {
+ return address;
+ }
+
+ public void setAddress(String address) {
+ this.address = address;
+ }
+
+ public Employee getEmployee() {
+ return employee;
+ }
+
+ public void setEmployee(Employee employee) {
+ this.employee = employee;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java
new file mode 100644
index 0000000000..3fbdb3820e
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Employee.java
@@ -0,0 +1,36 @@
+package com.baeldung.hibernate.joincolumn;
+
+import java.util.List;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+@Entity
+public class Employee {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+ @OneToMany(fetch = FetchType.LAZY, mappedBy = "employee")
+ private List emails;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public List getEmails() {
+ return emails;
+ }
+
+ public void setEmails(List emails) {
+ this.emails = emails;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java
new file mode 100644
index 0000000000..e5b9dc06bc
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/joincolumn/Office.java
@@ -0,0 +1,41 @@
+package com.baeldung.hibernate.joincolumn;
+
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.JoinColumns;
+import javax.persistence.ManyToOne;
+
+@Entity
+public class Office {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private Long id;
+
+ @ManyToOne(fetch = FetchType.LAZY)
+ @JoinColumns({
+ @JoinColumn(name="ADDR_ID", referencedColumnName="ID"),
+ @JoinColumn(name="ADDR_ZIP", referencedColumnName="ZIP")
+ })
+ private Address address;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public Address getAddress() {
+ return address;
+ }
+
+ public void setAddress(Address address) {
+ this.address = address;
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java
new file mode 100644
index 0000000000..4e00be2b5c
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java
@@ -0,0 +1,26 @@
+package com.baeldung.hibernate.lifecycle;
+
+import org.hibernate.EmptyInterceptor;
+import org.hibernate.type.Type;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+public class DirtyDataInspector extends EmptyInterceptor {
+ private static final ArrayList dirtyEntities = new ArrayList<>();
+
+ @Override
+ public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
+ dirtyEntities.add((FootballPlayer) entity);
+ return true;
+ }
+
+ public static List getDirtyEntities() {
+ return dirtyEntities;
+ }
+
+ public static void clearDirtyEntitites() {
+ dirtyEntities.clear();
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java
new file mode 100644
index 0000000000..49799a5292
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java
@@ -0,0 +1,35 @@
+package com.baeldung.hibernate.lifecycle;
+
+import javax.persistence.*;
+
+@Entity
+@Table(name = "Football_Player")
+public class FootballPlayer {
+ @Id
+ @GeneratedValue
+ private long id;
+
+ @Column
+ private String name;
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return "FootballPlayer{" + "id=" + id + ", name='" + name + '\'' + '}';
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java
new file mode 100644
index 0000000000..a06685fb9c
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java
@@ -0,0 +1,96 @@
+package com.baeldung.hibernate.lifecycle;
+
+import org.h2.tools.RunScript;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.hibernate.boot.Metadata;
+import org.hibernate.boot.MetadataSources;
+import org.hibernate.boot.SessionFactoryBuilder;
+import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.engine.spi.EntityEntry;
+import org.hibernate.engine.spi.SessionImplementor;
+import org.hibernate.service.ServiceRegistry;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.stream.Collectors;
+
+public class HibernateLifecycleUtil {
+ private static SessionFactory sessionFactory;
+ private static Connection connection;
+
+ public static void init() throws Exception {
+ Properties hbConfigProp = getHibernateProperties();
+ Class.forName(hbConfigProp.getProperty("hibernate.connection.driver_class"));
+ connection = DriverManager.getConnection(hbConfigProp.getProperty("hibernate.connection.url"), hbConfigProp.getProperty("hibernate.connection.username"), hbConfigProp.getProperty("hibernate.connection.password"));
+
+ try (InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lifecycle-init.sql");
+ InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) {
+ RunScript.execute(connection, h2InitReader);
+ }
+
+ ServiceRegistry serviceRegistry = configureServiceRegistry();
+ sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(new DirtyDataInspector()).build();
+ }
+
+ public static void tearDown() throws Exception {
+ sessionFactory.close();
+ connection.close();
+ }
+
+ public static SessionFactory getSessionFactory() {
+ return sessionFactory;
+ }
+
+ private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
+ MetadataSources metadataSources = new MetadataSources(serviceRegistry);
+ metadataSources.addAnnotatedClass(FootballPlayer.class);
+
+ Metadata metadata = metadataSources.buildMetadata();
+ return metadata.getSessionFactoryBuilder();
+
+ }
+
+ private static ServiceRegistry configureServiceRegistry() throws IOException {
+ Properties properties = getHibernateProperties();
+ return new StandardServiceRegistryBuilder().applySettings(properties).build();
+ }
+
+ private static Properties getHibernateProperties() throws IOException {
+ Properties properties = new Properties();
+ URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate-lifecycle.properties");
+ try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
+ properties.load(inputStream);
+ }
+ return properties;
+ }
+
+ public static List getManagedEntities(Session session) {
+ Map.Entry