diff --git a/.gitignore b/.gitignore
index a0a519c8cb..7fe2778755 100644
--- a/.gitignore
+++ b/.gitignore
@@ -56,4 +56,11 @@ core-java-io/hard_link.txt
core-java-io/target_link.txt
core-java/src/main/java/com/baeldung/manifest/MANIFEST.MF
ethereum/logs/
-jmeter/src/main/resources/*-JMeter.csv
\ No newline at end of file
+jmeter/src/main/resources/*-JMeter.csv
+
+**/node_modules/
+**/dist
+**/tmp
+**/out-tsc
+**/nbproject/
+**/nb-configuration.xml
\ No newline at end of file
diff --git a/JGit/pom.xml b/JGit/pom.xml
index d1ebd364da..176d55d321 100644
--- a/JGit/pom.xml
+++ b/JGit/pom.xml
@@ -3,10 +3,11 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.baeldung
- JGitSnippets
+ JGit
1.0-SNAPSHOT
jar
http://maven.apache.org
+ JGit
com.baeldung
diff --git a/JGit/src/main/resources/logback.xml b/JGit/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/JGit/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/README.md b/README.md
index d018783465..8e0a5eb9ee 100644
--- a/README.md
+++ b/README.md
@@ -2,41 +2,27 @@
The "REST with Spring" Classes
==============================
-After 5 months of work, here's the Master Class of REST With Spring:
-**[>> 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)**
+Here's the Master Class of REST With Spring (along with the newly announced Boot 2 material):
+**[>> 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:
-**[>> LEARN SPRING SECURITY MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
+**[>> LEARN SPRING SECURITY - MASTER CLASS](http://www.baeldung.com/learn-spring-security-course?utm_source=github&utm_medium=social&utm_content=tutorials&utm_campaign=lss#master-class)**
-Spring Tutorials
+Java and Spring Tutorials
================
-This project is **a collection of small and focused tutorials** each covering a single and well defined area of development.
-Most of the tutorial projects are focused on the `Spring Framework` (and `Spring Security`).
+This project is **a collection of small and focused tutorials** - each covering a single and well defined area of development in the Java ecosystem.
+A strong focus of these is, of course, the Spring Framework - Spring, Spring Boot and Spring Securiyt.
In additional to Spring, the following technologies are in focus: `core Java`, `Jackson`, `HttpClient`, `Guava`.
+
Building the project
====================
To do the full build, do: `mvn install -Pdefault -Dgib.enabled=false`
-Working with the code in Eclipse
-================================
-Any IDE can be used to work with the projects, but if you're using Eclipse, consider the following.
-
-- import the included **formatter** in Eclipse:
-`https://github.com/eugenp/tutorials/tree/master/eclipse`
-
-
-CI - Jenkins
-================================
-This tutorials project is being built **[>> HERE](https://rest-security.ci.cloudbees.com/job/tutorials-unit/)**
-
-### Relevant Articles:
-================================
-
-- [Apache Maven Standard Directory Layout](http://www.baeldung.com/maven-directory-structure)
-- [Apache Maven Tutorial](http://www.baeldung.com/maven)
-- [Designing a User Friendly Java Library](http://www.baeldung.com/design-a-user-friendly-java-library)
+Building a single module
+====================
+To build a specific module run the command: `mvn clean install -Dgib.enabled=false` in the module directory
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..9d347869bd 100644
--- a/algorithms/README.md
+++ b/algorithms/README.md
@@ -23,3 +23,11 @@
- [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)
+- [Round Up to the Nearest Hundred](https://www.baeldung.com/java-round-up-nearest-hundred)
+- [Merge Sort in Java](https://www.baeldung.com/java-merge-sort)
+- [Calculate Percentage in Java](https://www.baeldung.com/java-calculate-percentage)
diff --git a/algorithms/pom.xml b/algorithms/pom.xml
index eda87d6c75..db4a1c2eff 100644
--- a/algorithms/pom.xml
+++ b/algorithms/pom.xml
@@ -17,6 +17,11 @@
commons-math3
${commons-math3.version}
+
+ commons-codec
+ commons-codec
+ ${commons-codec.version}
+
org.projectlombok
lombok
@@ -85,6 +90,7 @@
3.7.0
1.0.1
3.9.0
+ 1.11
\ No newline at end of file
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/conversion/HexStringConverter.java b/algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java
new file mode 100644
index 0000000000..d3e251d3fd
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/conversion/HexStringConverter.java
@@ -0,0 +1,110 @@
+package com.baeldung.algorithms.conversion;
+
+import java.math.BigInteger;
+
+import javax.xml.bind.DatatypeConverter;
+
+import org.apache.commons.codec.DecoderException;
+import org.apache.commons.codec.binary.Hex;
+
+import com.google.common.io.BaseEncoding;
+
+public class HexStringConverter {
+
+ /**
+ * Create a byte Array from String of hexadecimal digits using Character conversion
+ * @param hexString - Hexadecimal digits as String
+ * @return Desired byte Array
+ */
+ public byte[] decodeHexString(String hexString) {
+ if (hexString.length() % 2 == 1) {
+ throw new IllegalArgumentException("Invalid hexadecimal String supplied.");
+ }
+ byte[] bytes = new byte[hexString.length() / 2];
+
+ for (int i = 0; i < hexString.length(); i += 2) {
+ bytes[i / 2] = hexToByte(hexString.substring(i, i + 2));
+ }
+ return bytes;
+ }
+
+ /**
+ * Create a String of hexadecimal digits from a byte Array using Character conversion
+ * @param byteArray - The byte Array
+ * @return Desired String of hexadecimal digits in lower case
+ */
+ public String encodeHexString(byte[] byteArray) {
+ StringBuffer hexStringBuffer = new StringBuffer();
+ for (int i = 0; i < byteArray.length; i++) {
+ hexStringBuffer.append(byteToHex(byteArray[i]));
+ }
+ return hexStringBuffer.toString();
+ }
+
+ public String byteToHex(byte num) {
+ char[] hexDigits = new char[2];
+ hexDigits[0] = Character.forDigit((num >> 4) & 0xF, 16);
+ hexDigits[1] = Character.forDigit((num & 0xF), 16);
+ return new String(hexDigits);
+ }
+
+ public byte hexToByte(String hexString) {
+ int firstDigit = toDigit(hexString.charAt(0));
+ int secondDigit = toDigit(hexString.charAt(1));
+ return (byte) ((firstDigit << 4) + secondDigit);
+ }
+
+ private int toDigit(char hexChar) {
+ int digit = Character.digit(hexChar, 16);
+ if(digit == -1) {
+ throw new IllegalArgumentException("Invalid Hexadecimal Character: "+ hexChar);
+ }
+ return digit;
+ }
+
+ public String encodeUsingBigIntegerToString(byte[] bytes) {
+ BigInteger bigInteger = new BigInteger(1, bytes);
+ return bigInteger.toString(16);
+ }
+
+ public String encodeUsingBigIntegerStringFormat(byte[] bytes) {
+ BigInteger bigInteger = new BigInteger(1, bytes);
+ return String.format("%0" + (bytes.length << 1) + "x", bigInteger);
+ }
+
+ public byte[] decodeUsingBigInteger(String hexString) {
+ byte[] byteArray = new BigInteger(hexString, 16).toByteArray();
+ if (byteArray[0] == 0) {
+ byte[] output = new byte[byteArray.length - 1];
+ System.arraycopy(byteArray, 1, output, 0, output.length);
+ return output;
+ }
+ return byteArray;
+ }
+
+ public String encodeUsingDataTypeConverter(byte[] bytes) {
+ return DatatypeConverter.printHexBinary(bytes);
+ }
+
+ public byte[] decodeUsingDataTypeConverter(String hexString) {
+ return DatatypeConverter.parseHexBinary(hexString);
+ }
+
+ public String encodeUsingApacheCommons(byte[] bytes) throws DecoderException {
+ return Hex.encodeHexString(bytes);
+ }
+
+ public byte[] decodeUsingApacheCommons(String hexString) throws DecoderException {
+ return Hex.decodeHex(hexString);
+ }
+
+ public String encodeUsingGuava(byte[] bytes) {
+ return BaseEncoding.base16()
+ .encode(bytes);
+ }
+
+ public byte[] decodeUsingGuava(String hexString) {
+ return BaseEncoding.base16()
+ .decode(hexString.toUpperCase());
+ }
+}
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/insertionsort/InsertionSort.java b/algorithms/src/main/java/com/baeldung/algorithms/insertionsort/InsertionSort.java
new file mode 100644
index 0000000000..02dd485cf1
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/insertionsort/InsertionSort.java
@@ -0,0 +1,41 @@
+package com.baeldung.algorithms.insertionsort;
+
+public class InsertionSort {
+
+ public static void insertionSortImperative(int[] input) {
+ for (int i = 1; i < input.length; i++) {
+ int key = input[i];
+ int j = i - 1;
+ while (j >= 0 && input[j] > key) {
+ input[j + 1] = input[j];
+ j = j - 1;
+ }
+ input[j + 1] = key;
+ }
+ }
+
+ public static void insertionSortRecursive(int[] input) {
+ insertionSortRecursive(input, input.length);
+ }
+
+ private static void insertionSortRecursive(int[] input, int i) {
+ // base case
+ if (i <= 1) {
+ return;
+ }
+
+ // sort the first i - 1 elements of the array
+ insertionSortRecursive(input, i - 1);
+
+ // then find the correct position of the element at position i
+ int key = input[i - 1];
+ int j = i - 2;
+ // shifting the elements from their position by 1
+ while (j >= 0 && input[j] > key) {
+ input[j + 1] = input[j];
+ j = j - 1;
+ }
+ // inserting the key at the appropriate position
+ input[j + 1] = key;
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java b/algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java
index 822abdae02..7054979ada 100644
--- a/algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java
+++ b/algorithms/src/main/java/com/baeldung/algorithms/kthlargest/FindKthLargest.java
@@ -98,7 +98,7 @@ public class FindKthLargest {
private int randomPartition(Integer arr[], int left, int right) {
int n = right - left + 1;
- int pivot = (int) (Math.random()) % n;
+ int pivot = (int) (Math.random() * n);
swap(arr, left + pivot, right);
return partition(arr, left, right);
}
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/mergesort/MergeSort.java b/algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java
new file mode 100644
index 0000000000..0deb48b6a0
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/mergesort/MergeSort.java
@@ -0,0 +1,50 @@
+package com.baeldung.algorithms.mergesort;
+
+public class MergeSort {
+
+ public static void main(String[] args) {
+ int[] a = { 5, 1, 6, 2, 3, 4 };
+ mergeSort(a, a.length);
+ for (int i = 0; i < a.length; i++)
+ System.out.println(a[i]);
+ }
+
+ public static void mergeSort(int[] a, int n) {
+ if (n < 2)
+ return;
+ int mid = n / 2;
+ int[] l = new int[mid];
+ int[] r = new int[n - mid];
+
+ for (int i = 0; i < mid; i++) {
+ l[i] = a[i];
+ }
+ for (int i = mid; i < n; i++) {
+ r[i - mid] = a[i];
+ }
+ mergeSort(l, mid);
+ mergeSort(r, n - mid);
+
+ merge(a, l, r, mid, n - mid);
+ }
+
+ public static void merge(int[] a, int[] l, int[] r, int left, int right) {
+
+ int i = 0, j = 0, k = 0;
+
+ while (i < left && j < right) {
+
+ if (l[i] < r[j])
+ a[k++] = l[i++];
+ else
+ a[k++] = r[j++];
+
+ }
+
+ while (i < left)
+ a[k++] = l[i++];
+
+ while (j < right)
+ a[k++] = r[j++];
+ }
+}
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java b/algorithms/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java
new file mode 100644
index 0000000000..e113cc3242
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/quicksort/QuickSort.java
@@ -0,0 +1,39 @@
+package com.baeldung.algorithms.quicksort;
+
+public class QuickSort {
+
+ public static void quickSort(int arr[], int begin, int end)
+ {
+ if (begin < end) {
+ int partitionIndex = partition(arr, begin, end);
+
+ // Recursively sort elements of the 2 sub-arrays
+ quickSort(arr, begin, partitionIndex-1);
+ quickSort(arr, partitionIndex+1, end);
+ }
+ }
+
+ private static int partition(int arr[], int begin, int end)
+ {
+ int pivot = arr[end];
+ int i = (begin-1);
+
+ for (int j=begin; j 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/conversion/ByteArrayConverterUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java
new file mode 100644
index 0000000000..be61802705
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/conversion/ByteArrayConverterUnitTest.java
@@ -0,0 +1,127 @@
+package com.baeldung.algorithms.conversion;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+import org.apache.commons.codec.DecoderException;
+import org.hamcrest.text.IsEqualIgnoringCase;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.baeldung.algorithms.conversion.HexStringConverter;
+
+public class ByteArrayConverterUnitTest {
+
+ private HexStringConverter hexStringConverter;
+
+ @Before
+ public void setup() {
+ hexStringConverter = new HexStringConverter();
+ }
+
+ @Test
+ public void shouldEncodeByteArrayToHexStringUsingBigIntegerToString() {
+ byte[] bytes = getSampleBytes();
+ String hexString = getSampleHexString();
+ if(hexString.charAt(0) == '0') {
+ hexString = hexString.substring(1);
+ }
+ String output = hexStringConverter.encodeUsingBigIntegerToString(bytes);
+ assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
+ }
+
+ @Test
+ public void shouldEncodeByteArrayToHexStringUsingBigIntegerStringFormat() {
+ byte[] bytes = getSampleBytes();
+ String hexString = getSampleHexString();
+ String output = hexStringConverter.encodeUsingBigIntegerStringFormat(bytes);
+ assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
+ }
+
+ @Test
+ public void shouldDecodeHexStringToByteArrayUsingBigInteger() {
+ byte[] bytes = getSampleBytes();
+ String hexString = getSampleHexString();
+ byte[] output = hexStringConverter.decodeUsingBigInteger(hexString);
+ assertArrayEquals(bytes, output);
+ }
+
+ @Test
+ public void shouldEncodeByteArrayToHexStringUsingCharacterConversion() {
+ byte[] bytes = getSampleBytes();
+ String hexString = getSampleHexString();
+ String output = hexStringConverter.encodeHexString(bytes);
+ assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
+ }
+
+ @Test
+ public void shouldDecodeHexStringToByteArrayUsingCharacterConversion() {
+ byte[] bytes = getSampleBytes();
+ String hexString = getSampleHexString();
+ byte[] output = hexStringConverter.decodeHexString(hexString);
+ assertArrayEquals(bytes, output);
+ }
+
+ @Test(expected=IllegalArgumentException.class)
+ public void shouldDecodeHexToByteWithInvalidHexCharacter() {
+ hexStringConverter.hexToByte("fg");
+ }
+
+ @Test
+ public void shouldEncodeByteArrayToHexStringDataTypeConverter() {
+ byte[] bytes = getSampleBytes();
+ String hexString = getSampleHexString();
+ String output = hexStringConverter.encodeUsingDataTypeConverter(bytes);
+ assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
+ }
+
+ @Test
+ public void shouldDecodeHexStringToByteArrayUsingDataTypeConverter() {
+ byte[] bytes = getSampleBytes();
+ String hexString = getSampleHexString();
+ byte[] output = hexStringConverter.decodeUsingDataTypeConverter(hexString);
+ assertArrayEquals(bytes, output);
+ }
+
+ @Test
+ public void shouldEncodeByteArrayToHexStringUsingGuava() {
+ byte[] bytes = getSampleBytes();
+ String hexString = getSampleHexString();
+ String output = hexStringConverter.encodeUsingGuava(bytes);
+ assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
+ }
+
+ @Test
+ public void shouldDecodeHexStringToByteArrayUsingGuava() {
+ byte[] bytes = getSampleBytes();
+ String hexString = getSampleHexString();
+ byte[] output = hexStringConverter.decodeUsingGuava(hexString);
+ assertArrayEquals(bytes, output);
+ }
+
+ @Test
+ public void shouldEncodeByteArrayToHexStringUsingApacheCommons() throws DecoderException {
+ byte[] bytes = getSampleBytes();
+ String hexString = getSampleHexString();
+ String output = hexStringConverter.encodeUsingApacheCommons(bytes);
+ assertThat(output, IsEqualIgnoringCase.equalToIgnoringCase(hexString));
+ }
+
+ @Test
+ public void shouldDecodeHexStringToByteArrayUsingApacheCommons() throws DecoderException {
+ byte[] bytes = getSampleBytes();
+ String hexString = getSampleHexString();
+ byte[] output = hexStringConverter.decodeUsingApacheCommons(hexString);
+ assertArrayEquals(bytes, output);
+ }
+
+ private String getSampleHexString() {
+ return "0af50c0e2d10";
+ }
+
+ private byte[] getSampleBytes() {
+ return new byte[] { 10, -11, 12, 14, 45, 16 };
+ }
+
+}
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/insertionsort/InsertionSortUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java
new file mode 100644
index 0000000000..b3d7e8c534
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/insertionsort/InsertionSortUnitTest.java
@@ -0,0 +1,25 @@
+package com.baeldung.algorithms.insertionsort;
+
+import com.baeldung.algorithms.insertionsort.InsertionSort;
+import org.junit.Test;
+
+import static org.junit.Assert.assertArrayEquals;
+
+public class InsertionSortUnitTest {
+
+ @Test
+ public void givenUnsortedArray_whenInsertionSortImperative_thenSortedAsc() {
+ int[] input = {6, 2, 3, 4, 5, 1};
+ InsertionSort.insertionSortImperative(input);
+ int[] expected = {1, 2, 3, 4, 5, 6};
+ assertArrayEquals("the two arrays are not equal", expected, input);
+ }
+
+ @Test
+ public void givenUnsortedArray_whenInsertionSortRecursive_thenSortedAsc() {
+ int[] input = {6, 4, 5, 2, 3, 1};
+ InsertionSort.insertionSortRecursive(input);
+ int[] expected = {1, 2, 3, 4, 5, 6};
+ assertArrayEquals("the two arrays are not equal", expected, input);
+ }
+}
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/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java
new file mode 100644
index 0000000000..5cd14b7bd0
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/mergesort/MergeSortUnitTest.java
@@ -0,0 +1,17 @@
+package com.baeldung.algorithms.mergesort;
+
+import org.junit.Assert;
+
+import org.junit.Test;
+
+public class MergeSortUnitTest {
+
+ @Test
+ public void positiveTest() {
+ int[] actual = { 5, 1, 6, 2, 3, 4 };
+ int[] expected = { 1, 2, 3, 4, 5, 6 };
+ MergeSort.mergeSort(actual, actual.length);
+ Assert.assertArrayEquals(expected, actual);
+ }
+
+}
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/quicksort/QuickSortUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java
new file mode 100644
index 0000000000..c9af5b4bf8
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/quicksort/QuickSortUnitTest.java
@@ -0,0 +1,17 @@
+package com.baeldung.algorithms.quicksort;
+
+import com.baeldung.algorithms.quicksort.QuickSort;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class QuickSortUnitTest {
+
+ @Test
+ public void givenIntegerArray_whenSortedWithQuickSort_thenGetSortedArray() {
+ int[] actual = { 9, 5, 1, 0, 6, 2, 3, 4, 7, 8 };
+ int[] expected = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
+ QuickSort.quickSort(actual, 0, actual.length-1);
+ Assert.assertArrayEquals(expected, actual);
+ }
+
+}
diff --git a/algorithms/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java b/algorithms/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java
new file mode 100644
index 0000000000..cd8c7c1241
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/quicksort/ThreeWayQuickSortUnitTest.java
@@ -0,0 +1,15 @@
+package com.baeldung.algorithms.quicksort;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class ThreeWayQuickSortUnitTest {
+
+ @Test
+ public void givenIntegerArray_whenSortedWithThreeWayQuickSort_thenGetSortedArray() {
+ int[] actual = { 3, 5, 5, 5, 3, 7, 7, 3, 5, 5, 7, 3, 3 };
+ int[] expected = { 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 7, 7, 7 };
+ ThreeWayQuickSort.threeWayQuickSort(actual, 0, actual.length-1);
+ Assert.assertArrayEquals(expected, actual);
+ }
+}
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/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java b/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java
similarity index 81%
rename from animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java
rename to animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java
index 8ecb1bc629..dcfd22ff87 100644
--- a/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppTest.java
+++ b/animal-sniffer-mvn-plugin/src/test/java/com/baeldung/AppUnitTest.java
@@ -7,7 +7,7 @@ import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
-public class AppTest
+public class AppUnitTest
extends TestCase
{
/**
@@ -15,7 +15,7 @@ public class AppTest
*
* @param testName name of the test case
*/
- public AppTest( String testName )
+ public AppUnitTest( String testName )
{
super( testName );
}
@@ -25,7 +25,7 @@ public class AppTest
*/
public static Test suite()
{
- return new TestSuite( AppTest.class );
+ return new TestSuite( AppUnitTest.class );
}
/**
diff --git a/annotations/annotation-processing/src/main/resources/logback.xml b/annotations/annotation-processing/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/annotations/annotation-processing/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/annotations/annotation-user/src/main/resources/logback.xml b/annotations/annotation-user/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/annotations/annotation-user/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/antlr/src/main/resources/logback.xml b/antlr/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/antlr/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-avro/README.md b/apache-avro/README.md
new file mode 100644
index 0000000000..32d84ecc76
--- /dev/null
+++ b/apache-avro/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Guide to Apache Avro](http://www.baeldung.com/java-apache-avro)
diff --git a/apache-avro/pom.xml b/apache-avro/pom.xml
index 39da518269..ddf5844271 100644
--- a/apache-avro/pom.xml
+++ b/apache-avro/pom.xml
@@ -4,8 +4,9 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.baeldung
- apache-avro-tutorial
+ apache-avro
0.0.1-SNAPSHOT
+ Apache Avro
UTF-8
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
index d2219a45f2..7d30c3d1ee 100644
--- a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroDeSerealizer.java
@@ -5,29 +5,37 @@ import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.io.IOException;
public class AvroDeSerealizer {
-public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data){
- DatumReader reader = new SpecificDatumReader<>(AvroHttpRequest.class);
- Decoder decoder = null;
- try {
- decoder = DecoderFactory.get().jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
- return reader.read(null, decoder);
- } catch (IOException e) {
- return null;
- }
-}
+ private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
-public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data){
- DatumReader employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
- Decoder decoder = DecoderFactory.get().binaryDecoder(data, null);
- try {
- return employeeReader.read(null, decoder);
- } catch (IOException e) {
+ public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) {
+ DatumReader reader = new SpecificDatumReader<>(AvroHttpRequest.class);
+ Decoder decoder = null;
+ try {
+ decoder = DecoderFactory.get()
+ .jsonDecoder(AvroHttpRequest.getClassSchema(), new String(data));
+ return reader.read(null, decoder);
+ } catch (IOException e) {
+ logger.error("Deserialization error" + e.getMessage());
+ }
+ return null;
+ }
+
+ public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data) {
+ DatumReader employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
+ Decoder decoder = DecoderFactory.get()
+ .binaryDecoder(data, null);
+ try {
+ return employeeReader.read(null, decoder);
+ } catch (IOException e) {
+ logger.error("Deserialization error" + e.getMessage());
+ }
return null;
}
}
-}
diff --git a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
index f56c89e201..767b688dea 100644
--- a/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
+++ b/apache-avro/src/main/java/com/baeldung/avro/util/serealization/AvroSerealizer.java
@@ -3,42 +3,48 @@ package com.baeldung.avro.util.serealization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.*;
import org.apache.avro.specific.SpecificDatumWriter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class AvroSerealizer {
-public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request){
- DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
- byte[] data = new byte[0];
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- Encoder jsonEncoder = null;
- try {
- jsonEncoder = EncoderFactory.get().jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
- writer.write(request, jsonEncoder);
- jsonEncoder.flush();
- data = stream.toByteArray();
- } catch (IOException e) {
- data =null;
- }
- return data;
-}
+ private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class);
-public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request){
- DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
- byte[] data = new byte[0];
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- Encoder jsonEncoder = EncoderFactory.get().binaryEncoder(stream,null);
- try {
- writer.write(request, jsonEncoder);
- jsonEncoder.flush();
- data = stream.toByteArray();
- } catch (IOException e) {
- data = null;
+ public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request) {
+ DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
+ byte[] data = new byte[0];
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ Encoder jsonEncoder = null;
+ try {
+ jsonEncoder = EncoderFactory.get()
+ .jsonEncoder(AvroHttpRequest.getClassSchema(), stream);
+ writer.write(request, jsonEncoder);
+ jsonEncoder.flush();
+ data = stream.toByteArray();
+ } catch (IOException e) {
+ logger.error("Serialization error " + e.getMessage());
+ }
+ return data;
}
- return data;
-}
+ public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request) {
+ DatumWriter writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
+ byte[] data = new byte[0];
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ Encoder jsonEncoder = EncoderFactory.get()
+ .binaryEncoder(stream, null);
+ try {
+ writer.write(request, jsonEncoder);
+ jsonEncoder.flush();
+ data = stream.toByteArray();
+ } catch (IOException e) {
+ logger.error("Serialization error " + e.getMessage());
+ }
+
+ return data;
+ }
}
diff --git a/apache-avro/src/main/resources/logback.xml b/apache-avro/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-avro/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java
deleted file mode 100644
index 937a4ae650..0000000000
--- a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-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 WhenSerialized_UsingJSONEncoder_ObjectGetsSerialized(){
- byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
- assertTrue(Objects.nonNull(data));
- assertTrue(data.length > 0);
-}
-
-@Test
-public void WhenSerialized_UsingBinaryEncoder_ObjectGetsSerialized(){
- byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
- assertTrue(Objects.nonNull(data));
- assertTrue(data.length > 0);
-}
-
-@Test
-public void WhenDeserialize_UsingJSONDecoder_ActualAndExpectedObjectsAreEqual(){
- byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
- AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
- assertEquals(actualRequest,request);
- assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
-}
-
-@Test
-public void WhenDeserialize_UsingBinaryecoder_ActualAndExpectedObjectsAreEqual(){
- byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
- AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
- assertEquals(actualRequest,request);
- assertTrue(actualRequest.getRequestTime().equals(request.getRequestTime()));
-}
-}
-
diff --git a/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.java
new file mode 100644
index 0000000000..992ea806c3
--- /dev/null
+++ b/apache-avro/src/test/java/com/baeldung/avro/util/serealization/AvroSerealizerDeSerealizerUnitTest.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 AvroSerealizerDeSerealizerUnitTest {
+
+ 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-geode/pom.xml b/apache-geode/pom.xml
new file mode 100644
index 0000000000..a3f6604ac4
--- /dev/null
+++ b/apache-geode/pom.xml
@@ -0,0 +1,46 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ apache-geode
+ 1.0-SNAPSHOT
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+ 1.6.0
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ 1.8
+ 1.8
+
+
+
+
+
+
+
+ org.apache.geode
+ geode-core
+ ${geode.core}
+
+
+ junit
+ junit
+ RELEASE
+
+
+
+
\ No newline at end of file
diff --git a/apache-geode/src/main/java/com/baeldung/geode/Customer.java b/apache-geode/src/main/java/com/baeldung/geode/Customer.java
new file mode 100644
index 0000000000..82ee5ecaeb
--- /dev/null
+++ b/apache-geode/src/main/java/com/baeldung/geode/Customer.java
@@ -0,0 +1,78 @@
+package com.baeldung.geode;
+
+import java.io.Serializable;
+import java.util.Objects;
+
+public class Customer implements Serializable {
+
+ private static final long serialVersionUID = -7482516011038799900L;
+
+ private CustomerKey key;
+ private String firstName;
+ private String lastName;
+ private Integer age;
+
+ public Customer() {
+ }
+
+ public Customer(String firstName, String lastName, int age) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.age = age;
+ }
+
+ public Customer(CustomerKey key, String firstName, String lastName, int age) {
+ this(firstName, lastName, age);
+ this.key = key;
+ }
+
+ // setters and getters
+
+ public static long getSerialVersionUID() {
+ return serialVersionUID;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public Integer getAge() {
+ return age;
+ }
+
+ public void setAge(Integer age) {
+ this.age = age;
+ }
+
+ @Override
+ public String toString() {
+ return "Customer{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}';
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+ Customer customer = (Customer) o;
+ return Objects.equals(firstName, customer.firstName) && Objects.equals(lastName, customer.lastName) && Objects.equals(age, customer.age);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(firstName, lastName, age);
+ }
+}
diff --git a/apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java b/apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java
new file mode 100644
index 0000000000..bfa64870c0
--- /dev/null
+++ b/apache-geode/src/main/java/com/baeldung/geode/CustomerKey.java
@@ -0,0 +1,57 @@
+package com.baeldung.geode;
+
+import java.io.Serializable;
+
+public class CustomerKey implements Serializable {
+
+ private static final long serialVersionUID = -3529253035303792458L;
+ private long id;
+ private String country;
+
+ public CustomerKey(long id) {
+ this.id = id;
+ this.country = "USA";
+ }
+
+ public CustomerKey(long id, String country) {
+ this.id = id;
+ this.country = country;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public String getCountry() {
+ return country;
+ }
+
+ public void setCountry(String country) {
+ this.country = country;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+
+ CustomerKey that = (CustomerKey) o;
+
+ if (id != that.id)
+ return false;
+ return country != null ? country.equals(that.country) : that.country == null;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = (int) (id ^ (id >>> 32));
+ result = 31 * result + (country != null ? country.hashCode() : 0);
+ return result;
+ }
+}
diff --git a/apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java b/apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java
new file mode 100644
index 0000000000..5ff8e53da8
--- /dev/null
+++ b/apache-geode/src/main/java/com/baeldung/geode/functions/UpperCaseNames.java
@@ -0,0 +1,34 @@
+package com.baeldung.geode.functions;
+
+import com.baeldung.geode.Customer;
+import com.baeldung.geode.CustomerKey;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.execute.Function;
+import org.apache.geode.cache.execute.FunctionContext;
+import org.apache.geode.cache.execute.RegionFunctionContext;
+
+import java.util.Map;
+
+public class UpperCaseNames implements Function {
+ private static final long serialVersionUID = -8946294032165677602L;
+
+ @Override
+ public void execute(FunctionContext context) {
+ RegionFunctionContext regionContext = (RegionFunctionContext) context;
+ Region region = regionContext.getDataSet();
+
+ for (Map.Entry entry : region.entrySet()) {
+ Customer customer = entry.getValue();
+ customer.setFirstName(customer.getFirstName()
+ .toUpperCase());
+ }
+
+ context.getResultSender()
+ .lastResult(true);
+ }
+
+ @Override
+ public String getId() {
+ return getClass().getName();
+ }
+}
diff --git a/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java
new file mode 100644
index 0000000000..b96d2c9b6a
--- /dev/null
+++ b/apache-geode/src/test/java/com/baeldung/geode/GeodeSamplesIntegrationTest.java
@@ -0,0 +1,110 @@
+package com.baeldung.geode;
+
+import com.baeldung.geode.functions.UpperCaseNames;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.client.ClientCache;
+import org.apache.geode.cache.client.ClientCacheFactory;
+import org.apache.geode.cache.client.ClientRegionShortcut;
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.FunctionService;
+import org.apache.geode.cache.query.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.junit.Assert.assertEquals;
+
+public class GeodeSamplesIntegrationTest {
+
+ ClientCache cache = null;
+ Region region = null;
+ Region queryRegion = null;
+ Region customerRegion = null;
+
+ @Before
+ public void connect() {
+ this.cache = new ClientCacheFactory().addPoolLocator("localhost", 10334)
+ .create();
+ this.region = this.cache. createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
+ .create("baeldung");
+ this.customerRegion = this.cache. createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
+ .create("baeldung-customers");
+ }
+
+ @After
+ public void cleanup() {
+ this.cache.close();
+ }
+
+ @Test
+ public void whenSendMessageToRegion_thenMessageSavedSuccessfully() {
+
+ this.region.put("1", "Hello");
+ this.region.put("2", "Baeldung");
+
+ assertEquals("Hello", region.get("1"));
+ assertEquals("Baeldung", region.get("2"));
+
+ }
+
+ @Test
+ public void whenPutMultipleValuesAtOnce_thenValuesSavedSuccessfully() {
+
+ Supplier> keys = () -> Stream.of("A", "B", "C", "D", "E");
+ Map values = keys.get()
+ .collect(Collectors.toMap(Function.identity(), String::toLowerCase));
+
+ this.region.putAll(values);
+
+ keys.get()
+ .forEach(k -> assertEquals(k.toLowerCase(), this.region.get(k)));
+
+ }
+
+ @Test
+ public void whenPutCustomKey_thenValuesSavedSuccessfully() {
+ CustomerKey key = new CustomerKey(123);
+ Customer customer = new Customer(key, "William", "Russell", 35);
+
+ Map customerInfo = new HashMap<>();
+ customerInfo.put(key, customer);
+
+ this.customerRegion.putAll(customerInfo);
+
+ Customer storedCustomer = this.customerRegion.get(key);
+ assertEquals("William", storedCustomer.getFirstName());
+ assertEquals("Russell", storedCustomer.getLastName());
+
+ }
+
+ @Test
+ public void whenFindACustomerUsingOQL_thenCorrectCustomerObject() throws NameResolutionException, TypeMismatchException, QueryInvocationTargetException, FunctionDomainException {
+
+ Map data = new HashMap<>();
+ data.put(new CustomerKey(1), new Customer("Gheorge", "Manuc", 36));
+ data.put(new CustomerKey(2), new Customer("Allan", "McDowell", 43));
+ this.customerRegion.putAll(data);
+
+ QueryService queryService = this.cache.getQueryService();
+ String query = "select * from /baeldung-customers c where c.firstName = 'Allan'";
+ SelectResults queryResults = (SelectResults) queryService.newQuery(query)
+ .execute();
+ assertEquals(1, queryResults.size());
+
+ }
+
+ @Test
+ public void whenExecuteUppercaseNames_thenCustomerNamesAreUppercased() {
+ Execution execution = FunctionService.onRegion(this.customerRegion);
+ execution.execute(UpperCaseNames.class.getName());
+ Customer customer = this.customerRegion.get(new CustomerKey(1));
+ assertEquals("GHEORGE", customer.getFirstName());
+ }
+}
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/README.md b/aws/README.md
index d23937a419..2c61928095 100644
--- a/aws/README.md
+++ b/aws/README.md
@@ -9,4 +9,4 @@
- [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests)
- [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3)
- [Managing Amazon SQS Queues in Java](http://www.baeldung.com/aws-queues-java)
-
+- [Guide to AWS Aurora RDS with Java](https://www.baeldung.com/aws-aurora-rds-java)
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 8e4e5f95b5..64d423aafe 100644
--- a/core-java-8/README.md
+++ b/core-java-8/README.md
@@ -9,50 +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)
-- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
-- [Measure Elapsed Time in Java](http://www.baeldung.com/java-measure-elapsed-time)
- [Java Optional – orElse() vs orElseGet()](http://www.baeldung.com/java-optional-or-else-vs-or-else-get)
-- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
- [Method Parameter Reflection in Java](http://www.baeldung.com/java-parameter-reflection)
- [Java 8 Unsigned Arithmetic Support](http://www.baeldung.com/java-unsigned-arithmetic)
-- [How to Get the Start and the End of a Day using Java](http://www.baeldung.com/java-day-start-end)
- [Generalized Target-Type Inference in Java](http://www.baeldung.com/java-generalized-target-type-inference)
-- [Image to Base64 String Conversion](http://www.baeldung.com/java-base64-image-string)
-- [Calculate Age in Java](http://www.baeldung.com/java-get-age)
+- [Overriding System Time for Testing in Java](http://www.baeldung.com/java-override-system-time)
+- [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/findItemsBasedOnValues/.gitignore b/core-java-8/findItemsBasedOnValues/.gitignore
new file mode 100644
index 0000000000..ae3c172604
--- /dev/null
+++ b/core-java-8/findItemsBasedOnValues/.gitignore
@@ -0,0 +1 @@
+/bin/
diff --git a/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java
new file mode 100644
index 0000000000..a0dcdddd85
--- /dev/null
+++ b/core-java-8/findItemsBasedOnValues/src/findItems/FindItemsBasedOnValues.java
@@ -0,0 +1,93 @@
+package findItems;
+
+import static org.junit.Assert.assertEquals;
+
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.junit.Test;
+
+public class FindItemsBasedOnValues {
+
+ List EmplList = new ArrayList();
+ List deptList = new ArrayList();
+
+ public static void main(String[] args) throws ParseException {
+ FindItemsBasedOnValues findItems = new FindItemsBasedOnValues();
+ findItems.givenDepartmentList_thenEmployeeListIsFilteredCorrectly();
+ }
+
+ @Test
+ public void givenDepartmentList_thenEmployeeListIsFilteredCorrectly() {
+ Integer expectedId = 1002;
+
+ populate(EmplList, deptList);
+
+ List filteredList = EmplList.stream()
+ .filter(empl -> deptList.stream()
+ .anyMatch(dept -> dept.getDepartment()
+ .equals("sales") && empl.getEmployeeId()
+ .equals(dept.getEmployeeId())))
+ .collect(Collectors.toList());
+
+ assertEquals(expectedId, filteredList.get(0)
+ .getEmployeeId());
+ }
+
+ private void populate(List EmplList, List deptList) {
+ Employee employee1 = new Employee(1001, "empl1");
+ Employee employee2 = new Employee(1002, "empl2");
+ Employee employee3 = new Employee(1003, "empl3");
+
+ Collections.addAll(EmplList, employee1, employee2, employee3);
+
+ Department department1 = new Department(1002, "sales");
+ Department department2 = new Department(1003, "marketing");
+ Department department3 = new Department(1004, "sales");
+
+ Collections.addAll(deptList, department1, department2, department3);
+ }
+}
+
+class Employee {
+ Integer employeeId;
+ String employeeName;
+
+ public Employee(Integer employeeId, String employeeName) {
+ super();
+ this.employeeId = employeeId;
+ this.employeeName = employeeName;
+ }
+
+ public Integer getEmployeeId() {
+ return employeeId;
+ }
+
+ public String getEmployeeName() {
+ return employeeName;
+ }
+
+}
+
+class Department {
+ Integer employeeId;
+ String department;
+
+ public Department(Integer employeeId, String department) {
+ super();
+ this.employeeId = employeeId;
+ this.department = department;
+ }
+
+ public Integer getEmployeeId() {
+ return employeeId;
+ }
+
+ public String getDepartment() {
+ return department;
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-8/pom.xml b/core-java-8/pom.xml
index 7e3b8cb280..18bdaa15f4 100644
--- a/core-java-8/pom.xml
+++ b/core-java-8/pom.xml
@@ -89,11 +89,6 @@
vavr
${vavr.version}
-
- one.util
- streamex
- ${streamex.version}
-
joda-time
joda-time
@@ -121,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
@@ -151,6 +129,7 @@
org.springframework.boot
spring-boot-maven-plugin
+ ${spring-boot-maven-plugin.version}
@@ -176,7 +155,6 @@
1.16.12
0.9.0
1.13
- 0.6.5
2.10
3.6.1
@@ -184,6 +162,6 @@
1.7.0
1.19
1.19
+ 2.0.4.RELEASE
-
-
\ No newline at end of file
+
diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java
new file mode 100644
index 0000000000..7587cc6834
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingCommonsEmptyIfNull.java
@@ -0,0 +1,19 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Collection;
+import java.util.stream.Stream;
+import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
+
+public class NullSafeCollectionStreamsUsingCommonsEmptyIfNull {
+
+ /**
+ * This method shows how to make a null safe stream from a collection through the use of
+ * emptyIfNull() method from Apache Commons CollectionUtils library
+ *
+ * @param collection The collection that is to be converted into a stream
+ * @return The stream that has been created from the collection or an empty stream if the collection is null
+ */
+ public Stream collectionAsStream(Collection collection) {
+ return emptyIfNull(collection).stream();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java
new file mode 100644
index 0000000000..ae8e399d53
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingJava8OptionalContainer.java
@@ -0,0 +1,21 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Collection;
+import java.util.Optional;
+import java.util.stream.Stream;
+
+public class NullSafeCollectionStreamsUsingJava8OptionalContainer {
+
+ /**
+ * This method shows how to make a null safe stream from a collection through the use of
+ * Java SE 8’s Optional Container
+ *
+ * @param collection The collection that is to be converted into a stream
+ * @return The stream that has been created from the collection or an empty stream if the collection is null
+ */
+ public Stream collectionAsStream(Collection collection) {
+ return Optional.ofNullable(collection)
+ .map(Collection::stream)
+ .orElseGet(Stream::empty);
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java
new file mode 100644
index 0000000000..63b6d34f11
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/nullsafecollectionstreams/NullSafeCollectionStreamsUsingNullDereferenceCheck.java
@@ -0,0 +1,20 @@
+package com.baeldung.nullsafecollectionstreams;
+
+import java.util.Collection;
+import java.util.stream.Stream;
+
+public class NullSafeCollectionStreamsUsingNullDereferenceCheck {
+
+ /**
+ * This method shows how to make a null safe stream from a collection through the use of a check
+ * to prevent null dereferences
+ *
+ * @param collection The collection that is to be converted into a stream
+ * @return The stream that has been created from the collection or an empty stream if the collection is null
+ */
+ public Stream collectionAsStream(Collection collection) {
+ return collection == null ? Stream.empty() : collection.stream();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java b/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java
new file mode 100644
index 0000000000..46018faf80
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/optional/PersonRepository.java
@@ -0,0 +1,9 @@
+package com.baeldung.optional;
+
+public class PersonRepository {
+
+ public String findNameById(String id) {
+ return id == null ? null : "Name";
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java b/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java
new file mode 100644
index 0000000000..2513ec0d03
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/BenchmarkRunner.java
@@ -0,0 +1,23 @@
+package com.baeldung.primitive;
+
+public class BenchmarkRunner {
+
+ public static void main(String[] args) throws Exception {
+ new IntPrimitiveLookup().run();
+ new IntegerWrapperLookup().run();
+ new FloatPrimitiveLookup().run();
+ new FloatWrapperLookup().run();
+ new DoublePrimitiveLookup().run();
+ new DoubleWrapperLookup().run();
+ new ShortPrimitiveLookup().run();
+ new ShortWrapperLookup().run();
+ new BooleanPrimitiveLookup().run();
+ new BooleanWrapperLookup().run();
+ new CharPrimitiveLookup().run();
+ new CharacterWrapperLookup().run();
+ new BytePrimitiveLookup().run();
+ new ByteWrapperLookup().run();
+ new LongPrimitiveLookup().run();
+ new LongWrapperLookup().run();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java
new file mode 100644
index 0000000000..2ad698eba4
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/BooleanPrimitiveLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class BooleanPrimitiveLookup extends Lookup {
+
+ private boolean[] elements;
+ private final boolean pivot = false;
+
+ @Setup
+ @Override
+ public void prepare() {
+ elements = new boolean[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = true;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return BooleanPrimitiveLookup.class.getSimpleName();
+ }
+
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java
new file mode 100644
index 0000000000..8d996739a8
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/BooleanWrapperLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class BooleanWrapperLookup extends Lookup {
+ private Boolean[] elements;
+ private final boolean pivot = false;
+
+ @Override
+ @Setup
+ public void prepare() {
+ elements = new Boolean[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = true;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Boolean pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return BooleanWrapperLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java
new file mode 100644
index 0000000000..73eda5cf5b
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/BytePrimitiveLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class BytePrimitiveLookup extends Lookup {
+
+ private byte[] elements;
+ private final byte pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ byte common = 1;
+ elements = new byte[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return BytePrimitiveLookup.class.getSimpleName();
+ }
+
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java
new file mode 100644
index 0000000000..23e02315a6
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/ByteWrapperLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class ByteWrapperLookup extends Lookup {
+ private Byte[] elements;
+ private final byte pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ byte common = 1;
+ elements = new Byte[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Byte pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return ByteWrapperLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java
new file mode 100644
index 0000000000..a6d4be6206
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/CharPrimitiveLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class CharPrimitiveLookup extends Lookup {
+
+ private char[] elements;
+ private final char pivot = 'b';
+
+ @Setup
+ @Override
+ public void prepare() {
+ char common = 'a';
+ elements = new char[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return CharPrimitiveLookup.class.getSimpleName();
+ }
+
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java
new file mode 100644
index 0000000000..9509b4a156
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/CharacterWrapperLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class CharacterWrapperLookup extends Lookup {
+ private Character[] elements;
+ private final char pivot = 'b';
+
+ @Override
+ @Setup
+ public void prepare() {
+ char common = 'a';
+ elements = new Character[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Character pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return CharacterWrapperLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java
new file mode 100644
index 0000000000..f95515a02d
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/DoublePrimitiveLookup.java
@@ -0,0 +1,42 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class DoublePrimitiveLookup extends Lookup {
+ private double[] elements;
+ private final double pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ double common = 1;
+ elements = new double[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return DoublePrimitiveLookup.class.getSimpleName();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java
new file mode 100644
index 0000000000..671c2ccc29
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/DoubleWrapperLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class DoubleWrapperLookup extends Lookup {
+ private Double[] elements;
+ private final double pivot = 2d;
+
+ @Override
+ @Setup
+ public void prepare() {
+ double common = 1;
+ elements = new Double[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Double pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return DoubleWrapperLookup.class.getSimpleName();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java
new file mode 100644
index 0000000000..26b58f0053
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/FloatPrimitiveLookup.java
@@ -0,0 +1,42 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class FloatPrimitiveLookup extends Lookup {
+ private float[] elements;
+ private final float pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ int common = 1;
+ elements = new float[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return FloatPrimitiveLookup.class.getSimpleName();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java
new file mode 100644
index 0000000000..8e75eae3e3
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/FloatWrapperLookup.java
@@ -0,0 +1,43 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class FloatWrapperLookup extends Lookup {
+ private Float[] elements;
+ private final float pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ float common = 1;
+ elements = new Float[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Float pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return FloatWrapperLookup.class.getSimpleName();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java
new file mode 100644
index 0000000000..551163dba2
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/IntPrimitiveLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class IntPrimitiveLookup extends Lookup {
+
+ private int[] elements;
+ private final int pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ int common = 1;
+ elements = new int[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return IntPrimitiveLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java
new file mode 100644
index 0000000000..f39fb80a0b
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/IntegerWrapperLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class IntegerWrapperLookup extends Lookup {
+ private Integer[] elements;
+ private final int pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ int common = 1;
+ elements = new Integer[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Integer pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return IntegerWrapperLookup.class.getSimpleName();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java
new file mode 100644
index 0000000000..2f414577da
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/LongPrimitiveLookup.java
@@ -0,0 +1,42 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class LongPrimitiveLookup extends Lookup {
+ private long[] elements;
+ private final long pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ long common = 1;
+ elements = new long[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return LongPrimitiveLookup.class.getSimpleName();
+ }
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java
new file mode 100644
index 0000000000..692a9fd15c
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/LongWrapperLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class LongWrapperLookup extends Lookup{
+ private Long[] elements;
+ private final long pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ long common = 1;
+ elements = new Long[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Long pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return LongWrapperLookup.class.getSimpleName();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java b/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java
new file mode 100644
index 0000000000..3dc7b7655e
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/Lookup.java
@@ -0,0 +1,56 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.results.RunResult;
+import org.openjdk.jmh.runner.Runner;
+import org.openjdk.jmh.runner.RunnerException;
+import org.openjdk.jmh.runner.options.Options;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+import java.util.Collection;
+
+/**
+ * An abstract class that is to be extended by the classes that
+ * perform lookup in the arrays either of Java primitive types or their wrappers.
+ */
+public abstract class Lookup {
+ /**
+ * the array size
+ */
+ final protected int s = 50000000;
+
+ /**
+ * Initialize the array: fill in the array with the same
+ * elements except for the last one.
+ */
+ abstract public void prepare();
+
+ /**
+ * Free the array's reference.
+ */
+ abstract public void clean();
+
+ /**
+ * Find the position of the element that is different from the others.
+ * By construction, it is the last array element.
+ *
+ * @return array's last element index
+ */
+ abstract public int findPosition();
+
+ /**
+ * Get the name of the class that extends this one. It is needed in order
+ * to set up the benchmark.
+ *
+ * @return
+ */
+ abstract public String getSimpleClassName();
+
+ Collection run() throws RunnerException {
+ Options opt = new OptionsBuilder()
+ .include(getSimpleClassName())
+ .forks(1)
+ .build();
+ return new Runner(opt).run();
+ }
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java
new file mode 100644
index 0000000000..2d2ffbd67b
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/ShortPrimitiveLookup.java
@@ -0,0 +1,45 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class ShortPrimitiveLookup extends Lookup {
+
+ private short[] elements;
+ private final short pivot = 2;
+
+ @Setup
+ @Override
+ public void prepare() {
+ short common = 1;
+ elements = new short[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @TearDown
+ @Override
+ public void clean() {
+ elements = null;
+ }
+
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ while (pivot != elements[index]) {
+ index++;
+ }
+ return index;
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return ShortPrimitiveLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java b/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java
new file mode 100644
index 0000000000..1c1cd4a345
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/primitive/ShortWrapperLookup.java
@@ -0,0 +1,46 @@
+package com.baeldung.primitive;
+
+import org.openjdk.jmh.annotations.*;
+
+@State(Scope.Thread)
+public class ShortWrapperLookup extends Lookup {
+ private Short[] elements;
+ private final short pivot = 2;
+
+ @Override
+ @Setup
+ public void prepare() {
+ short common = 1;
+ elements = new Short[s];
+ for (int i = 0; i < s - 1; i++) {
+ elements[i] = common;
+ }
+ elements[s - 1] = pivot;
+ }
+
+ @Override
+ @TearDown
+ public void clean() {
+ elements = null;
+ }
+
+ @Override
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ public int findPosition() {
+ int index = 0;
+ Short pivotWrapper = pivot;
+ while (!pivotWrapper.equals(elements[index])) {
+ index++;
+ }
+ return index;
+
+ }
+
+ @Override
+ public String getSimpleClassName() {
+ return ShortWrapperLookup.class.getSimpleName();
+ }
+
+
+}
diff --git a/core-java-8/src/main/resources/logback.xml b/core-java-8/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/core-java-8/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java b/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java
deleted file mode 100644
index 4d95bc82e1..0000000000
--- a/core-java-8/src/test/java/com/baeldung/internationalization/DateTimeFormatterUnitTest.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.baeldung.internationalization;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-import java.time.LocalDateTime;
-import java.time.ZoneId;
-import java.time.ZonedDateTime;
-import java.time.format.DateTimeFormatter;
-import java.time.format.FormatStyle;
-import java.util.Locale;
-import java.util.TimeZone;
-
-public class DateTimeFormatterUnitTest {
-
- @Test
- public void givenDefaultUsLocaleAndDateTimeAndPattern_whenFormatWithDifferentLocales_thenGettingLocalizedDateTimes() {
- Locale.setDefault(Locale.US);
- LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
- String pattern = "dd-MMMM-yyyy HH:mm:ss.SSS";
-
- DateTimeFormatter defaultTimeFormatter = DateTimeFormatter.ofPattern(pattern);
- DateTimeFormatter plTimeFormatter = DateTimeFormatter.ofPattern(pattern, new Locale("pl", "PL"));
- DateTimeFormatter deTimeFormatter = DateTimeFormatter.ofPattern(pattern).withLocale(Locale.GERMANY);
-
- Assert.assertEquals("01-January-2018 10:15:50.000", defaultTimeFormatter.format(localDateTime));
- Assert.assertEquals("01-stycznia-2018 10:15:50.000", plTimeFormatter.format(localDateTime));
- Assert.assertEquals("01-Januar-2018 10:15:50.000", deTimeFormatter.format(localDateTime));
- }
-
- @Test
- public void givenDateTimeAndTimeZone_whenFormatWithDifferentLocales_thenGettingLocalizedZonedDateTimes() {
- Locale.setDefault(Locale.US);
- LocalDateTime localDateTime = LocalDateTime.of(2018, 1, 1, 10, 15, 50, 500);
- ZoneId losAngelesTimeZone = TimeZone.getTimeZone("America/Los_Angeles").toZoneId();
-
- DateTimeFormatter localizedFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
- DateTimeFormatter frLocalizedFormatter =
- DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).withLocale(Locale.FRANCE);
- String formattedDateTime = localizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
- String frFormattedDateTime = frLocalizedFormatter.format(ZonedDateTime.of(localDateTime, losAngelesTimeZone));
-
- Assert.assertEquals("Monday, January 1, 2018 10:15:50 AM PST", formattedDateTime);
- Assert.assertEquals("lundi 1 janvier 2018 10 h 15 PST", frFormattedDateTime);
- }
-}
diff --git a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
index f371c0d7da..71ec5b147f 100644
--- a/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
+++ b/core-java-8/src/test/java/com/baeldung/java8/Java8SortUnitTest.java
@@ -1,16 +1,18 @@
package com.baeldung.java8;
-import com.baeldung.java8.entity.Human;
-import com.google.common.collect.Lists;
-import com.google.common.primitives.Ints;
-import org.junit.Assert;
-import org.junit.Test;
+import static org.hamcrest.Matchers.equalTo;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
+import java.util.stream.Collectors;
-import static org.hamcrest.Matchers.equalTo;
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.baeldung.java8.entity.Human;
+import com.google.common.collect.Lists;
+import com.google.common.primitives.Ints;
public class Java8SortUnitTest {
@@ -111,5 +113,22 @@ public class Java8SortUnitTest {
humans.sort(Comparator.comparing(Human::getName));
Assert.assertThat(humans.get(0), equalTo(new Human("Jack", 12)));
}
+
+ @Test
+ public final void givenStreamNaturalOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
+ final List letters = Lists.newArrayList("B", "A", "C");
+
+ final List sortedLetters = letters.stream().sorted().collect(Collectors.toList());
+ Assert.assertThat(sortedLetters.get(0), equalTo("A"));
+ }
+ @Test
+ public final void givenStreamCustomOrdering_whenSortingEntitiesByName_thenCorrectlySorted() {
+
+ final List humans = Lists.newArrayList(new Human("Sarah", 10), new Human("Jack", 12));
+ final Comparator nameComparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
+
+ final List sortedHumans = humans.stream().sorted(nameComparator).collect(Collectors.toList());
+ Assert.assertThat(sortedHumans.get(0), equalTo(new Human("Jack", 12)));
+ }
}
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/stream/conditional/StreamForEachIfElseUnitTest.java b/core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java
new file mode 100644
index 0000000000..b5d26eb6a8
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/stream/conditional/StreamForEachIfElseUnitTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.stream.conditional;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Stream;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class StreamForEachIfElseUnitTest {
+
+ @Test
+ public final void givenIntegerStream_whenCheckingIntegerParityWithIfElse_thenEnsureCorrectParity() {
+ List ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+
+ ints.stream()
+ .forEach(i -> {
+ if (i.intValue() % 2 == 0) {
+ Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0);
+ } else {
+ Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0);
+ }
+ });
+
+ }
+
+ @Test
+ public final void givenIntegerStream_whenCheckingIntegerParityWithStreamFilter_thenEnsureCorrectParity() {
+ List ints = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+
+ Stream evenIntegers = ints.stream()
+ .filter(i -> i.intValue() % 2 == 0);
+ Stream oddIntegers = ints.stream()
+ .filter(i -> i.intValue() % 2 != 0);
+
+ evenIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not even", i.intValue() % 2 == 0));
+ oddIntegers.forEach(i -> Assert.assertTrue(i.intValue() + " is not odd", i.intValue() % 2 != 0));
+
+ }
+
+}
diff --git a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java
index 1689a5054d..ec20b7794b 100644
--- a/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java
+++ b/core-java-8/src/test/java/com/baeldung/util/CurrentDateTimeUnitTest.java
@@ -1,7 +1,6 @@
package com.baeldung.util;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import java.time.Clock;
import java.time.Instant;
@@ -10,8 +9,6 @@ import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
-import org.joda.time.DateTime;
-import org.joda.time.DateTimeUtils;
import org.junit.Test;
public class CurrentDateTimeUnitTest {
diff --git a/core-java-9/README.md b/core-java-9/README.md
index a76dcefc69..38816471aa 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,7 @@
- [A Guide to Java 9 Modularity](http://www.baeldung.com/java-9-modularity)
- [Optional orElse Optional](http://www.baeldung.com/java-optional-or-else-optional)
- [Java 9 java.lang.Module API](http://www.baeldung.com/java-9-module-api)
+- [Iterate Through a Range of Dates in Java](https://www.baeldung.com/java-iterate-date-range)
+- [Initialize a HashMap in Java](https://www.baeldung.com/java-initialize-hashmap)
+- [Java 9 Platform Logging API](https://www.baeldung.com/java-9-logging-api)
+- [Guide to java.lang.Process API](https://www.baeldung.com/java-process-api)
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/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/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 7b3745b486..aef640634e 100644
--- a/core-java-collections/README.md
+++ b/core-java-collections/README.md
@@ -31,3 +31,27 @@
- [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)
+- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall)
+- [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)
+- [Sort a HashMap in Java](https://www.baeldung.com/java-hashmap-sort)
+- [Finding the Highest Value in a Java Map](https://www.baeldung.com/java-find-map-max)
+- [Operating on and Removing an Item from Stream](https://www.baeldung.com/java-use-remove-item-stream)
diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml
index ff06714bfe..b4a6e26d13 100644
--- a/core-java-collections/pom.xml
+++ b/core-java-collections/pom.xml
@@ -1,72 +1,88 @@
-
- 4.0.0
- com.baeldung
- core-java-collections
- 0.1.0-SNAPSHOT
- jar
- core-java-collections
-
-
- com.baeldung
- parent-java
- 0.0.1-SNAPSHOT
- ../parent-java
-
-
-
-
- net.sourceforge.collections
- collections-generic
- ${collections-generic.version}
-
-
- org.apache.commons
- commons-collections4
- ${commons-collections4.version}
-
-
- com.jayway.awaitility
- awaitility
- ${avaitility.version}
- test
-
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
-
-
- org.eclipse.collections
- eclipse-collections-api
- ${eclipse.collections.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
-
-
-
-
- 1.2.0
- 3.5
- 4.1
- 4.01
- 1.7.0
- 3.6.1
- 9.2.0
-
-
+
+ 4.0.0
+ core-java-collections
+ 0.1.0-SNAPSHOT
+ jar
+ core-java-collections
+
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-java
+
+
+
+
+ net.sourceforge.collections
+ collections-generic
+ ${collections-generic.version}
+
+
+ org.apache.commons
+ commons-collections4
+ ${commons-collections4.version}
+
+
+ com.jayway.awaitility
+ awaitility
+ ${avaitility.version}
+ test
+
+
+ org.apache.commons
+ 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
+
+
+
+ one.util
+ streamex
+ 0.6.5
+
+
+
+
+ 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