diff --git a/.gitignore b/.gitignore
index e78c1e7e24..180462a32f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -48,3 +48,17 @@ dependency-reduced-pom.xml
*.so
*.dylib
*.dll
+
+xml/src/test/resources/example_dom4j_new.xml
+xml/src/test/resources/example_dom4j_updated.xml
+xml/src/test/resources/example_jaxb_new.xml
+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
+
+**/node_modules/
+**/dist
+**/tmp
+**/out-tsc
diff --git a/.travis.yml b/.travis.yml
index 4df8a96f6d..5e2d690b4e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -4,7 +4,7 @@ before_install:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: skip
-script: travis_wait 60 mvn -q install
+script: travis_wait 60 mvn -q install -Pdefault
sudo: required
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 1d916c8409..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:
@@ -19,7 +19,7 @@ In additional to Spring, the following technologies are in focus: `core Java`, `
Building the project
====================
-To do the full build, do: `mvn install -Dgib.enabled=false`
+To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
Working with the code in Eclipse
diff --git a/Twitter4J/pom.xml b/Twitter4J/pom.xml
index 80236a2cd4..982c1adc23 100644
--- a/Twitter4J/pom.xml
+++ b/Twitter4J/pom.xml
@@ -1,13 +1,9 @@
4.0.0
-
- com.mabsisa
Twitter4J
jar
- 1.0-SNAPSHOT
Twitter4J
- http://maven.apache.org
com.baeldung
@@ -23,27 +19,6 @@
-
- ${project.artifactId}
-
-
- src/main/resources
-
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
-
- **/ApplicationTest.java
-
-
-
-
-
-
4.0.6
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/pom.xml b/activejdbc/pom.xml
index 0c8047f10b..542e674ff3 100644
--- a/activejdbc/pom.xml
+++ b/activejdbc/pom.xml
@@ -1,7 +1,6 @@
4.0.0
- com.baeldung
activejdbc
1.0-SNAPSHOT
jar
@@ -79,55 +78,11 @@
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
- brief
- true
- false
-
- **/*Spec*.java
- **/*Test*.java
-
-
- **/helpers/*
- **/*$*
-
-
-
-
-
- snapshots1
- JavaLite Snapshots1
- http://repo.javalite.io/
-
- true
- always
- warn
-
-
-
-
-
-
- snapshots2
- JavaLite Snapshots2
- http://repo.javalite.io/
-
- true
- always
- warn
-
-
-
-
- 1.4.13
+ 2.0
development.test,development
5.1.34
diff --git a/activejdbc/src/main/java/com/baeldung/model/Employee.java b/activejdbc/src/main/java/com/baeldung/model/Employee.java
index b7fa8aaf1f..e6e9be2aac 100644
--- a/activejdbc/src/main/java/com/baeldung/model/Employee.java
+++ b/activejdbc/src/main/java/com/baeldung/model/Employee.java
@@ -16,4 +16,8 @@ public class Employee extends Model {
set("created_by",createdBy);
}
+ public String getLastName() {
+ return getString("last_name");
+ }
+
}
diff --git a/activejdbc/src/main/java/com/baeldung/model/Role.java b/activejdbc/src/main/java/com/baeldung/model/Role.java
index 3f425dbe6b..bbd5a7d169 100644
--- a/activejdbc/src/main/java/com/baeldung/model/Role.java
+++ b/activejdbc/src/main/java/com/baeldung/model/Role.java
@@ -15,4 +15,8 @@ public class Role extends Model {
set("role_name",role);
set("created_by",createdBy);
}
+
+ public String getRoleName() {
+ return getString("role_name");
+ }
}
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/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppTest.java b/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java
similarity index 97%
rename from activejdbc/src/test/java/com/baeldung/ActiveJDBCAppTest.java
rename to activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java
index 316dc34712..22eb87f930 100644
--- a/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppTest.java
+++ b/activejdbc/src/test/java/com/baeldung/ActiveJDBCAppManualTest.java
@@ -7,7 +7,7 @@ import org.junit.Test;
import java.util.List;
-public class ActiveJDBCAppTest extends DBSpec
+public class ActiveJDBCAppManualTest extends DBSpec
{
@Test
public void ifEmployeeCreated_thenIsValid() {
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..9b3bbcdee5 100644
--- a/algorithms/README.md
+++ b/algorithms/README.md
@@ -23,3 +23,8 @@
- [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)
+- [Check If Two Rectangles Overlap In Java](https://www.baeldung.com/java-check-if-two-rectangles-overlap)
+- [Calculate the Distance Between Two Points in Java](https://www.baeldung.com/java-distance-between-two-points)
+- [Find the Intersection of Two Lines in Java](https://www.baeldung.com/java-intersection-of-two-lines)
+- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
diff --git a/algorithms/roundUpToHundred/.gitignore b/algorithms/roundUpToHundred/.gitignore
new file mode 100644
index 0000000000..ae3c172604
--- /dev/null
+++ b/algorithms/roundUpToHundred/.gitignore
@@ -0,0 +1 @@
+/bin/
diff --git a/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundred.java b/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundred.java
new file mode 100644
index 0000000000..f5024c227d
--- /dev/null
+++ b/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundred.java
@@ -0,0 +1,20 @@
+package com.java.src;
+
+import java.util.Scanner;
+
+public class RoundUpToHundred {
+
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ double input = scanner.nextDouble();
+ scanner.close();
+
+ RoundUpToHundred.round(input);
+ }
+
+ static long round(double input) {
+ long i = (long) Math.ceil(input);
+ return ((i + 99) / 100) * 100;
+ };
+
+}
diff --git a/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java b/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java
new file mode 100644
index 0000000000..f35a9a249f
--- /dev/null
+++ b/algorithms/roundUpToHundred/src/com/java/src/RoundUpToHundredTest.java
@@ -0,0 +1,14 @@
+package com.java.src;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class RoundUpToHundredTest {
+ @Test
+ public void givenInput_whenRound_thenRoundUpToTheNearestHundred() {
+ assertEquals("Rounded up to hundred", 100, RoundUpToHundred.round(99));
+ assertEquals("Rounded up to three hundred ", 300, RoundUpToHundred.round(200.2));
+ assertEquals("Returns same rounded value", 400, RoundUpToHundred.round(400));
+ }
+}
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/rectanglesoverlap/Point.java b/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java
new file mode 100644
index 0000000000..68b1e7c594
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Point.java
@@ -0,0 +1,29 @@
+package com.baeldung.algorithms.rectanglesoverlap;
+
+public class Point {
+
+ private int x;
+ private int y;
+
+ public Point(int x, int y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ public int getX() {
+ return x;
+ }
+
+ public void setX(int x) {
+ this.x = x;
+ }
+
+ public int getY() {
+ return y;
+ }
+
+ public void setY(int y) {
+ this.y = y;
+ }
+
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java b/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java
new file mode 100644
index 0000000000..38f5edec61
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/rectanglesoverlap/Rectangle.java
@@ -0,0 +1,40 @@
+package com.baeldung.algorithms.rectanglesoverlap;
+
+public class Rectangle {
+
+ private Point bottomLeft;
+ private Point topRight;
+
+ public Rectangle(Point bottomLeft, Point topRight) {
+ this.bottomLeft = bottomLeft;
+ this.topRight = topRight;
+ }
+
+ public Point getBottomLeft() {
+ return bottomLeft;
+ }
+
+ public void setBottomLeft(Point bottomLeft) {
+ this.bottomLeft = bottomLeft;
+ }
+
+ public Point getTopRight() {
+ return topRight;
+ }
+
+ public void setTopRight(Point topRight) {
+ this.topRight = topRight;
+ }
+
+ public boolean isOverlapping(Rectangle other) {
+ // one rectangle is to the top of the other
+ if (this.topRight.getY() < other.bottomLeft.getY() || this.bottomLeft.getY() > other.topRight.getY()) {
+ return false;
+ }
+ // one rectangle is to the left of the other
+ if (this.topRight.getX() < other.bottomLeft.getX() || this.bottomLeft.getX() > other.topRight.getX()) {
+ return false;
+ }
+ return true;
+ }
+}
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/rectanglesoverlap/RectangleUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java
new file mode 100644
index 0000000000..6707b34477
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/rectanglesoverlap/RectangleUnitTest.java
@@ -0,0 +1,42 @@
+package com.baeldung.algorithms.rectanglesoverlap;
+
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.assertFalse;
+import org.junit.Test;
+
+import com.baeldung.algorithms.rectanglesoverlap.Point;
+import com.baeldung.algorithms.rectanglesoverlap.Rectangle;
+
+public class RectangleUnitTest {
+
+ @Test
+ public void givenTwoOverlappingRectangles_whenisOverlappingCalled_shouldReturnTrue() {
+ Rectangle rectangle1 = new Rectangle(new Point(2, 1), new Point(4, 3));
+ Rectangle rectangle2 = new Rectangle(new Point(1, 1), new Point(6, 4));
+ assertTrue(rectangle1.isOverlapping(rectangle2));
+
+ rectangle1 = new Rectangle(new Point(-5, -2), new Point(2, 3));
+ rectangle2 = new Rectangle(new Point(-2, -1), new Point(5, 2));
+ assertTrue(rectangle1.isOverlapping(rectangle2));
+
+ rectangle1 = new Rectangle(new Point(-5, 1), new Point(2, 4));
+ rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5));
+ assertTrue(rectangle1.isOverlapping(rectangle2));
+ }
+
+ @Test
+ public void givenTwoNonOverlappingRectangles_whenisOverlappingCalled_shouldReturnFalse() {
+ Rectangle rectangle1 = new Rectangle(new Point(-5, 1), new Point(-3, 4));
+ Rectangle rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, 5));
+ assertFalse(rectangle1.isOverlapping(rectangle2));
+
+ rectangle1 = new Rectangle(new Point(-5, 1), new Point(3, 4));
+ rectangle2 = new Rectangle(new Point(-2, -2), new Point(5, -1));
+ assertFalse(rectangle1.isOverlapping(rectangle2));
+
+ rectangle1 = new Rectangle(new Point(-2, 1), new Point(0, 3));
+ rectangle2 = new Rectangle(new Point(3, 1), new Point(5, 4));
+ assertFalse(rectangle1.isOverlapping(rectangle2));
+ }
+
+}
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
new file mode 100644
index 0000000000..3e3234ff96
--- /dev/null
+++ b/apache-avro/pom.xml
@@ -0,0 +1,89 @@
+
+
+ 4.0.0
+ com.baeldung
+ apache-avro
+ 0.0.1-SNAPSHOT
+ Apache Avro
+
+
+ UTF-8
+ 3.5
+ 1.8.2
+ 1.8
+ 1.7.25
+
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+
+ junit
+ junit
+ 4.10
+ test
+
+
+ org.slf4j
+ slf4j-simple
+ ${slf4j.version}
+ compile
+
+
+ org.apache.avro
+ avro
+ ${avro.version}
+
+
+ org.apache.avro
+ avro-compiler
+ ${avro.version}
+
+
+
+ org.apache.avro
+ avro-maven-plugin
+ ${avro.version}
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${compiler-plugin.version}
+
+ ${java.version}
+ ${java.version}
+
+
+
+ org.apache.avro
+ avro-maven-plugin
+ ${avro.version}
+
+
+ schemas
+ generate-sources
+
+ schema
+ protocol
+ idl-protocol
+
+
+ ${project.basedir}/src/main/resources/
+ ${project.basedir}/src/main/java/
+
+
+
+
+
+
+
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/AvroClassGenerator.java b/apache-avro/src/main/java/com/baeldung/avro/util/AvroClassGenerator.java
new file mode 100644
index 0000000000..718b62a752
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/AvroClassGenerator.java
@@ -0,0 +1,14 @@
+package com.baeldung.avro.util;
+
+import org.apache.avro.Schema;
+import org.apache.avro.compiler.specific.SpecificCompiler;
+
+import java.io.File;
+import java.io.IOException;
+
+public class AvroClassGenerator {
+ public void generateAvroClasses() throws IOException {
+ SpecificCompiler compiler = new SpecificCompiler(new Schema.Parser().parse(new File("src/main/resources/avroHttpRequest-schema.avsc")));
+ compiler.compileToDestination(new File("src/main/resources"), new File("src/main/java"));
+ }
+}
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/AvroSchemaBuilder.java b/apache-avro/src/main/java/com/baeldung/avro/util/AvroSchemaBuilder.java
new file mode 100644
index 0000000000..4a1314cd00
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/AvroSchemaBuilder.java
@@ -0,0 +1,24 @@
+package com.baeldung.avro.util;
+
+
+import org.apache.avro.Schema;
+import org.apache.avro.SchemaBuilder;
+
+public class AvroSchemaBuilder {
+
+ public Schema createAvroHttpRequestSchema(){
+
+ Schema clientIdentifier = SchemaBuilder.record("ClientIdentifier").namespace("com.baeldung.avro.model")
+ .fields().requiredString("hostName").requiredString("ipAddress").endRecord();
+
+ Schema avroHttpRequest = SchemaBuilder.record("AvroHttpRequest").namespace("com.baeldung.avro.model").fields()
+ .requiredLong("requestTime")
+ .name("clientIdentifier").type(clientIdentifier).noDefault()
+ .name("employeeNames").type().array().items().stringType().arrayDefault(null)
+ .name("active").type().enumeration("Active").symbols("YES", "NO").noDefault()
+ .endRecord();
+ return avroHttpRequest;
+ }
+}
+
+
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/model/Active.java b/apache-avro/src/main/java/com/baeldung/avro/util/model/Active.java
new file mode 100644
index 0000000000..3ae0508394
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/model/Active.java
@@ -0,0 +1,13 @@
+/**
+ * Autogenerated by Avro
+ *
+ * DO NOT EDIT DIRECTLY
+ */
+package com.baeldung.avro.util.model;
+@SuppressWarnings("all")
+@org.apache.avro.specific.AvroGenerated
+public enum Active {
+ YES, NO ;
+ public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"enum\",\"name\":\"Active\",\"namespace\":\"com.baeldung.avro.model\",\"symbols\":[\"YES\",\"NO\"]}");
+ public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
+}
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/model/AvroHttpRequest.java b/apache-avro/src/main/java/com/baeldung/avro/util/model/AvroHttpRequest.java
new file mode 100644
index 0000000000..56b36050a5
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/model/AvroHttpRequest.java
@@ -0,0 +1,491 @@
+/**
+ * Autogenerated by Avro
+ *
+ * DO NOT EDIT DIRECTLY
+ */
+package com.baeldung.avro.util.model;
+
+import org.apache.avro.specific.SpecificData;
+import org.apache.avro.message.BinaryMessageEncoder;
+import org.apache.avro.message.BinaryMessageDecoder;
+import org.apache.avro.message.SchemaStore;
+
+@SuppressWarnings("all")
+@org.apache.avro.specific.AvroGenerated
+public class AvroHttpRequest extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
+ private static final long serialVersionUID = -8649010116827875312L;
+ public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"AvroHttpRequest\",\"namespace\":\"com.baeldung.avro.model\",\"fields\":[{\"name\":\"requestTime\",\"type\":\"long\"},{\"name\":\"clientIdentifier\",\"type\":{\"type\":\"record\",\"name\":\"ClientIdentifier\",\"fields\":[{\"name\":\"hostName\",\"type\":\"string\"},{\"name\":\"ipAddress\",\"type\":\"string\"}]}},{\"name\":\"employeeNames\",\"type\":{\"type\":\"array\",\"items\":\"string\"},\"default\":null},{\"name\":\"active\",\"type\":{\"type\":\"enum\",\"name\":\"Active\",\"symbols\":[\"YES\",\"NO\"]}}]}");
+ public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
+
+ private static SpecificData MODEL$ = new SpecificData();
+
+ private static final BinaryMessageEncoder ENCODER =
+ new BinaryMessageEncoder(MODEL$, SCHEMA$);
+
+ private static final BinaryMessageDecoder DECODER =
+ new BinaryMessageDecoder(MODEL$, SCHEMA$);
+
+ /**
+ * Return the BinaryMessageDecoder instance used by this class.
+ */
+ public static BinaryMessageDecoder getDecoder() {
+ return DECODER;
+ }
+
+ /**
+ * Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
+ * @param resolver a {@link SchemaStore} used to find schemas by fingerprint
+ */
+ public static BinaryMessageDecoder createDecoder(SchemaStore resolver) {
+ return new BinaryMessageDecoder(MODEL$, SCHEMA$, resolver);
+ }
+
+ /** Serializes this AvroHttpRequest to a ByteBuffer. */
+ public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
+ return ENCODER.encode(this);
+ }
+
+ /** Deserializes a AvroHttpRequest from a ByteBuffer. */
+ public static AvroHttpRequest fromByteBuffer(
+ java.nio.ByteBuffer b) throws java.io.IOException {
+ return DECODER.decode(b);
+ }
+
+ @Deprecated public long requestTime;
+ @Deprecated public ClientIdentifier clientIdentifier;
+ @Deprecated public java.util.List employeeNames;
+ @Deprecated public Active active;
+
+ /**
+ * Default constructor. Note that this does not initialize fields
+ * to their default values from the schema. If that is desired then
+ * one should use newBuilder().
+ */
+ public AvroHttpRequest() {}
+
+ /**
+ * All-args constructor.
+ * @param requestTime The new value for requestTime
+ * @param clientIdentifier The new value for clientIdentifier
+ * @param employeeNames The new value for employeeNames
+ * @param active The new value for active
+ */
+ public AvroHttpRequest(java.lang.Long requestTime, ClientIdentifier clientIdentifier, java.util.List employeeNames, Active active) {
+ this.requestTime = requestTime;
+ this.clientIdentifier = clientIdentifier;
+ this.employeeNames = employeeNames;
+ this.active = active;
+ }
+
+ public org.apache.avro.Schema getSchema() { return SCHEMA$; }
+ // Used by DatumWriter. Applications should not call.
+ public java.lang.Object get(int field$) {
+ switch (field$) {
+ case 0: return requestTime;
+ case 1: return clientIdentifier;
+ case 2: return employeeNames;
+ case 3: return active;
+ default: throw new org.apache.avro.AvroRuntimeException("Bad index");
+ }
+ }
+
+ // Used by DatumReader. Applications should not call.
+ @SuppressWarnings(value="unchecked")
+ public void put(int field$, java.lang.Object value$) {
+ switch (field$) {
+ case 0: requestTime = (java.lang.Long)value$; break;
+ case 1: clientIdentifier = (ClientIdentifier)value$; break;
+ case 2: employeeNames = (java.util.List)value$; break;
+ case 3: active = (Active)value$; break;
+ default: throw new org.apache.avro.AvroRuntimeException("Bad index");
+ }
+ }
+
+ /**
+ * Gets the value of the 'requestTime' field.
+ * @return The value of the 'requestTime' field.
+ */
+ public java.lang.Long getRequestTime() {
+ return requestTime;
+ }
+
+ /**
+ * Sets the value of the 'requestTime' field.
+ * @param value the value to set.
+ */
+ public void setRequestTime(java.lang.Long value) {
+ this.requestTime = value;
+ }
+
+ /**
+ * Gets the value of the 'clientIdentifier' field.
+ * @return The value of the 'clientIdentifier' field.
+ */
+ public ClientIdentifier getClientIdentifier() {
+ return clientIdentifier;
+ }
+
+ /**
+ * Sets the value of the 'clientIdentifier' field.
+ * @param value the value to set.
+ */
+ public void setClientIdentifier(ClientIdentifier value) {
+ this.clientIdentifier = value;
+ }
+
+ /**
+ * Gets the value of the 'employeeNames' field.
+ * @return The value of the 'employeeNames' field.
+ */
+ public java.util.List getEmployeeNames() {
+ return employeeNames;
+ }
+
+ /**
+ * Sets the value of the 'employeeNames' field.
+ * @param value the value to set.
+ */
+ public void setEmployeeNames(java.util.List value) {
+ this.employeeNames = value;
+ }
+
+ /**
+ * Gets the value of the 'active' field.
+ * @return The value of the 'active' field.
+ */
+ public Active getActive() {
+ return active;
+ }
+
+ /**
+ * Sets the value of the 'active' field.
+ * @param value the value to set.
+ */
+ public void setActive(Active value) {
+ this.active = value;
+ }
+
+ /**
+ * Creates a new AvroHttpRequest RecordBuilder.
+ * @return A new AvroHttpRequest RecordBuilder
+ */
+ public static AvroHttpRequest.Builder newBuilder() {
+ return new AvroHttpRequest.Builder();
+ }
+
+ /**
+ * Creates a new AvroHttpRequest RecordBuilder by copying an existing Builder.
+ * @param other The existing builder to copy.
+ * @return A new AvroHttpRequest RecordBuilder
+ */
+ public static AvroHttpRequest.Builder newBuilder(AvroHttpRequest.Builder other) {
+ return new AvroHttpRequest.Builder(other);
+ }
+
+ /**
+ * Creates a new AvroHttpRequest RecordBuilder by copying an existing AvroHttpRequest instance.
+ * @param other The existing instance to copy.
+ * @return A new AvroHttpRequest RecordBuilder
+ */
+ public static AvroHttpRequest.Builder newBuilder(AvroHttpRequest other) {
+ return new AvroHttpRequest.Builder(other);
+ }
+
+ /**
+ * RecordBuilder for AvroHttpRequest instances.
+ */
+ public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase
+ implements org.apache.avro.data.RecordBuilder {
+
+ private long requestTime;
+ private ClientIdentifier clientIdentifier;
+ private ClientIdentifier.Builder clientIdentifierBuilder;
+ private java.util.List employeeNames;
+ private Active active;
+
+ /** Creates a new Builder */
+ private Builder() {
+ super(SCHEMA$);
+ }
+
+ /**
+ * Creates a Builder by copying an existing Builder.
+ * @param other The existing Builder to copy.
+ */
+ private Builder(AvroHttpRequest.Builder other) {
+ super(other);
+ if (isValidValue(fields()[0], other.requestTime)) {
+ this.requestTime = data().deepCopy(fields()[0].schema(), other.requestTime);
+ fieldSetFlags()[0] = true;
+ }
+ if (isValidValue(fields()[1], other.clientIdentifier)) {
+ this.clientIdentifier = data().deepCopy(fields()[1].schema(), other.clientIdentifier);
+ fieldSetFlags()[1] = true;
+ }
+ if (other.hasClientIdentifierBuilder()) {
+ this.clientIdentifierBuilder = ClientIdentifier.newBuilder(other.getClientIdentifierBuilder());
+ }
+ if (isValidValue(fields()[2], other.employeeNames)) {
+ this.employeeNames = data().deepCopy(fields()[2].schema(), other.employeeNames);
+ fieldSetFlags()[2] = true;
+ }
+ if (isValidValue(fields()[3], other.active)) {
+ this.active = data().deepCopy(fields()[3].schema(), other.active);
+ fieldSetFlags()[3] = true;
+ }
+ }
+
+ /**
+ * Creates a Builder by copying an existing AvroHttpRequest instance
+ * @param other The existing instance to copy.
+ */
+ private Builder(AvroHttpRequest other) {
+ super(SCHEMA$);
+ if (isValidValue(fields()[0], other.requestTime)) {
+ this.requestTime = data().deepCopy(fields()[0].schema(), other.requestTime);
+ fieldSetFlags()[0] = true;
+ }
+ if (isValidValue(fields()[1], other.clientIdentifier)) {
+ this.clientIdentifier = data().deepCopy(fields()[1].schema(), other.clientIdentifier);
+ fieldSetFlags()[1] = true;
+ }
+ this.clientIdentifierBuilder = null;
+ if (isValidValue(fields()[2], other.employeeNames)) {
+ this.employeeNames = data().deepCopy(fields()[2].schema(), other.employeeNames);
+ fieldSetFlags()[2] = true;
+ }
+ if (isValidValue(fields()[3], other.active)) {
+ this.active = data().deepCopy(fields()[3].schema(), other.active);
+ fieldSetFlags()[3] = true;
+ }
+ }
+
+ /**
+ * Gets the value of the 'requestTime' field.
+ * @return The value.
+ */
+ public java.lang.Long getRequestTime() {
+ return requestTime;
+ }
+
+ /**
+ * Sets the value of the 'requestTime' field.
+ * @param value The value of 'requestTime'.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder setRequestTime(long value) {
+ validate(fields()[0], value);
+ this.requestTime = value;
+ fieldSetFlags()[0] = true;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'requestTime' field has been set.
+ * @return True if the 'requestTime' field has been set, false otherwise.
+ */
+ public boolean hasRequestTime() {
+ return fieldSetFlags()[0];
+ }
+
+
+ /**
+ * Clears the value of the 'requestTime' field.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder clearRequestTime() {
+ fieldSetFlags()[0] = false;
+ return this;
+ }
+
+ /**
+ * Gets the value of the 'clientIdentifier' field.
+ * @return The value.
+ */
+ public ClientIdentifier getClientIdentifier() {
+ return clientIdentifier;
+ }
+
+ /**
+ * Sets the value of the 'clientIdentifier' field.
+ * @param value The value of 'clientIdentifier'.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder setClientIdentifier(ClientIdentifier value) {
+ validate(fields()[1], value);
+ this.clientIdentifierBuilder = null;
+ this.clientIdentifier = value;
+ fieldSetFlags()[1] = true;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'clientIdentifier' field has been set.
+ * @return True if the 'clientIdentifier' field has been set, false otherwise.
+ */
+ public boolean hasClientIdentifier() {
+ return fieldSetFlags()[1];
+ }
+
+ /**
+ * Gets the Builder instance for the 'clientIdentifier' field and creates one if it doesn't exist yet.
+ * @return This builder.
+ */
+ public ClientIdentifier.Builder getClientIdentifierBuilder() {
+ if (clientIdentifierBuilder == null) {
+ if (hasClientIdentifier()) {
+ setClientIdentifierBuilder(ClientIdentifier.newBuilder(clientIdentifier));
+ } else {
+ setClientIdentifierBuilder(ClientIdentifier.newBuilder());
+ }
+ }
+ return clientIdentifierBuilder;
+ }
+
+ /**
+ * Sets the Builder instance for the 'clientIdentifier' field
+ * @param value The builder instance that must be set.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder setClientIdentifierBuilder(ClientIdentifier.Builder value) {
+ clearClientIdentifier();
+ clientIdentifierBuilder = value;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'clientIdentifier' field has an active Builder instance
+ * @return True if the 'clientIdentifier' field has an active Builder instance
+ */
+ public boolean hasClientIdentifierBuilder() {
+ return clientIdentifierBuilder != null;
+ }
+
+ /**
+ * Clears the value of the 'clientIdentifier' field.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder clearClientIdentifier() {
+ clientIdentifier = null;
+ clientIdentifierBuilder = null;
+ fieldSetFlags()[1] = false;
+ return this;
+ }
+
+ /**
+ * Gets the value of the 'employeeNames' field.
+ * @return The value.
+ */
+ public java.util.List getEmployeeNames() {
+ return employeeNames;
+ }
+
+ /**
+ * Sets the value of the 'employeeNames' field.
+ * @param value The value of 'employeeNames'.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder setEmployeeNames(java.util.List value) {
+ validate(fields()[2], value);
+ this.employeeNames = value;
+ fieldSetFlags()[2] = true;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'employeeNames' field has been set.
+ * @return True if the 'employeeNames' field has been set, false otherwise.
+ */
+ public boolean hasEmployeeNames() {
+ return fieldSetFlags()[2];
+ }
+
+
+ /**
+ * Clears the value of the 'employeeNames' field.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder clearEmployeeNames() {
+ employeeNames = null;
+ fieldSetFlags()[2] = false;
+ return this;
+ }
+
+ /**
+ * Gets the value of the 'active' field.
+ * @return The value.
+ */
+ public Active getActive() {
+ return active;
+ }
+
+ /**
+ * Sets the value of the 'active' field.
+ * @param value The value of 'active'.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder setActive(Active value) {
+ validate(fields()[3], value);
+ this.active = value;
+ fieldSetFlags()[3] = true;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'active' field has been set.
+ * @return True if the 'active' field has been set, false otherwise.
+ */
+ public boolean hasActive() {
+ return fieldSetFlags()[3];
+ }
+
+
+ /**
+ * Clears the value of the 'active' field.
+ * @return This builder.
+ */
+ public AvroHttpRequest.Builder clearActive() {
+ active = null;
+ fieldSetFlags()[3] = false;
+ return this;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public AvroHttpRequest build() {
+ try {
+ AvroHttpRequest record = new AvroHttpRequest();
+ record.requestTime = fieldSetFlags()[0] ? this.requestTime : (java.lang.Long) defaultValue(fields()[0]);
+ if (clientIdentifierBuilder != null) {
+ record.clientIdentifier = this.clientIdentifierBuilder.build();
+ } else {
+ record.clientIdentifier = fieldSetFlags()[1] ? this.clientIdentifier : (ClientIdentifier) defaultValue(fields()[1]);
+ }
+ record.employeeNames = fieldSetFlags()[2] ? this.employeeNames : (java.util.List) defaultValue(fields()[2]);
+ record.active = fieldSetFlags()[3] ? this.active : (Active) defaultValue(fields()[3]);
+ return record;
+ } catch (java.lang.Exception e) {
+ throw new org.apache.avro.AvroRuntimeException(e);
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static final org.apache.avro.io.DatumWriter
+ WRITER$ = (org.apache.avro.io.DatumWriter)MODEL$.createDatumWriter(SCHEMA$);
+
+ @Override public void writeExternal(java.io.ObjectOutput out)
+ throws java.io.IOException {
+ WRITER$.write(this, SpecificData.getEncoder(out));
+ }
+
+ @SuppressWarnings("unchecked")
+ private static final org.apache.avro.io.DatumReader
+ READER$ = (org.apache.avro.io.DatumReader)MODEL$.createDatumReader(SCHEMA$);
+
+ @Override public void readExternal(java.io.ObjectInput in)
+ throws java.io.IOException {
+ READER$.read(this, SpecificData.getDecoder(in));
+ }
+
+}
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/model/ClientIdentifier.java b/apache-avro/src/main/java/com/baeldung/avro/util/model/ClientIdentifier.java
new file mode 100644
index 0000000000..503dde40df
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/model/ClientIdentifier.java
@@ -0,0 +1,308 @@
+/**
+ * Autogenerated by Avro
+ *
+ * DO NOT EDIT DIRECTLY
+ */
+package com.baeldung.avro.util.model;
+
+import org.apache.avro.specific.SpecificData;
+import org.apache.avro.message.BinaryMessageEncoder;
+import org.apache.avro.message.BinaryMessageDecoder;
+import org.apache.avro.message.SchemaStore;
+
+@SuppressWarnings("all")
+@org.apache.avro.specific.AvroGenerated
+public class ClientIdentifier extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
+ private static final long serialVersionUID = 8754570983127295424L;
+ public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"ClientIdentifier\",\"namespace\":\"com.baeldung.avro.model\",\"fields\":[{\"name\":\"hostName\",\"type\":\"string\"},{\"name\":\"ipAddress\",\"type\":\"string\"}]}");
+ public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; }
+
+ private static SpecificData MODEL$ = new SpecificData();
+
+ private static final BinaryMessageEncoder ENCODER =
+ new BinaryMessageEncoder(MODEL$, SCHEMA$);
+
+ private static final BinaryMessageDecoder DECODER =
+ new BinaryMessageDecoder(MODEL$, SCHEMA$);
+
+ /**
+ * Return the BinaryMessageDecoder instance used by this class.
+ */
+ public static BinaryMessageDecoder getDecoder() {
+ return DECODER;
+ }
+
+ /**
+ * Create a new BinaryMessageDecoder instance for this class that uses the specified {@link SchemaStore}.
+ * @param resolver a {@link SchemaStore} used to find schemas by fingerprint
+ */
+ public static BinaryMessageDecoder createDecoder(SchemaStore resolver) {
+ return new BinaryMessageDecoder(MODEL$, SCHEMA$, resolver);
+ }
+
+ /** Serializes this ClientIdentifier to a ByteBuffer. */
+ public java.nio.ByteBuffer toByteBuffer() throws java.io.IOException {
+ return ENCODER.encode(this);
+ }
+
+ /** Deserializes a ClientIdentifier from a ByteBuffer. */
+ public static ClientIdentifier fromByteBuffer(
+ java.nio.ByteBuffer b) throws java.io.IOException {
+ return DECODER.decode(b);
+ }
+
+ @Deprecated public java.lang.CharSequence hostName;
+ @Deprecated public java.lang.CharSequence ipAddress;
+
+ /**
+ * Default constructor. Note that this does not initialize fields
+ * to their default values from the schema. If that is desired then
+ * one should use newBuilder().
+ */
+ public ClientIdentifier() {}
+
+ /**
+ * All-args constructor.
+ * @param hostName The new value for hostName
+ * @param ipAddress The new value for ipAddress
+ */
+ public ClientIdentifier(java.lang.CharSequence hostName, java.lang.CharSequence ipAddress) {
+ this.hostName = hostName;
+ this.ipAddress = ipAddress;
+ }
+
+ public org.apache.avro.Schema getSchema() { return SCHEMA$; }
+ // Used by DatumWriter. Applications should not call.
+ public java.lang.Object get(int field$) {
+ switch (field$) {
+ case 0: return hostName;
+ case 1: return ipAddress;
+ default: throw new org.apache.avro.AvroRuntimeException("Bad index");
+ }
+ }
+
+ // Used by DatumReader. Applications should not call.
+ @SuppressWarnings(value="unchecked")
+ public void put(int field$, java.lang.Object value$) {
+ switch (field$) {
+ case 0: hostName = (java.lang.CharSequence)value$; break;
+ case 1: ipAddress = (java.lang.CharSequence)value$; break;
+ default: throw new org.apache.avro.AvroRuntimeException("Bad index");
+ }
+ }
+
+ /**
+ * Gets the value of the 'hostName' field.
+ * @return The value of the 'hostName' field.
+ */
+ public java.lang.CharSequence getHostName() {
+ return hostName;
+ }
+
+ /**
+ * Sets the value of the 'hostName' field.
+ * @param value the value to set.
+ */
+ public void setHostName(java.lang.CharSequence value) {
+ this.hostName = value;
+ }
+
+ /**
+ * Gets the value of the 'ipAddress' field.
+ * @return The value of the 'ipAddress' field.
+ */
+ public java.lang.CharSequence getIpAddress() {
+ return ipAddress;
+ }
+
+ /**
+ * Sets the value of the 'ipAddress' field.
+ * @param value the value to set.
+ */
+ public void setIpAddress(java.lang.CharSequence value) {
+ this.ipAddress = value;
+ }
+
+ /**
+ * Creates a new ClientIdentifier RecordBuilder.
+ * @return A new ClientIdentifier RecordBuilder
+ */
+ public static ClientIdentifier.Builder newBuilder() {
+ return new ClientIdentifier.Builder();
+ }
+
+ /**
+ * Creates a new ClientIdentifier RecordBuilder by copying an existing Builder.
+ * @param other The existing builder to copy.
+ * @return A new ClientIdentifier RecordBuilder
+ */
+ public static ClientIdentifier.Builder newBuilder(ClientIdentifier.Builder other) {
+ return new ClientIdentifier.Builder(other);
+ }
+
+ /**
+ * Creates a new ClientIdentifier RecordBuilder by copying an existing ClientIdentifier instance.
+ * @param other The existing instance to copy.
+ * @return A new ClientIdentifier RecordBuilder
+ */
+ public static ClientIdentifier.Builder newBuilder(ClientIdentifier other) {
+ return new ClientIdentifier.Builder(other);
+ }
+
+ /**
+ * RecordBuilder for ClientIdentifier instances.
+ */
+ public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase
+ implements org.apache.avro.data.RecordBuilder {
+
+ private java.lang.CharSequence hostName;
+ private java.lang.CharSequence ipAddress;
+
+ /** Creates a new Builder */
+ private Builder() {
+ super(SCHEMA$);
+ }
+
+ /**
+ * Creates a Builder by copying an existing Builder.
+ * @param other The existing Builder to copy.
+ */
+ private Builder(ClientIdentifier.Builder other) {
+ super(other);
+ if (isValidValue(fields()[0], other.hostName)) {
+ this.hostName = data().deepCopy(fields()[0].schema(), other.hostName);
+ fieldSetFlags()[0] = true;
+ }
+ if (isValidValue(fields()[1], other.ipAddress)) {
+ this.ipAddress = data().deepCopy(fields()[1].schema(), other.ipAddress);
+ fieldSetFlags()[1] = true;
+ }
+ }
+
+ /**
+ * Creates a Builder by copying an existing ClientIdentifier instance
+ * @param other The existing instance to copy.
+ */
+ private Builder(ClientIdentifier other) {
+ super(SCHEMA$);
+ if (isValidValue(fields()[0], other.hostName)) {
+ this.hostName = data().deepCopy(fields()[0].schema(), other.hostName);
+ fieldSetFlags()[0] = true;
+ }
+ if (isValidValue(fields()[1], other.ipAddress)) {
+ this.ipAddress = data().deepCopy(fields()[1].schema(), other.ipAddress);
+ fieldSetFlags()[1] = true;
+ }
+ }
+
+ /**
+ * Gets the value of the 'hostName' field.
+ * @return The value.
+ */
+ public java.lang.CharSequence getHostName() {
+ return hostName;
+ }
+
+ /**
+ * Sets the value of the 'hostName' field.
+ * @param value The value of 'hostName'.
+ * @return This builder.
+ */
+ public ClientIdentifier.Builder setHostName(java.lang.CharSequence value) {
+ validate(fields()[0], value);
+ this.hostName = value;
+ fieldSetFlags()[0] = true;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'hostName' field has been set.
+ * @return True if the 'hostName' field has been set, false otherwise.
+ */
+ public boolean hasHostName() {
+ return fieldSetFlags()[0];
+ }
+
+
+ /**
+ * Clears the value of the 'hostName' field.
+ * @return This builder.
+ */
+ public ClientIdentifier.Builder clearHostName() {
+ hostName = null;
+ fieldSetFlags()[0] = false;
+ return this;
+ }
+
+ /**
+ * Gets the value of the 'ipAddress' field.
+ * @return The value.
+ */
+ public java.lang.CharSequence getIpAddress() {
+ return ipAddress;
+ }
+
+ /**
+ * Sets the value of the 'ipAddress' field.
+ * @param value The value of 'ipAddress'.
+ * @return This builder.
+ */
+ public ClientIdentifier.Builder setIpAddress(java.lang.CharSequence value) {
+ validate(fields()[1], value);
+ this.ipAddress = value;
+ fieldSetFlags()[1] = true;
+ return this;
+ }
+
+ /**
+ * Checks whether the 'ipAddress' field has been set.
+ * @return True if the 'ipAddress' field has been set, false otherwise.
+ */
+ public boolean hasIpAddress() {
+ return fieldSetFlags()[1];
+ }
+
+
+ /**
+ * Clears the value of the 'ipAddress' field.
+ * @return This builder.
+ */
+ public ClientIdentifier.Builder clearIpAddress() {
+ ipAddress = null;
+ fieldSetFlags()[1] = false;
+ return this;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public ClientIdentifier build() {
+ try {
+ ClientIdentifier record = new ClientIdentifier();
+ record.hostName = fieldSetFlags()[0] ? this.hostName : (java.lang.CharSequence) defaultValue(fields()[0]);
+ record.ipAddress = fieldSetFlags()[1] ? this.ipAddress : (java.lang.CharSequence) defaultValue(fields()[1]);
+ return record;
+ } catch (java.lang.Exception e) {
+ throw new org.apache.avro.AvroRuntimeException(e);
+ }
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ private static final org.apache.avro.io.DatumWriter
+ WRITER$ = (org.apache.avro.io.DatumWriter)MODEL$.createDatumWriter(SCHEMA$);
+
+ @Override public void writeExternal(java.io.ObjectOutput out)
+ throws java.io.IOException {
+ WRITER$.write(this, SpecificData.getEncoder(out));
+ }
+
+ @SuppressWarnings("unchecked")
+ private static final org.apache.avro.io.DatumReader
+ READER$ = (org.apache.avro.io.DatumReader)MODEL$.createDatumReader(SCHEMA$);
+
+ @Override public void readExternal(java.io.ObjectInput in)
+ throws java.io.IOException {
+ READER$.read(this, SpecificData.getDecoder(in));
+ }
+
+}
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
new file mode 100644
index 0000000000..7d30c3d1ee
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
@@ -0,0 +1,41 @@
+package com.baeldung.avro.util.serealization;
+
+import com.baeldung.avro.util.model.AvroHttpRequest;
+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 {
+
+ private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
+
+ 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
new file mode 100644
index 0000000000..767b688dea
--- /dev/null
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
@@ -0,0 +1,50 @@
+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 {
+
+ private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class);
+
+ 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;
+ }
+
+ 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/avroHttpRequest-schema.avsc b/apache-avro/src/main/resources/avroHttpRequest-schema.avsc
new file mode 100644
index 0000000000..18179a9cde
--- /dev/null
+++ b/apache-avro/src/main/resources/avroHttpRequest-schema.avsc
@@ -0,0 +1,47 @@
+{
+ "type":"record",
+ "name":"AvroHttpRequest",
+ "namespace":"com.baeldung.avro.model",
+ "fields":[
+ {
+ "name":"requestTime",
+ "type":"long"
+ },
+ {
+ "name":"clientIdentifier",
+ "type":{
+ "type":"record",
+ "name":"ClientIdentifier",
+ "fields":[
+ {
+ "name":"hostName",
+ "type":"string"
+ },
+ {
+ "name":"ipAddress",
+ "type":"string"
+ }
+ ]
+ }
+ },
+ {
+ "name":"employeeNames",
+ "type":{
+ "type":"array",
+ "items":"string"
+ },
+ "default":null
+ },
+ {
+ "name":"active",
+ "type":{
+ "type":"enum",
+ "name":"Active",
+ "symbols":[
+ "YES",
+ "NO"
+ ]
+ }
+ }
+ ]
+}
\ No newline at end of file
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
new file mode 100644
index 0000000000..ecd15ccbbc
--- /dev/null
+++ b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java
@@ -0,0 +1,83 @@
+package com.baeldung.avro.util.serealization;
+
+import com.baeldung.avro.util.model.Active;
+import com.baeldung.avro.util.model.AvroHttpRequest;
+import com.baeldung.avro.util.model.ClientIdentifier;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+
+import static org.junit.Assert.*;
+
+public class AvroSerealizerDeSerealizerTest {
+
+ AvroSerealizer serealizer;
+ AvroDeSerealizer deSerealizer;
+ AvroHttpRequest request;
+
+ @Before
+ public void setUp() throws Exception {
+ serealizer = new AvroSerealizer();
+ deSerealizer = new AvroDeSerealizer();
+
+ ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder()
+ .setHostName("localhost")
+ .setIpAddress("255.255.255.0")
+ .build();
+
+ List employees = new ArrayList();
+ employees.add("James");
+ employees.add("Alice");
+ employees.add("David");
+ employees.add("Han");
+
+ request = AvroHttpRequest.newBuilder()
+ .setRequestTime(01l)
+ .setActive(Active.YES)
+ .setClientIdentifier(clientIdentifier)
+ .setEmployeeNames(employees)
+ .build();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ }
+
+ @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/README.md b/apache-cxf/README.md
index 1e66ce5da8..d03999dce3 100644
--- a/apache-cxf/README.md
+++ b/apache-cxf/README.md
@@ -3,3 +3,4 @@
- [Apache CXF Support for RESTful Web Services](http://www.baeldung.com/apache-cxf-rest-api)
- [A Guide to Apache CXF with Spring](http://www.baeldung.com/apache-cxf-with-spring)
- [Introduction to Apache CXF](http://www.baeldung.com/introduction-to-apache-cxf)
+- [Server-Sent Events (SSE) In JAX-RS](https://www.baeldung.com/java-ee-jax-rs-sse)
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..2e82dc3829
--- /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
+
+
+
+ ${project.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/README.md b/apache-meecrowave/README.md
new file mode 100644
index 0000000000..42b93a383e
--- /dev/null
+++ b/apache-meecrowave/README.md
@@ -0,0 +1,3 @@
+### Relevant Articles:
+================================
+- [Building a Microservice with Apache Meecrowave](http://www.baeldung.com/apache-meecrowave)
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..98d9563284 100644
--- a/apache-shiro/pom.xml
+++ b/apache-shiro/pom.xml
@@ -3,14 +3,14 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.baeldung
apache-shiro
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
@@ -35,13 +35,11 @@
org.slf4j
jcl-over-slf4j
- ${slf4j-version}
runtime
org.slf4j
slf4j-log4j12
- ${slf4j-version}
runtime
@@ -52,26 +50,9 @@
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
- ${java.version}
- ${java.version}
-
-
-
-
-
1.4.0
- 3.7.0
- 1.8
1.2.17
- 1.7.25
\ No newline at end of file
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/README.md b/asciidoctor/README.md
index aafd0bca17..2124907e87 100644
--- a/asciidoctor/README.md
+++ b/asciidoctor/README.md
@@ -1,5 +1,4 @@
### Relevant articles
-- [Introduction to Asciidoctor](http://www.baeldung.com/introduction-to-asciidoctor)
- [Generating a Book with Asciidoctor](http://www.baeldung.com/asciidoctor-book)
- [Introduction to Asciidoctor in Java](http://www.baeldung.com/asciidoctor)
diff --git a/asciidoctor/pom.xml b/asciidoctor/pom.xml
index 15de5ac913..42ee544eb0 100644
--- a/asciidoctor/pom.xml
+++ b/asciidoctor/pom.xml
@@ -61,9 +61,10 @@
- 1.5.5
- 1.5.4
- 1.5.0-alpha.11
+ 1.5.6
+ 1.5.6
+
+ 1.5.0-alpha.15
1.5.0-alpha.15
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/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoTest.java b/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java
similarity index 89%
rename from asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoTest.java
rename to asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java
index 3e312eb059..c4129e6441 100644
--- a/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoTest.java
+++ b/asciidoctor/src/test/java/com/baeldung/asciidoctor/AsciidoctorDemoIntegrationTest.java
@@ -3,7 +3,7 @@ package com.baeldung.asciidoctor;
import org.junit.Assert;
import org.junit.Test;
-public class AsciidoctorDemoTest {
+public class AsciidoctorDemoIntegrationTest {
@Test
public void givenString_whenConverting_thenResultingHTMLCode() {
diff --git a/asm/pom.xml b/asm/pom.xml
index 7bbaa2a8f1..5aad2a0e37 100644
--- a/asm/pom.xml
+++ b/asm/pom.xml
@@ -42,14 +42,6 @@
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${maven-surefire-plugin.version}
-
- -javaagent:"C:\asm-1.0.jar"
-
-
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/pom.xml b/aws-lambda/pom.xml
index 3a2be70da6..c47c3cd86f 100644
--- a/aws-lambda/pom.xml
+++ b/aws-lambda/pom.xml
@@ -95,7 +95,6 @@
2.8.2
1.11.241
3.0.0
- 2.10
\ 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/.gitignore b/aws/.gitignore
index b83d22266a..bf11a4cc38 100644
--- a/aws/.gitignore
+++ b/aws/.gitignore
@@ -1 +1,2 @@
/target/
+.idea/
\ No newline at end of file
diff --git a/aws/pom.xml b/aws/pom.xml
index 176ecaa40d..ab63f6afa1 100644
--- a/aws/pom.xml
+++ b/aws/pom.xml
@@ -100,26 +100,6 @@
-
-
- org.apache.maven.plugins
- maven-dependency-plugin
- ${maven-dependency-plugin.version}
-
-
- copy-dependencies
- test-compile
-
- copy-dependencies
-
-
- test
- so,dll,dylib
- ${project.basedir}/native-libs
-
-
-
-
@@ -137,14 +117,13 @@
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
1.10.L001
0.9.4.0006L
3.0.0
- 2.10
\ No newline at end of file
diff --git a/aws/src/main/java/com/baeldung/rds/AWSRDSService.java b/aws/src/main/java/com/baeldung/rds/AWSRDSService.java
new file mode 100644
index 0000000000..d4da92f30f
--- /dev/null
+++ b/aws/src/main/java/com/baeldung/rds/AWSRDSService.java
@@ -0,0 +1,184 @@
+package com.baeldung.rds;
+
+import com.amazonaws.auth.AWSCredentialsProvider;
+import com.amazonaws.auth.AWSStaticCredentialsProvider;
+import com.amazonaws.auth.BasicAWSCredentials;
+import com.amazonaws.regions.Regions;
+import com.amazonaws.services.rds.AmazonRDS;
+import com.amazonaws.services.rds.AmazonRDSClientBuilder;
+import com.amazonaws.services.rds.model.*;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.*;
+import java.util.List;
+import java.util.Properties;
+import java.util.UUID;
+import java.util.logging.Logger;
+
+public class AWSRDSService {
+
+
+ final static Logger logger = Logger.getLogger(AWSRDSService.class.getName());
+ private AWSCredentialsProvider credentials;
+ private AmazonRDS amazonRDS;
+ private String db_username;
+ private String db_password;
+ private String db_database;
+ private String db_hostname;
+
+ /*
+ * User access key and secret key must be set before execute any operation.
+ * Follow the link on how to get the user access and secret key
+ * https://aws.amazon.com/blogs/security/wheres-my-secret-access-key/
+ * **/
+ public AWSRDSService() throws IOException {
+ //Init RDS client with credentials and region.
+ credentials = new
+ AWSStaticCredentialsProvider(new
+ BasicAWSCredentials("",
+ ""));
+ amazonRDS = AmazonRDSClientBuilder.standard().withCredentials(credentials)
+ .withRegion(Regions.AP_SOUTHEAST_2).build();
+ Properties prop = new Properties();
+ InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
+ prop.load(input);
+ db_username = prop.getProperty("db_username");
+ db_password = prop.getProperty("db_password");
+ db_database = prop.getProperty("db_database");
+ }
+
+ public AWSRDSService(AmazonRDS amazonRDS){
+ this.amazonRDS = amazonRDS;
+ }
+
+ /**
+ * create the RDS instance.
+ * After instance creation, update the db_hostname with endpoint in db.properties.
+ * */
+
+ public String launchInstance() {
+
+ String identifier = "";
+ CreateDBInstanceRequest request = new CreateDBInstanceRequest();
+ // RDS instance name
+ request.setDBInstanceIdentifier("Sydney");
+ request.setEngine("postgres");
+ request.setMultiAZ(false);
+ request.setMasterUsername(db_username);
+ request.setMasterUserPassword(db_password);
+ request.setDBName(db_database);
+ request.setStorageType("gp2");
+ request.setAllocatedStorage(10);
+
+ DBInstance instance = amazonRDS.createDBInstance(request);
+
+ // Information about the new RDS instance
+ identifier = instance.getDBInstanceIdentifier();
+ String status = instance.getDBInstanceStatus();
+ Endpoint endpoint = instance.getEndpoint();
+ String endpoint_url = "Endpoint URL not available yet.";
+ if (endpoint != null) {
+ endpoint_url = endpoint.toString();
+ }
+ logger.info(identifier + "\t" + status);
+ logger.info(endpoint_url);
+
+ return identifier;
+
+ }
+
+ // Describe DB instances
+ public void listInstances() {
+ DescribeDBInstancesResult result = amazonRDS.describeDBInstances();
+ List instances = result.getDBInstances();
+ for (DBInstance instance : instances) {
+ // Information about each RDS instance
+ String identifier = instance.getDBInstanceIdentifier();
+ String engine = instance.getEngine();
+ String status = instance.getDBInstanceStatus();
+ Endpoint endpoint = instance.getEndpoint();
+ String endpoint_url = "Endpoint URL not available yet.";
+ if (endpoint != null) {
+ endpoint_url = endpoint.toString();
+ }
+ logger.info(identifier + "\t" + engine + "\t" + status);
+ logger.info("\t" + endpoint_url);
+ }
+
+ }
+
+ //Delete RDS instance
+ public void terminateInstance(String identifier) {
+
+ DeleteDBInstanceRequest request = new DeleteDBInstanceRequest();
+ request.setDBInstanceIdentifier(identifier);
+ request.setSkipFinalSnapshot(true);
+
+ // Delete the RDS instance
+ DBInstance instance = amazonRDS.deleteDBInstance(request);
+
+ // Information about the RDS instance being deleted
+ String status = instance.getDBInstanceStatus();
+ Endpoint endpoint = instance.getEndpoint();
+ String endpoint_url = "Endpoint URL not available yet.";
+ if (endpoint != null) {
+ endpoint_url = endpoint.toString();
+ }
+
+ logger.info(identifier + "\t" + status);
+ logger.info(endpoint_url);
+
+ }
+
+
+ public void runJdbcTests() throws SQLException, IOException {
+
+ // Getting database properties from db.properties
+ Properties prop = new Properties();
+ InputStream input = AWSRDSService.class.getClassLoader().getResourceAsStream("db.properties");
+ prop.load(input);
+ db_hostname = prop.getProperty("db_hostname");
+ String jdbc_url = "jdbc:postgresql://" + db_hostname + ":5432/" + db_database;
+
+ // Create a connection using the JDBC driver
+ try (Connection conn = DriverManager.getConnection(jdbc_url, db_username, db_password)) {
+
+ // Create the test table if not exists
+ Statement statement = conn.createStatement();
+ String sql = "CREATE TABLE IF NOT EXISTS jdbc_test (id SERIAL PRIMARY KEY, content VARCHAR(80))";
+ statement.executeUpdate(sql);
+
+ // Do some INSERT
+ PreparedStatement preparedStatement = conn.prepareStatement("INSERT INTO jdbc_test (content) VALUES (?)");
+ String content = "" + UUID.randomUUID();
+ preparedStatement.setString(1, content);
+ preparedStatement.executeUpdate();
+ logger.info("INSERT: " + content);
+
+ // Do some SELECT
+ sql = "SELECT * FROM jdbc_test";
+ ResultSet resultSet = statement.executeQuery(sql);
+ while (resultSet.next()) {
+ String count = resultSet.getString("content");
+ logger.info("Total Records: " + count);
+ }
+ }
+
+
+ }
+
+ public static void main(String[] args) throws IOException, SQLException {
+ AWSRDSService awsrdsService = new AWSRDSService();
+
+ String instanceName = awsrdsService.launchInstance();
+
+ //Add some wait for instance creation.
+
+ awsrdsService.listInstances();
+
+ awsrdsService.runJdbcTests();
+
+ awsrdsService.terminateInstance(instanceName);
+ }
+}
diff --git a/aws/src/main/resources/db.properties b/aws/src/main/resources/db.properties
new file mode 100644
index 0000000000..e934611a2b
--- /dev/null
+++ b/aws/src/main/resources/db.properties
@@ -0,0 +1,4 @@
+db_hostname=
+db_username=username
+db_password=password
+db_database=mydb
\ No newline at end of file
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..2291da9084 100644
--- a/cas/cas-secured-app/pom.xml
+++ b/cas/cas-secured-app/pom.xml
@@ -2,18 +2,16 @@
4.0.0
- com.baeldung
cas-secured-app
- 0.0.1-SNAPSHOT
jar
cas-secured-app
- Demo project for Spring Boot
+ Demo project for CAS
- org.springframework.boot
- spring-boot-starter-parent
- 1.5.13.RELEASE
-
+ parent-boot-1
+ com.baeldung
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-1
@@ -60,10 +58,4 @@
-
- UTF-8
- UTF-8
- 1.8
-
-
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/cas/cas-server/pom.xml b/cas/cas-server/pom.xml
index a15b4b58d5..9b61aaec3d 100644
--- a/cas/cas-server/pom.xml
+++ b/cas/cas-server/pom.xml
@@ -2,11 +2,17 @@
4.0.0
- com.baeldung
cas-server
war
1.0
+
+ parent-boot-1
+ com.baeldung
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-1
+
+
org.apereo.cas
@@ -39,7 +45,6 @@
org.springframework.boot
spring-boot-maven-plugin
- ${springboot.version}
${mainClassName}
true
@@ -74,42 +79,10 @@
-
- org.apache.maven.plugins
- maven-compiler-plugin
- ${maven-compiler-plugin.version}
-
cas
-
-
- sonatype-releases
- http://oss.sonatype.org/content/repositories/releases/
-
- false
-
-
- true
-
-
-
- sonatype-snapshots
- https://oss.sonatype.org/content/repositories/snapshots/
-
- true
-
-
- false
-
-
-
- shibboleth-releases
- https://build.shibboleth.net/nexus/content/repositories/releases
-
-
-
@@ -214,8 +187,7 @@
- 5.3.0-SNAPSHOT
- 1.5.13.RELEASE
+ 5.3.3
-tomcat
@@ -223,14 +195,12 @@
false
${project.build.directory}/war/work/org.apereo.cas/cas-server-webapp${app.server}/META-INF/MANIFEST.MF
- 1.8
- 1.8
- UTF-8
0.0.4
2.6
3.3
+
0.3.0
1.1.0
-
\ No newline at end of file
+
diff --git a/cdi-portable-extension/flyway-cdi/pom.xml b/cdi-portable-extension/flyway-cdi/pom.xml
new file mode 100644
index 0000000000..9fb781aaab
--- /dev/null
+++ b/cdi-portable-extension/flyway-cdi/pom.xml
@@ -0,0 +1,38 @@
+
+
+ 4.0.0
+
+ flyway-cdi
+
+
+ com.baeldung
+ cdi-portable-extension
+ 1.0-SNAPSHOT
+
+
+
+
+ javax.enterprise
+ cdi-api
+ 2.0.SP1
+
+
+ org.flywaydb
+ flyway-core
+ 5.1.4
+
+
+ org.apache.tomcat
+ tomcat-jdbc
+ 8.5.33
+
+
+ javax.annotation
+ javax.annotation-api
+ 1.3.2
+
+
+
+
diff --git a/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java b/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java
new file mode 100644
index 0000000000..a5019b82c1
--- /dev/null
+++ b/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayExtension.java
@@ -0,0 +1,74 @@
+package com.baeldung.cdi.extension;
+
+import org.apache.tomcat.jdbc.pool.DataSource;
+import org.flywaydb.core.Flyway;
+
+import javax.annotation.sql.DataSourceDefinition;
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.event.Observes;
+import javax.enterprise.inject.Any;
+import javax.enterprise.inject.Default;
+import javax.enterprise.inject.literal.InjectLiteral;
+import javax.enterprise.inject.spi.*;
+import javax.enterprise.util.AnnotationLiteral;
+
+
+/**
+ * Flyway is now under CDI container like:
+ *
+ * @ApplicationScoped
+ * @FlywayType public class Flyway{
+ * @Inject setDataSource(DataSource dataSource){
+ * //...
+ * }
+ * }
+ */
+
+public class FlywayExtension implements Extension {
+
+ DataSourceDefinition dataSourceDefinition = null;
+
+ public void registerFlywayType(@Observes BeforeBeanDiscovery bbdEvent) {
+ bbdEvent.addAnnotatedType(Flyway.class, Flyway.class.getName());
+ }
+
+ public void detectDataSourceDefinition(@Observes @WithAnnotations(DataSourceDefinition.class) ProcessAnnotatedType> patEvent) {
+ AnnotatedType at = patEvent.getAnnotatedType();
+ dataSourceDefinition = at.getAnnotation(DataSourceDefinition.class);
+ }
+
+ public void processAnnotatedType(@Observes ProcessAnnotatedType patEvent) {
+ patEvent.configureAnnotatedType()
+ //Add Scope
+ .add(ApplicationScoped.Literal.INSTANCE)
+ //Add Qualifier
+ .add(new AnnotationLiteral() {
+ })
+ //Decorate setDataSource(DataSource dataSource){} with @Inject
+ .filterMethods(annotatedMethod -> {
+ return annotatedMethod.getParameters().size() == 1 &&
+ annotatedMethod.getParameters().get(0).getBaseType().equals(javax.sql.DataSource.class);
+ })
+ .findFirst().get().add(InjectLiteral.INSTANCE);
+ }
+
+ void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) {
+ abdEvent.addBean()
+ .types(javax.sql.DataSource.class, DataSource.class)
+ .qualifiers(new AnnotationLiteral() {}, new AnnotationLiteral() {})
+ .scope(ApplicationScoped.class)
+ .name(DataSource.class.getName())
+ .beanClass(DataSource.class)
+ .createWith(creationalContext -> {
+ DataSource instance = new DataSource();
+ instance.setUrl(dataSourceDefinition.url());
+ instance.setDriverClassName(dataSourceDefinition.className());
+ return instance;
+ });
+ }
+
+ void runFlywayMigration(@Observes AfterDeploymentValidation adv, BeanManager manager) {
+ Flyway flyway = manager.createInstance().select(Flyway.class, new AnnotationLiteral() {}).get();
+ flyway.migrate();
+ }
+}
diff --git a/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayType.java b/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayType.java
new file mode 100644
index 0000000000..7c3a5affa6
--- /dev/null
+++ b/cdi-portable-extension/flyway-cdi/src/main/java/com/baeldung/cdi/extension/FlywayType.java
@@ -0,0 +1,14 @@
+package com.baeldung.cdi.extension;
+
+import javax.inject.Qualifier;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.*;
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target({FIELD, METHOD, PARAMETER, TYPE})
+@Qualifier
+public @interface FlywayType {
+}
\ No newline at end of file
diff --git a/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/beans.xml b/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/beans.xml
new file mode 100644
index 0000000000..44959bfa99
--- /dev/null
+++ b/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/beans.xml
@@ -0,0 +1,6 @@
+
+
\ No newline at end of file
diff --git a/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension b/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension
new file mode 100644
index 0000000000..a82dc47714
--- /dev/null
+++ b/cdi-portable-extension/flyway-cdi/src/main/resources/META-INF/services/javax.enterprise.inject.spi.Extension
@@ -0,0 +1,2 @@
+com.baeldung.cdi.extension.FlywayExtension
+
diff --git a/cdi-portable-extension/main-app/pom.xml b/cdi-portable-extension/main-app/pom.xml
new file mode 100644
index 0000000000..fab9b8bf07
--- /dev/null
+++ b/cdi-portable-extension/main-app/pom.xml
@@ -0,0 +1,52 @@
+
+
+ 4.0.0
+
+ main-app
+ jar
+
+
+ com.baeldung
+ cdi-portable-extension
+ 1.0-SNAPSHOT
+
+
+
+
+
+ javax.enterprise
+ cdi-api
+ 2.0.SP1
+
+
+ org.jboss.weld.se
+ weld-se-core
+ 3.0.5.Final
+ runtime
+
+
+
+ com.baeldung
+ flyway-cdi
+ 1.0-SNAPSHOT
+ runtime
+
+
+
+ com.h2database
+ h2
+ 1.4.197
+ runtime
+
+
+
+ javax.annotation
+ javax.annotation-api
+ 1.3.2
+
+
+
+
+
\ No newline at end of file
diff --git a/cdi-portable-extension/main-app/src/main/java/com/baeldung/cdi/extension/MainApp.java b/cdi-portable-extension/main-app/src/main/java/com/baeldung/cdi/extension/MainApp.java
new file mode 100644
index 0000000000..1f6c5b43ba
--- /dev/null
+++ b/cdi-portable-extension/main-app/src/main/java/com/baeldung/cdi/extension/MainApp.java
@@ -0,0 +1,16 @@
+package com.baeldung.cdi.extension;
+
+import javax.annotation.sql.DataSourceDefinition;
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.inject.se.SeContainer;
+import javax.enterprise.inject.se.SeContainerInitializer;
+
+@ApplicationScoped
+@DataSourceDefinition(name = "ds", className = "org.h2.Driver", url = "jdbc:h2:mem:testdb")
+public class MainApp {
+ public static void main(String[] args) {
+ SeContainerInitializer initializer = SeContainerInitializer.newInstance();
+ try (SeContainer container = initializer.initialize()) {
+ }
+ }
+}
\ No newline at end of file
diff --git a/cdi-portable-extension/main-app/src/main/resources/META-INF/beans.xml b/cdi-portable-extension/main-app/src/main/resources/META-INF/beans.xml
new file mode 100644
index 0000000000..44959bfa99
--- /dev/null
+++ b/cdi-portable-extension/main-app/src/main/resources/META-INF/beans.xml
@@ -0,0 +1,6 @@
+
+
\ No newline at end of file
diff --git a/cdi-portable-extension/main-app/src/main/resources/db/migration/V1__Create_person_table.sql b/cdi-portable-extension/main-app/src/main/resources/db/migration/V1__Create_person_table.sql
new file mode 100644
index 0000000000..6bddc7689e
--- /dev/null
+++ b/cdi-portable-extension/main-app/src/main/resources/db/migration/V1__Create_person_table.sql
@@ -0,0 +1,4 @@
+create table PERSON (
+ ID int not null,
+ NAME varchar(100) not null
+);
diff --git a/cdi-portable-extension/main-app/src/main/resources/db/migration/V2__Add_people.sql b/cdi-portable-extension/main-app/src/main/resources/db/migration/V2__Add_people.sql
new file mode 100644
index 0000000000..d8f1d62667
--- /dev/null
+++ b/cdi-portable-extension/main-app/src/main/resources/db/migration/V2__Add_people.sql
@@ -0,0 +1,3 @@
+insert into PERSON (ID, NAME) values (1, 'Axel');
+insert into PERSON (ID, NAME) values (2, 'Mr. Foo');
+insert into PERSON (ID, NAME) values (3, 'Ms. Bar');
diff --git a/cdi-portable-extension/pom.xml b/cdi-portable-extension/pom.xml
new file mode 100644
index 0000000000..66913de84d
--- /dev/null
+++ b/cdi-portable-extension/pom.xml
@@ -0,0 +1,30 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ cdi-portable-extension
+ 1.0-SNAPSHOT
+ pom
+
+
+ 1.8
+ 1.8
+
+
+
+ main-app
+ flyway-cdi
+
+
+
+
+ javax.enterprise
+ cdi-api
+ 2.0.SP1
+
+
+
+
\ 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/pom.xml b/checker-plugin/pom.xml
index 7538340f69..45f0939e77 100644
--- a/checker-plugin/pom.xml
+++ b/checker-plugin/pom.xml
@@ -41,27 +41,6 @@
-
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
-
-
- properties
-
-
-
-
-
maven-compiler-plugin
${maven-compiler-plugin.version}
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 dcf7b24ef8..64d423aafe 100644
--- a/core-java-8/README.md
+++ b/core-java-8/README.md
@@ -9,49 +9,26 @@
- [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)
-- [Filtering Kotlin Collections](http://www.baeldung.com/kotlin-filter-collection)
-- [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)
+- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)
+- [Set the Time Zone of a Date in Java](https://www.baeldung.com/java-set-date-time-zone)
+- [An Overview of Regular Expressions Performance in Java](https://www.baeldung.com/java-regex-performance)
+- [Java Primitives versus Objects](https://www.baeldung.com/java-primitives-vs-objects)
diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml
index dee0634951..18bdaa15f4 100644
--- a/core-java-8/pom.xml
+++ b/core-java-8/pom.xml
@@ -89,16 +89,21 @@
vavr
${vavr.version}
-
- one.util
- streamex
- ${streamex.version}
-
joda-time
joda-time
${joda.version}
+
+ org.aspectj
+ aspectjrt
+ ${asspectj.version}
+
+
+ org.aspectj
+ aspectjweaver
+ ${asspectj.version}
+
@@ -111,23 +116,6 @@
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
- copy-dependencies
- prepare-package
-
- copy-dependencies
-
-
- ${project.build.directory}/libs
-
-
-
-
-
org.apache.maven.plugins
maven-compiler-plugin
@@ -141,6 +129,7 @@
org.springframework.boot
spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
@@ -166,13 +155,13 @@
1.16.12
0.9.0
1.13
- 0.6.5
2.10
3.6.1
+ 1.8.9
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/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj b/core-java-8/src/main/java/com/baeldung/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj
new file mode 100644
index 0000000000..b28bebfdaf
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/aspect/ChangeCallsToCurrentTimeInMillisMethod.aj
@@ -0,0 +1,9 @@
+package com.baeldung.aspect;
+
+public aspect ChangeCallsToCurrentTimeInMillisMethod {
+ long around():
+ call(public static native long java.lang.System.currentTimeMillis())
+ && within(user.code.base.pckg.*) {
+ return 0;
+ }
+}
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/list/AddElementsUnitTest.java b/core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java
new file mode 100644
index 0000000000..93c28812bd
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/list/AddElementsUnitTest.java
@@ -0,0 +1,87 @@
+package com.baeldung.list;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.*;
+
+import static org.junit.Assert.*;
+
+public class AddElementsUnitTest {
+
+ 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-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 3ad3deb548..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
@@ -39,5 +39,4 @@ public class CurrentDateTimeUnitTest {
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
}
-
}
diff --git a/core-java-9/README.md b/core-java-9/README.md
index a76dcefc69..bf07cfcc86 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,6 @@
- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)
+- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
+- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
+- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
diff --git a/core-java-9/logging.sh b/core-java-9/logging.sh
new file mode 100755
index 0000000000..c9b502f300
--- /dev/null
+++ b/core-java-9/logging.sh
@@ -0,0 +1,15 @@
+# compile logging module
+# javac --module-path mods -d mods/com.baeldung.logging src/modules/com.baeldung.logging/module-info.java src/modules/com.baeldung.logging/com/baeldung/logging/*.java
+
+# compile logging slf4j module
+javac --module-path mods -d mods/com.baeldung.logging.slf4j src/modules/com.baeldung.logging.slf4j/module-info.java src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/*.java
+
+
+# compile logging main app module
+javac --module-path mods -d mods/com.baeldung.logging.app src/modules/com.baeldung.logging.app/module-info.java src/modules/com.baeldung.logging.app/com/baeldung/logging/app/*.java
+
+# run logging main app
+# java --module-path mods -m com.baeldung.logging.app/com.baeldung.logging.app.MainApp
+
+# run looging main app using logback
+java --module-path mods -Dlogback.configurationFile=mods/logback.xml -m com.baeldung.logging.app/com.baeldung.logging.app.MainApp
diff --git a/core-java-9/mods/logback.xml b/core-java-9/mods/logback.xml
new file mode 100644
index 0000000000..c22c7a7130
--- /dev/null
+++ b/core-java-9/mods/logback.xml
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+ %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} -- %msg%n
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-9/pom.xml b/core-java-9/pom.xml
index 4ba06f7c0d..f22d0a3ed9 100644
--- a/core-java-9/pom.xml
+++ b/core-java-9/pom.xml
@@ -19,11 +19,23 @@
${awaitility.version}
test
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
com.google.guava
guava
${guava.version}
+
+ org.junit.platform
+ junit-platform-runner
+ ${junit.platform.version}
+ test
+
@@ -50,6 +62,8 @@
+ 3.10.0
+ 1.2.0
1.7.0
1.9
1.9
diff --git a/core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java b/core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java
new file mode 100644
index 0000000000..84d2e63c6c
--- /dev/null
+++ b/core-java-9/src/main/java/com/baeldung/java9/language/stream/StreamsGroupingCollectionFilter.java
@@ -0,0 +1,27 @@
+package com.baeldung.java9.language.stream;
+
+import static java.util.stream.Collectors.filtering;
+import static java.util.stream.Collectors.groupingBy;
+import static java.util.stream.Collectors.toList;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+
+public class StreamsGroupingCollectionFilter {
+
+ static public Map> findEvenNumbersAfterGroupingByQuantityOfDigits(Collection baseCollection) {
+ Function getQuantityOfDigits = item -> (int) Math.log10(item) + 1;
+
+ return baseCollection.stream()
+ .collect(groupingBy(getQuantityOfDigits, filtering(item -> item % 2 == 0, toList())));
+ }
+
+ static public Map> findEvenNumbersBeforeGroupingByQuantityOfDigits(Collection baseCollection) {
+
+ return baseCollection.stream()
+ .filter(item -> item % 2 == 0)
+ .collect(groupingBy(item -> (int) Math.log10(item) + 1, toList()));
+ }
+}
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/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java b/core-java-9/src/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java
new file mode 100644
index 0000000000..01f53d59e9
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.logging.app/com/baeldung/logging/app/MainApp.java
@@ -0,0 +1,13 @@
+package com.baeldung.logging.app;
+
+import static java.lang.System.Logger.*;
+
+public class MainApp {
+
+ private static System.Logger LOGGER = System.getLogger("MainApp");
+
+ public static void main(String[] args) {
+ LOGGER.log(Level.ERROR, "error test");
+ LOGGER.log(Level.INFO, "info test");
+ }
+}
diff --git a/core-java-9/src/modules/com.baeldung.logging.app/module-info.java b/core-java-9/src/modules/com.baeldung.logging.app/module-info.java
new file mode 100644
index 0000000000..037c72b755
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.logging.app/module-info.java
@@ -0,0 +1,2 @@
+module com.baeldung.logging.app {
+}
\ No newline at end of file
diff --git a/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java b/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java
new file mode 100644
index 0000000000..df41e071fd
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLogger.java
@@ -0,0 +1,99 @@
+package com.baeldung.logging.slf4j;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ResourceBundle;
+
+public class Slf4jLogger implements System.Logger {
+
+ private final String name;
+ private final Logger logger;
+
+ public Slf4jLogger(String name) {
+ this.name = name;
+ logger = LoggerFactory.getLogger(name);
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public boolean isLoggable(Level level) {
+ switch (level) {
+ case OFF:
+ return false;
+ case TRACE:
+ return logger.isTraceEnabled();
+ case DEBUG:
+ return logger.isDebugEnabled();
+ case INFO:
+ return logger.isInfoEnabled();
+ case WARNING:
+ return logger.isWarnEnabled();
+ case ERROR:
+ return logger.isErrorEnabled();
+ case ALL:
+ default:
+ return true;
+ }
+ }
+
+ @Override
+ public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) {
+ if (!isLoggable(level)) {
+ return;
+ }
+
+ switch (level) {
+ case TRACE:
+ logger.trace(msg, thrown);
+ break;
+ case DEBUG:
+ logger.debug(msg, thrown);
+ break;
+ case INFO:
+ logger.info(msg, thrown);
+ break;
+ case WARNING:
+ logger.warn(msg, thrown);
+ break;
+ case ERROR:
+ logger.error(msg, thrown);
+ break;
+ case ALL:
+ default:
+ logger.info(msg, thrown);
+ }
+ }
+
+ @Override
+ public void log(Level level, ResourceBundle bundle, String format, Object... params) {
+ if (!isLoggable(level)) {
+ return;
+ }
+
+ switch (level) {
+ case TRACE:
+ logger.trace(format, params);
+ break;
+ case DEBUG:
+ logger.debug(format, params);
+ break;
+ case INFO:
+ logger.info(format, params);
+ break;
+ case WARNING:
+ logger.warn(format, params);
+ break;
+ case ERROR:
+ logger.error(format, params);
+ break;
+ case ALL:
+ default:
+ logger.info(format, params);
+ }
+ }
+}
diff --git a/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java b/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java
new file mode 100644
index 0000000000..97f7cccb92
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.logging.slf4j/com/baeldung/logging/slf4j/Slf4jLoggerFinder.java
@@ -0,0 +1,8 @@
+package com.baeldung.logging.slf4j;
+
+public class Slf4jLoggerFinder extends System.LoggerFinder {
+ @Override
+ public System.Logger getLogger(String name, Module module) {
+ return new Slf4jLogger(name);
+ }
+}
diff --git a/core-java-9/src/modules/com.baeldung.logging.slf4j/module-info.java b/core-java-9/src/modules/com.baeldung.logging.slf4j/module-info.java
new file mode 100644
index 0000000000..311ca22f5b
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.logging.slf4j/module-info.java
@@ -0,0 +1,6 @@
+module com.baeldung.logging.slf4j {
+ requires org.slf4j;
+ provides java.lang.System.LoggerFinder
+ with com.baeldung.logging.slf4j.Slf4jLoggerFinder;
+ exports com.baeldung.logging.slf4j;
+}
\ No newline at end of file
diff --git a/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java b/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java
new file mode 100644
index 0000000000..a495e6979d
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/ConsoleLogger.java
@@ -0,0 +1,27 @@
+package com.baeldung.logging;
+
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+
+public class ConsoleLogger implements System.Logger {
+
+ @Override
+ public String getName() {
+ return "ConsoleLogger";
+ }
+
+ @Override
+ public boolean isLoggable(Level level) {
+ return true;
+ }
+
+ @Override
+ public void log(Level level, ResourceBundle bundle, String msg, Throwable thrown) {
+ System.out.printf("ConsoleLogger [%s]: %s - %s%n", level, msg, thrown);
+ }
+
+ @Override
+ public void log(Level level, ResourceBundle bundle, String format, Object... params) {
+ System.out.printf("ConsoleLogger [%s]: %s%n", level, MessageFormat.format(format, params));
+ }
+}
diff --git a/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java b/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java
new file mode 100644
index 0000000000..b38955f199
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.logging/com/baeldung/logging/CustomLoggerFinder.java
@@ -0,0 +1,9 @@
+package com.baeldung.logging;
+
+public class CustomLoggerFinder extends System.LoggerFinder {
+
+ @Override
+ public System.Logger getLogger(String name, Module module) {
+ return new ConsoleLogger();
+ }
+}
diff --git a/core-java-9/src/modules/com.baeldung.logging/module-info.java b/core-java-9/src/modules/com.baeldung.logging/module-info.java
new file mode 100644
index 0000000000..4ca0af0225
--- /dev/null
+++ b/core-java-9/src/modules/com.baeldung.logging/module-info.java
@@ -0,0 +1,5 @@
+module com.baeldung.logging {
+ provides java.lang.System.LoggerFinder
+ with com.baeldung.logging.CustomLoggerFinder;
+ exports com.baeldung.logging;
+}
\ No newline at end of file
diff --git a/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java
new file mode 100644
index 0000000000..1b9315678a
--- /dev/null
+++ b/core-java-9/src/test/java/com/baeldung/java9/language/stream/CollectionFilterUnitTest.java
@@ -0,0 +1,51 @@
+package com.baeldung.java9.language.stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.junit.jupiter.api.Test;
+import org.junit.platform.runner.JUnitPlatform;
+import org.junit.runner.RunWith;
+
+@RunWith(JUnitPlatform.class)
+public class CollectionFilterUnitTest {
+
+ private static final Collection BASE_INTEGER_COLLECTION = Arrays.asList(9, 12, 55, 56, 101, 115, 8002, 223, 2668, 19, 8);
+ private static final Map> EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP = createExpectedFilterAfterGroupingMap();
+ private static Map> createExpectedFilterAfterGroupingMap() {
+ Map> map = new HashMap<>();
+ map.put(1, Arrays.asList(8));
+ map.put(2, Arrays.asList(12, 56));
+ map.put(3, Collections.emptyList());
+ map.put(4, Arrays.asList(8002, 2668));
+ return map;
+
+ }
+
+ private static final Map> EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP = createExpectedFilterBeforeGroupingMap();
+ private static Map> createExpectedFilterBeforeGroupingMap() {
+ Map> map = new HashMap<>();
+ map.put(1, Arrays.asList(8));
+ map.put(2, Arrays.asList(12, 56));
+ map.put(4, Arrays.asList(8002, 2668));
+ return map;
+
+ }
+
+ @Test
+ public void givenAStringCollection_whenFilteringFourLetterWords_thenObtainTheFilteredCollection() {
+ Map> filteredAfterGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersAfterGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION);
+ Map> filteredBeforeGroupingMap = StreamsGroupingCollectionFilter.findEvenNumbersBeforeGroupingByQuantityOfDigits(BASE_INTEGER_COLLECTION);
+
+ assertThat(filteredAfterGroupingMap).containsAllEntriesOf(EXPECTED_EVEN_FILTERED_AFTER_GROUPING_MAP);
+ assertThat(filteredBeforeGroupingMap).doesNotContainKey(3)
+ .containsAllEntriesOf(EXPECTED_EVEN_FILTERED_BEFORE_GROUPING_MAP);
+ }
+
+}
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..2c5525b9ed
--- /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_whenStarted_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_whenDestroyed_thenCheckIfAlive() 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 510eac9dbc..ca275d7c09 100644
--- a/core-java-collections/README.md
+++ b/core-java-collections/README.md
@@ -30,3 +30,24 @@
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
- [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)
+- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
+- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
+- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
+- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
+- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
+- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
+- [Get the Key for a Value from a Java Map](https://www.baeldung.com/java-map-key-from-value)
+- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml
index a5aea49c14..d0c3c25beb 100644
--- a/core-java-collections/pom.xml
+++ b/core-java-collections/pom.xml
@@ -36,19 +36,50 @@
commons-lang3
${commons-lang3.version}
+
+ org.eclipse.collections
+ eclipse-collections
+ ${eclipse.collections.version}
+
org.assertj
assertj-core
${assertj.version}
test
+
+ org.junit.platform
+ junit-platform-runner
+ ${junit.platform.version}
+ test
+
+
+ org.openjdk.jmh
+ jmh-core
+ ${openjdk.jmh.version}
+
+
+ org.openjdk.jmh
+ jmh-generator-annprocess
+ ${openjdk.jmh.version}
+
+
+ org.apache.commons
+ commons-exec
+ 1.3
+
+
+
+ 1.19
+ 1.2.0
3.5
4.1
4.01
1.7.0
3.6.1
+ 7.1.0
diff --git a/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningArrays.java b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningArrays.java
new file mode 100644
index 0000000000..2ad48033c0
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningArrays.java
@@ -0,0 +1,39 @@
+package com.baeldung.combiningcollections;
+
+import java.util.Arrays;
+import java.util.stream.Stream;
+
+import org.apache.commons.lang3.ArrayUtils;
+
+import com.google.common.collect.ObjectArrays;
+
+public class CombiningArrays {
+
+ public static Object[] usingNativeJava(Object[] first, Object[] second) {
+ Object[] combined = new Object[first.length + second.length];
+ System.arraycopy(first, 0, combined, 0, first.length);
+ System.arraycopy(second, 0, combined, first.length, second.length);
+ return combined;
+ }
+
+ public static Object[] usingJava8ObjectStream(Object[] first, Object[] second) {
+ Object[] combined = Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray();
+ return combined;
+ }
+
+ public static Object[] usingJava8FlatMaps(Object[] first, Object[] second) {
+ Object[] combined = Stream.of(first, second).flatMap(Stream::of).toArray(String[]::new);
+ return combined;
+ }
+
+ public static Object[] usingApacheCommons(Object[] first, Object[] second) {
+ Object[] combined = ArrayUtils.addAll(first, second);
+ return combined;
+ }
+
+ public static Object[] usingGuava(Object[] first, Object[] second) {
+ Object [] combined = ObjectArrays.concat(first, second, Object.class);
+ return combined;
+ }
+
+}
diff --git a/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningLists.java b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningLists.java
new file mode 100644
index 0000000000..3fdf672758
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/combiningcollections/CombiningLists.java
@@ -0,0 +1,46 @@
+package com.baeldung.combiningcollections;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.apache.commons.collections4.ListUtils;
+
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
+public class CombiningLists {
+
+ public static List