diff --git a/.gitignore b/.gitignore
index f78dcd70e1..7725bf202e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -69,6 +69,7 @@ jmeter/src/main/resources/*-Basic*.csv
jmeter/src/main/resources/*-JMeter*.csv
jmeter/src/main/resources/*ReportsDashboard*.csv
jmeter/src/main/resources/dashboard/*ReportsDashboard*.csv
+jmeter/src/main/resources/*FileExtractionExample.csv
ninja/devDb.mv.db
@@ -88,6 +89,7 @@ spring-soap/src/main/java/com/baeldung/springsoap/gen/
/report-*.json
transaction.log
*-shell.log
+customers.xml
apache-cxf/cxf-aegis/baeldung.xml
testing-modules/report-*.json
@@ -102,6 +104,7 @@ spring-boot-modules/spring-boot-react/frontend/build
spring-boot-modules/spring-boot-react/frontend/node
spring-boot-modules/spring-boot-react/frontend/yarn.lock
spring-boot-modules/spring-boot-properties-3/*.log
+spring-boot-modules/spring-boot-properties-3/*.gz
# SDKMan
.sdkmanrc
@@ -109,5 +112,12 @@ spring-boot-modules/spring-boot-properties-3/*.log
# Localstack
**/.localstack
+#libraries-2
+libraries-2/employee*
+libraries-2/src/test/resources/crawler4j/**
+
#web-modules/ninja
-devDb*.db
\ No newline at end of file
+devDb*.db
+
+#jaxb
+*.xjb
\ No newline at end of file
diff --git a/README.md b/README.md
index 7ed1e6990a..b354a8f819 100644
--- a/README.md
+++ b/README.md
@@ -74,6 +74,10 @@ Building a single module
====================
To build a specific module, run the command: `mvn clean install` in the module directory.
+It can happen that your module is part of a parent module e.g. `parent-boot-1`,`parent-spring-5` etc, then you will need to build the parent module first so that you can build your module.
+We have created a `parents` profile that you can use to build just the parent modules, just run the profile as:
+`mvn clean install -Pparents`
+
Building modules from the root of the repository
====================
diff --git a/akka-modules/akka-http/pom.xml b/akka-modules/akka-http/pom.xml
index 3af7c492ca..9372107fc9 100644
--- a/akka-modules/akka-http/pom.xml
+++ b/akka-modules/akka-http/pom.xml
@@ -36,7 +36,6 @@
-
10.0.11
2.5.11
diff --git a/akka-modules/spring-akka/pom.xml b/akka-modules/spring-akka/pom.xml
index 7451a40b86..2201181435 100644
--- a/akka-modules/spring-akka/pom.xml
+++ b/akka-modules/spring-akka/pom.xml
@@ -43,7 +43,7 @@
- 4.3.4.RELEASE
+ 5.3.25
2.4.14
diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checktargetsum/CheckTargetSum.java b/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checktargetsum/CheckTargetSum.java
new file mode 100644
index 0000000000..fdbde62301
--- /dev/null
+++ b/algorithms-modules/algorithms-miscellaneous-3/src/main/java/com/baeldung/algorithms/checktargetsum/CheckTargetSum.java
@@ -0,0 +1,58 @@
+package com.baeldung.algorithms.checktargetsum;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+public class CheckTargetSum {
+ public boolean isTargetSumExistNaive(int[] nums, int target) {
+ for (int i = 0; i < nums.length; i++) {
+ for (int j = i + 1; j < nums.length; j++) {
+ if (nums[i] + nums[j] == target) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ public boolean isTargetSumExistSorted(int[] nums, int target) {
+ Arrays.sort(nums);
+
+ int start = 0;
+ int end = nums.length - 1;
+
+ while (start < end) {
+ int sum = nums[start] + nums[end];
+
+ if (sum == target) {
+ return true;
+ }
+
+ if (sum < target) {
+ start++;
+ } else {
+ end--;
+ }
+ }
+
+ return false;
+ }
+
+ public boolean isTargetSumExistHashSet(int[] nums, int target) {
+ Set hashSet = new HashSet<>();
+
+ for (int num : nums) {
+ int diff = target - num;
+
+ if (hashSet.contains(diff)) {
+ return true;
+ }
+
+ hashSet.add(num);
+ }
+
+ return false;
+ }
+}
diff --git a/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checktargetsum/CheckTargetSumUnitTest.java b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checktargetsum/CheckTargetSumUnitTest.java
new file mode 100644
index 0000000000..ff20ce112e
--- /dev/null
+++ b/algorithms-modules/algorithms-miscellaneous-3/src/test/java/com/baeldung/algorithms/checktargetsum/CheckTargetSumUnitTest.java
@@ -0,0 +1,46 @@
+package com.baeldung.algorithms.checktargetsum;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class CheckTargetSumUnitTest {
+ private CheckTargetSum checkTargetSum = new CheckTargetSum();
+
+ private int[] nums = new int[] { 10, 5, 15, 7, 14, 1, 9 };
+
+ private int existingTarget = 6;
+
+ private int nonExistingTarget = 27;
+
+ @Test
+ public void givenArrayOfIntegers_whenTargetSumNaive_thenPairExists() {
+ assertTrue(checkTargetSum.isTargetSumExistNaive(nums, existingTarget));
+ }
+
+ @Test
+ public void givenArrayOfIntegers_whenTargetSumNaive_thenPairDoesNotExists() {
+ assertFalse(checkTargetSum.isTargetSumExistNaive(nums, nonExistingTarget));
+ }
+
+ @Test
+ public void givenArrayOfIntegers_whenTargetSumSorted_thenPairExists() {
+ assertTrue(checkTargetSum.isTargetSumExistNaive(nums, existingTarget));
+ }
+
+ @Test
+ public void givenArrayOfIntegers_whenTargetSumSorted_thenPairDoesNotExists() {
+ assertFalse(checkTargetSum.isTargetSumExistNaive(nums, nonExistingTarget));
+ }
+
+ @Test
+ public void givenArrayOfIntegers_whenTargetSumHashSet_thenPairExists() {
+ assertTrue(checkTargetSum.isTargetSumExistNaive(nums, existingTarget));
+ }
+
+ @Test
+ public void givenArrayOfIntegers_whenTargetSumHashSet_thenPairDoesNotExists() {
+ assertFalse(checkTargetSum.isTargetSumExistNaive(nums, nonExistingTarget));
+ }
+}
diff --git a/algorithms-modules/algorithms-miscellaneous-7/README.md b/algorithms-modules/algorithms-miscellaneous-7/README.md
index 918fcd21dd..ab07d655f9 100644
--- a/algorithms-modules/algorithms-miscellaneous-7/README.md
+++ b/algorithms-modules/algorithms-miscellaneous-7/README.md
@@ -1,4 +1,6 @@
### Relevant Articles:
- [Algorithm to Identify and Validate a Credit Card Number](https://www.baeldung.com/java-validate-cc-number)
+- [Find the N Most Frequent Elements in a Java Array](https://www.baeldung.com/java-n-most-frequent-elements-array)
+- [Getting Pixel Array From Image in Java](https://www.baeldung.com/java-getting-pixel-array-from-image)
- More articles: [[<-- prev]](/algorithms-miscellaneous-6)
diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsFinder.java b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsFinder.java
new file mode 100644
index 0000000000..0d78691bcc
--- /dev/null
+++ b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsFinder.java
@@ -0,0 +1,93 @@
+package com.baeldung.algorithms.frequentelements;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+public class MostFrequentElementsFinder {
+
+ public static List findByHashMapAndPriorityQueue(Integer[] array, int n) {
+ Map countMap = new HashMap<>();
+
+ // For each element i in the array, add it to the countMap and increment its count.
+ for (Integer i : array) {
+ countMap.put(i, countMap.getOrDefault(i, 0) + 1);
+ }
+
+ // Create a max heap (priority queue) that will prioritize elements with higher counts.
+ PriorityQueue heap = new PriorityQueue<>(
+ (a, b) -> countMap.get(b) - countMap.get(a));
+
+ // Add all the unique elements in the array to the heap.
+ heap.addAll(countMap.keySet());
+
+ List result = new ArrayList<>();
+ for (int i = 0; i < n && !heap.isEmpty(); i++) {
+ // Poll the highest-count element from the heap and add it to the result list.
+ result.add(heap.poll());
+ }
+
+ return result;
+ }
+
+ public static List findByStream(Integer[] arr, int n) {
+ return Arrays.stream(arr).collect(Collectors.groupingBy(i -> i, Collectors.counting()))
+ .entrySet().stream()
+ .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
+ .map(Map.Entry::getKey)
+ .limit(n)
+ .collect(Collectors.toList());
+ }
+
+ public static List findByTreeMap(Integer[] arr, int n) {
+ // Create a TreeMap and use a reverse order comparator to sort the entries by frequency in descending order
+ Map countMap = new TreeMap<>(Collections.reverseOrder());
+
+ for (int i : arr) {
+ countMap.put(i, countMap.getOrDefault(i, 0) + 1);
+ }
+
+ // Create a list of the map entries and sort them by value (i.e. by frequency) in descending order
+ List> sortedEntries = new ArrayList<>(countMap.entrySet());
+ sortedEntries.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));
+
+ // Extract the n most frequent elements from the sorted list of entries
+ List result = new ArrayList<>();
+ for (int i = 0; i < n && i < sortedEntries.size(); i++) {
+ result.add(sortedEntries.get(i).getKey());
+ }
+
+ return result;
+ }
+
+ public static List findByBucketSort(Integer[] arr, int n) {
+ List result = new ArrayList<>();
+ Map freqMap = new HashMap<>();
+ List[] bucket = new List[arr.length + 1];
+
+ // Loop through the input array and update the frequency count of each element in the HashMap
+ for (int num : arr) {
+ freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
+ }
+
+ // Loop through the HashMap and add each element to its corresponding bucket based on its frequency count
+ for (int num : freqMap.keySet()) {
+ int freq = freqMap.get(num);
+ if (bucket[freq] == null) {
+ bucket[freq] = new ArrayList<>();
+ }
+ bucket[freq].add(num);
+ }
+
+ // Loop through the bucket array in reverse order and add the elements to the result list
+ // until we have found the n most frequent elements
+ for (int i = bucket.length - 1; i >= 0 && result.size() < n; i--) {
+ if (bucket[i] != null) {
+ result.addAll(bucket[i]);
+ }
+ }
+
+ // Return a sublist of the result list containing only the first n elements
+ return result.subList(0, n);
+ }
+
+}
diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/pixelarray/GetPixelArray.java b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/pixelarray/GetPixelArray.java
new file mode 100644
index 0000000000..ba7fe44808
--- /dev/null
+++ b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/pixelarray/GetPixelArray.java
@@ -0,0 +1,65 @@
+package com.baeldung.algorithms.pixelarray;
+
+import java.awt.image.BufferedImage;
+import java.awt.image.DataBufferByte;
+public class GetPixelArray {
+
+ public static int[][] get2DPixelArraySlow(BufferedImage sampleImage) {
+ int width = sampleImage.getWidth();
+ int height = sampleImage.getHeight();
+ int[][] result = new int[height][width];
+
+ for (int row = 0; row < height; row++) {
+ for (int col = 0; col < width; col++) {
+ result[row][col] = sampleImage.getRGB(col, row);
+ }
+ }
+
+ return result;
+ }
+
+ public static int[][] get2DPixelArrayFast(BufferedImage image) {
+ final byte[] pixelData = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
+ final int width = image.getWidth();
+ final int height = image.getHeight();
+ final boolean hasAlphaChannel = image.getAlphaRaster() != null;
+
+ int[][] result = new int[height][width];
+ if (hasAlphaChannel) {
+ final int numberOfValues = 4;
+ for (int valueIndex = 0, row = 0, col = 0; valueIndex + numberOfValues - 1 < pixelData.length; valueIndex += numberOfValues) {
+ // Getting the values for each pixel from the pixelData array.
+ int argb = 0;
+ argb += (((int) pixelData[valueIndex] & 0xff) << 24); // alpha value
+ argb += ((int) pixelData[valueIndex + 1] & 0xff); // blue value
+ argb += (((int) pixelData[valueIndex + 2] & 0xff) << 8); // green value
+ argb += (((int) pixelData[valueIndex + 3] & 0xff) << 16); // red value
+ result[row][col] = argb;
+
+ col++;
+ if (col == width) {
+ col = 0;
+ row++;
+ }
+ }
+ } else {
+ final int numberOfValues = 3;
+ for (int valueIndex = 0, row = 0, col = 0; valueIndex + numberOfValues - 1 < pixelData.length; valueIndex += numberOfValues) {
+ int argb = 0;
+ argb += -16777216; // 255 alpha value (fully opaque)
+ argb += ((int) pixelData[valueIndex] & 0xff); // blue value
+ argb += (((int) pixelData[valueIndex + 1] & 0xff) << 8); // green value
+ argb += (((int) pixelData[valueIndex + 2] & 0xff) << 16); // red value
+ result[row][col] = argb;
+
+ col++;
+ if (col == width) {
+ col = 0;
+ row++;
+ }
+ }
+ }
+
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsUnitTest.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsUnitTest.java
new file mode 100644
index 0000000000..9fa4862163
--- /dev/null
+++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsUnitTest.java
@@ -0,0 +1,33 @@
+package com.baeldung.algorithms.frequentelements;
+
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Java6Assertions.assertThat;
+
+public class MostFrequentElementsUnitTest {
+
+ private final Integer[] inputArray = {1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 7, 7, 7, 8, 9, 9, 9, 9, 9};
+ private final int n = 3;
+ private final Integer[] outputArray = {9, 7, 5};
+
+ @Test
+ void givenIntegersArray_UseFindByHashMapAndPriorityQueueMethod_thenReturnMostFrequentElements() {
+ assertThat(MostFrequentElementsFinder.findByHashMapAndPriorityQueue(inputArray, n)).containsExactly(outputArray);
+ }
+
+ @Test
+ void givenIntegersArray_UseFindByBucketSortMethod_thenReturnMostFrequentElements() {
+ assertThat(MostFrequentElementsFinder.findByBucketSort(inputArray, n)).containsExactly(outputArray);
+ }
+
+ @Test
+ void givenIntegersArray_UseFindByStreamMethod_thenReturnMostFrequentElements() {
+ assertThat(MostFrequentElementsFinder.findByStream(inputArray, n)).containsExactly(outputArray);
+ }
+
+ @Test
+ void givenIntegersArray_UseFindByTreeMapMethod_thenReturnMostFrequentElements() {
+ assertThat(MostFrequentElementsFinder.findByTreeMap(inputArray, n)).containsExactly(outputArray);
+ }
+
+}
diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/pixelarray/GetPixelArrayUnitTest.java b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/pixelarray/GetPixelArrayUnitTest.java
new file mode 100644
index 0000000000..b7bbb462dd
--- /dev/null
+++ b/algorithms-modules/algorithms-miscellaneous-7/src/test/java/com/baeldung/algorithms/pixelarray/GetPixelArrayUnitTest.java
@@ -0,0 +1,30 @@
+package com.baeldung.algorithms.pixelarray;
+
+import static com.baeldung.algorithms.pixelarray.GetPixelArray.get2DPixelArrayFast;
+import static com.baeldung.algorithms.pixelarray.GetPixelArray.get2DPixelArraySlow;
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.File;
+import java.io.IOException;
+import java.util.Arrays;
+
+public class GetPixelArrayUnitTest {
+ @Test
+ public void givenImage_whenGetPixelArray_thenBothMethodsReturnEqualValues() {
+ BufferedImage sampleImage = null;
+ try {
+ sampleImage = ImageIO.read(new File("src/main/resources/images/sampleImage.jpg"));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ int[][] firstResult = get2DPixelArraySlow(sampleImage);
+ int[][] secondResult = get2DPixelArrayFast(sampleImage);
+
+ assertTrue(Arrays.deepEquals(firstResult, secondResult));
+ }
+}
diff --git a/annotations/annotation-processing/pom.xml b/annotations/annotation-processing/pom.xml
index 2a17242ee5..14bbc409e5 100644
--- a/annotations/annotation-processing/pom.xml
+++ b/annotations/annotation-processing/pom.xml
@@ -21,7 +21,6 @@
-
1.0-rc2
diff --git a/apache-cxf-modules/cxf-aegis/pom.xml b/apache-cxf-modules/cxf-aegis/pom.xml
index d013aabc65..6b9e026cdd 100644
--- a/apache-cxf-modules/cxf-aegis/pom.xml
+++ b/apache-cxf-modules/cxf-aegis/pom.xml
@@ -20,4 +20,8 @@
+
+ 4.0.0
+
+
\ No newline at end of file
diff --git a/apache-cxf-modules/cxf-introduction/pom.xml b/apache-cxf-modules/cxf-introduction/pom.xml
index fe7b917c6f..fdcd100cc5 100644
--- a/apache-cxf-modules/cxf-introduction/pom.xml
+++ b/apache-cxf-modules/cxf-introduction/pom.xml
@@ -23,6 +23,16 @@
cxf-rt-transports-http-jetty
${cxf.version}
+
+ jakarta.xml.ws
+ jakarta.xml.ws-api
+ ${jakarta-xml.version}
+
+
+ jakarta.jws
+ jakarta.jws-api
+ ${jakarta.jws.version}
+
@@ -37,4 +47,10 @@
+
+ 4.0.0
+ 4.0.0
+ 3.0.0
+
+
\ No newline at end of file
diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java
index 472d38b8e1..cd482af0db 100644
--- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java
+++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Baeldung.java
@@ -2,8 +2,8 @@ package com.baeldung.cxf.introduction;
import java.util.Map;
-import javax.jws.WebService;
-import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+import jakarta.jws.WebService;
+import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@WebService
public interface Baeldung {
diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java
index 240f6bb1da..04a6243cc2 100644
--- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java
+++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/BaeldungImpl.java
@@ -3,7 +3,7 @@ package com.baeldung.cxf.introduction;
import java.util.LinkedHashMap;
import java.util.Map;
-import javax.jws.WebService;
+import jakarta.jws.WebService;
@WebService(endpointInterface = "com.baeldung.cxf.introduction.Baeldung")
public class BaeldungImpl implements Baeldung {
diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java
index 2ac649f4c5..f00a64a055 100644
--- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java
+++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Server.java
@@ -1,6 +1,6 @@
package com.baeldung.cxf.introduction;
-import javax.xml.ws.Endpoint;
+import jakarta.xml.ws.Endpoint;
public class Server {
public static void main(String args[]) throws InterruptedException {
diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java
index cad8f94d97..0605956bbc 100644
--- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java
+++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/Student.java
@@ -1,6 +1,6 @@
package com.baeldung.cxf.introduction;
-import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
@XmlJavaTypeAdapter(StudentAdapter.class)
public interface Student {
diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java
index 29b829d808..7885c953a5 100644
--- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java
+++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentAdapter.java
@@ -1,6 +1,6 @@
package com.baeldung.cxf.introduction;
-import javax.xml.bind.annotation.adapters.XmlAdapter;
+import jakarta.xml.bind.annotation.adapters.XmlAdapter;
public class StudentAdapter extends XmlAdapter {
public StudentImpl marshal(Student student) throws Exception {
diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java
index bc9dd27afe..041418befb 100644
--- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java
+++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentImpl.java
@@ -1,6 +1,6 @@
package com.baeldung.cxf.introduction;
-import javax.xml.bind.annotation.XmlType;
+import jakarta.xml.bind.annotation.XmlType;
@XmlType(name = "Student")
public class StudentImpl implements Student {
diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java
index 4c40886c42..aa17b0cf4f 100644
--- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java
+++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMap.java
@@ -3,8 +3,8 @@ package com.baeldung.cxf.introduction;
import java.util.ArrayList;
import java.util.List;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlType;
+import jakarta.xml.bind.annotation.XmlElement;
+import jakarta.xml.bind.annotation.XmlType;
@XmlType(name = "StudentMap")
public class StudentMap {
diff --git a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java
index f156676a5f..3bf1bfd2ff 100644
--- a/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java
+++ b/apache-cxf-modules/cxf-introduction/src/main/java/com/baeldung/cxf/introduction/StudentMapAdapter.java
@@ -3,7 +3,7 @@ package com.baeldung.cxf.introduction;
import java.util.LinkedHashMap;
import java.util.Map;
-import javax.xml.bind.annotation.adapters.XmlAdapter;
+import jakarta.xml.bind.annotation.adapters.XmlAdapter;
public class StudentMapAdapter extends XmlAdapter> {
public StudentMap marshal(Map boundMap) throws Exception {
diff --git a/apache-cxf-modules/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java b/apache-cxf-modules/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java
index 60fc0a10e7..89b127a742 100644
--- a/apache-cxf-modules/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java
+++ b/apache-cxf-modules/cxf-introduction/src/test/java/com/baeldung/cxf/introduction/StudentLiveTest.java
@@ -5,8 +5,8 @@ import static org.junit.Assert.assertEquals;
import java.util.Map;
import javax.xml.namespace.QName;
-import javax.xml.ws.Service;
-import javax.xml.ws.soap.SOAPBinding;
+import jakarta.xml.ws.Service;
+import jakarta.xml.ws.soap.SOAPBinding;
import org.junit.Before;
import org.junit.Test;
diff --git a/apache-cxf-modules/cxf-jaxrs-implementation/pom.xml b/apache-cxf-modules/cxf-jaxrs-implementation/pom.xml
index cc5eba4025..8418853b1e 100644
--- a/apache-cxf-modules/cxf-jaxrs-implementation/pom.xml
+++ b/apache-cxf-modules/cxf-jaxrs-implementation/pom.xml
@@ -16,12 +16,28 @@
org.apache.cxf
cxf-rt-frontend-jaxrs
- ${cxf.version}
+ 4.0.0
org.apache.cxf
cxf-rt-transports-http-jetty
- ${cxf.version}
+ 4.0.0
+
+
+ jakarta.xml.ws
+ jakarta.xml.ws-api
+ ${jakarta-xml.version}
+
+
+ jakarta.jws
+ jakarta.jws-api
+ ${jakarta-jws.version}
+
+
+ jakarta.platform
+ jakarta.jakartaee-web-api
+ ${jakarta-platform.version}
+ compile
org.apache.httpcomponents
@@ -50,6 +66,9 @@
4.5.2
+ 4.0.0
+ 3.0.0
+ 9.0.0
\ No newline at end of file
diff --git a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java b/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java
index dba9b9c661..9f2ba2e837 100644
--- a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java
+++ b/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Course.java
@@ -1,8 +1,8 @@
package com.baeldung.cxf.jaxrs.implementation;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Response;
-import javax.xml.bind.annotation.XmlRootElement;
+import jakarta.ws.rs.*;
+import jakarta.ws.rs.core.Response;
+import jakarta.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
diff --git a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java b/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java
index a2fd6be435..e527180440 100644
--- a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java
+++ b/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/CourseRepository.java
@@ -1,7 +1,7 @@
package com.baeldung.cxf.jaxrs.implementation;
-import javax.ws.rs.*;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.*;
+import jakarta.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
diff --git a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java b/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java
index bd3dad0f5e..f6c4e32cdd 100644
--- a/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java
+++ b/apache-cxf-modules/cxf-jaxrs-implementation/src/main/java/com/baeldung/cxf/jaxrs/implementation/Student.java
@@ -1,6 +1,6 @@
package com.baeldung.cxf.jaxrs.implementation;
-import javax.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Student")
public class Student {
diff --git a/apache-cxf-modules/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java b/apache-cxf-modules/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java
index 29c34ae16b..a9f71930f2 100644
--- a/apache-cxf-modules/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java
+++ b/apache-cxf-modules/cxf-jaxrs-implementation/src/test/java/com/baeldung/cxf/jaxrs/implementation/ServiceLiveTest.java
@@ -7,7 +7,7 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
-import javax.xml.bind.JAXB;
+import jakarta.xml.bind.JAXB;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
diff --git a/apache-cxf-modules/cxf-spring/pom.xml b/apache-cxf-modules/cxf-spring/pom.xml
index ebbebd7f3b..1c87ae4bfb 100644
--- a/apache-cxf-modules/cxf-spring/pom.xml
+++ b/apache-cxf-modules/cxf-spring/pom.xml
@@ -40,10 +40,22 @@
spring-webmvc
${spring.version}
+
+ com.sun.xml.ws
+ jaxws-ri
+ 2.3.3
+ pom
+
javax.servlet
javax.servlet-api
- ${javax.servlet-api.version}
+ 4.0.1
+ provided
+
+
+ javax.servlet
+ jstl
+ 1.2
@@ -103,8 +115,9 @@
- 4.3.4.RELEASE
+ 5.3.25
1.6.1
+ 3.3.2
\ No newline at end of file
diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/pom.xml b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/pom.xml
index 26c8a87c2b..ce2b0059c3 100644
--- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/pom.xml
+++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/pom.xml
@@ -23,6 +23,11 @@
cxf-rt-rs-sse
${cxf-version}
+
+ jakarta.ws.rs
+ jakarta.ws.rs-api
+ ${jakarta-ws.version}
+
@@ -55,7 +60,8 @@
- 3.2.0
+ 4.0.0
+ 3.1.0
\ No newline at end of file
diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java
index 5d42b3a243..af9a9c7691 100644
--- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java
+++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java
@@ -1,10 +1,10 @@
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 jakarta.ws.rs.client.Client;
+import jakarta.ws.rs.client.ClientBuilder;
+import jakarta.ws.rs.client.WebTarget;
+import jakarta.ws.rs.sse.InboundSseEvent;
+import jakarta.ws.rs.sse.SseEventSource;
import java.util.function.Consumer;
public class SseClientApp {
diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java
index 9afc187a6d..4e3c236437 100644
--- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java
+++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java
@@ -1,10 +1,10 @@
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 jakarta.ws.rs.client.Client;
+import jakarta.ws.rs.client.ClientBuilder;
+import jakarta.ws.rs.client.WebTarget;
+import jakarta.ws.rs.sse.InboundSseEvent;
+import jakarta.ws.rs.sse.SseEventSource;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml
index 0467fd9e5d..3bd3e5cb27 100644
--- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml
+++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/pom.xml
@@ -15,16 +15,14 @@
- javax.ws.rs
- javax.ws.rs-api
- ${rs-api.version}
- provided
+ jakarta.ws.rs
+ jakarta.ws.rs-api
+ ${jakarta-ws.version}
- javax.enterprise
- cdi-api
- ${cdi-api.version}
- provided
+ jakarta.enterprise
+ jakarta.enterprise.cdi-api
+ ${jakarta-cdi-api}
javax.json.bind
@@ -37,6 +35,11 @@
${project.artifactId}
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
net.wasdev.wlp.maven.plugins
liberty-maven-plugin
@@ -78,9 +81,10 @@
2.4.2
false
18.0.0.2
- 2.1
- 2.0
+ 3.1.0
+ 4.0.1
1.0
+ 3.3.2
\ No newline at end of file
diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java
index 058d19f045..fdd1af632c 100644
--- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java
+++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java
@@ -1,7 +1,7 @@
package com.baeldung.sse.jaxrs;
-import javax.ws.rs.ApplicationPath;
-import javax.ws.rs.core.Application;
+import jakarta.ws.rs.ApplicationPath;
+import jakarta.ws.rs.core.Application;
@ApplicationPath("sse")
public class AppConfig extends Application {
diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java
index 1f60168a1b..3e211f109b 100644
--- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java
+++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java
@@ -1,15 +1,15 @@
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;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import jakarta.ws.rs.*;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.sse.OutboundSseEvent;
+import jakarta.ws.rs.sse.Sse;
+import jakarta.ws.rs.sse.SseBroadcaster;
+import jakarta.ws.rs.sse.SseEventSink;
@ApplicationScoped
@Path("stock")
diff --git a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java
index 15818ead5d..721ef35678 100644
--- a/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java
+++ b/apache-cxf-modules/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java
@@ -1,11 +1,11 @@
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 jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.context.Initialized;
+import jakarta.enterprise.event.Event;
+import jakarta.enterprise.event.Observes;
+import jakarta.inject.Inject;
+import jakarta.inject.Named;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
diff --git a/apache-httpclient-2/README.md b/apache-httpclient-2/README.md
index 45f1e41637..a19112476b 100644
--- a/apache-httpclient-2/README.md
+++ b/apache-httpclient-2/README.md
@@ -12,6 +12,6 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Reading an HTTP Response Body as a String in Java](https://www.baeldung.com/java-http-response-body-as-string)
- [How To Get Cookies From the Apache HttpClient Response](https://www.baeldung.com/java-apache-httpclient-cookies)
- [Enabling Logging for Apache HttpClient](https://www.baeldung.com/apache-httpclient-enable-logging)
-- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
+- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
- More articles: [[<-- prev]](../apache-httpclient)
diff --git a/apache-httpclient-2/pom.xml b/apache-httpclient-2/pom.xml
index 91c4c718c0..8b7217dbe1 100644
--- a/apache-httpclient-2/pom.xml
+++ b/apache-httpclient-2/pom.xml
@@ -21,17 +21,6 @@
${commons-lang3.version}
-
- org.apache.httpcomponents
- httpclient
- ${httpclient.version}
-
-
- commons-logging
- commons-logging
-
-
-
org.apache.httpcomponents.client5
httpclient5
@@ -97,8 +86,7 @@
3.22.0
5.11.2
- 4.5.8
- 5.2
+ 5.2.1
11
11
2.1.7.RELEASE
diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java
index 265fa39816..ef57406705 100644
--- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java
+++ b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/cookies/HttpClientGettingCookieValueUnitTest.java
@@ -23,7 +23,7 @@ import java.io.IOException;
class HttpClientGettingCookieValueUnitTest {
private static Logger log = LoggerFactory.getLogger(HttpClientGettingCookieValueUnitTest.class);
- private static final String SAMPLE_URL = "http://www.baeldung.com/";
+ private static final String SAMPLE_URL = "http://www.github.com/";
@Test
void whenSettingCustomCookieOnTheRequest_thenGettingTheSameCookieFromTheResponse() throws IOException {
diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/expandUrl/HttpClientExpandUrlLiveTest.java b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/expandUrl/HttpClientExpandUrlLiveTest.java
new file mode 100644
index 0000000000..c1bb5bdddb
--- /dev/null
+++ b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/expandUrl/HttpClientExpandUrlLiveTest.java
@@ -0,0 +1,126 @@
+package com.baeldung.httpclient.expandUrl;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+
+import java.io.IOException;
+import java.util.List;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+import org.apache.commons.lang3.tuple.Pair;
+
+import org.apache.hc.client5.http.classic.methods.HttpHead;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+
+import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpHeaders;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+class HttpClientExpandUrlLiveTest {
+
+ private static CloseableHttpClient httpClient;
+
+ @BeforeAll
+ static void setup() {
+ httpClient = HttpClientBuilder.create()
+ .disableRedirectHandling()
+ .build();
+ }
+
+ @AfterAll
+ static void tearDown() throws IOException {
+ if (httpClient != null) {
+ httpClient.close();
+ }
+ }
+
+ @Test
+ void givenShortenedOnce_whenUrlIsExpanded_thenCorrectResult() throws IOException {
+ final String expectedResult = "https://www.baeldung.com/rest-versioning";
+ final String actualResult = expandSingleLevel("http://bit.ly/3LScTri");
+ assertThat(actualResult, equalTo(expectedResult));
+ }
+
+ @Test
+ void givenShortenedMultiple_whenUrlIsExpanded_thenCorrectResult() throws IOException {
+ final String expectedResult = "https://www.baeldung.com/rest-versioning";
+ final String actualResult = expand("http://t.co/e4rDDbnzmk");
+ assertThat(actualResult, equalTo(expectedResult));
+ }
+
+ private String expand(final String urlArg) throws IOException {
+ String originalUrl = urlArg;
+ String newUrl = expandSingleLevel(originalUrl);
+ while (!originalUrl.equals(newUrl)) {
+ originalUrl = newUrl;
+ newUrl = expandSingleLevel(originalUrl);
+ }
+
+ return newUrl;
+ }
+
+ final String expandSafe(final String urlArg) throws IOException {
+ String originalUrl = urlArg;
+ String newUrl = expandSingleLevelSafe(originalUrl).getRight();
+ final List alreadyVisited = Lists.newArrayList(originalUrl, newUrl);
+ while (!originalUrl.equals(newUrl)) {
+ originalUrl = newUrl;
+ final Pair statusAndUrl = expandSingleLevelSafe(originalUrl);
+ newUrl = statusAndUrl.getRight();
+ final boolean isRedirect = statusAndUrl.getLeft() == 301 || statusAndUrl.getLeft() == 302;
+ if (isRedirect && alreadyVisited.contains(newUrl)) {
+ throw new IllegalStateException("Likely a redirect loop");
+ }
+ alreadyVisited.add(newUrl);
+ }
+
+ return newUrl;
+ }
+
+ private Pair expandSingleLevelSafe(final String url) throws IOException {
+ try {
+ HttpHead request = new HttpHead(url);
+ Pair resp = httpClient.execute(request, response -> {
+ final int statusCode = response.getCode();
+ if (statusCode != 301 && statusCode != 302) {
+ return new ImmutablePair<>(statusCode, url);
+ }
+ final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
+ Preconditions.checkState(headers.length == 1);
+ final String newUrl = headers[0].getValue();
+
+ return new ImmutablePair<>(statusCode, newUrl);
+ });
+ return resp;
+ } catch (final IllegalArgumentException uriEx) {
+ return new ImmutablePair<>(500, url);
+ }
+ }
+
+ private String expandSingleLevel(final String url) throws IOException {
+ try {
+ HttpHead request = new HttpHead(url);
+ String expandedUrl = httpClient.execute(request, response -> {
+ final int statusCode = response.getCode();
+ if (statusCode != 301 && statusCode != 302) {
+ return url;
+ }
+ final Header[] headers = response.getHeaders(HttpHeaders.LOCATION);
+ Preconditions.checkState(headers.length == 1);
+
+ return headers[0].getValue();
+ });
+ return expandedUrl;
+ } catch (final IllegalArgumentException uriEx) {
+ return url;
+ }
+ }
+
+}
diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java
index 0d45eedc12..adf9a1a1a6 100644
--- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java
+++ b/apache-httpclient-2/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java
@@ -1,37 +1,39 @@
package com.baeldung.httpclient.httpclient;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
-import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
-import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.junit.jupiter.api.Test;
-import java.io.IOException;
-
-import static org.assertj.core.api.Assertions.assertThat;
-
class ApacheHttpClientUnitTest extends GetRequestMockServer {
@Test
void givenDeveloperUsedHttpClient_whenExecutingGetRequest_thenStatusIsOkButSonarReportsAnIssue() throws IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(serviceOneUrl);
- HttpResponse response = httpClient.execute(httpGet);
- assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
+ httpClient.execute(httpGet, response -> {
+ assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
+ return response;
+ });
}
@Test
void givenDeveloperUsedCloseableHttpClient_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet(serviceOneUrl);
- HttpResponse response = httpClient.execute(httpGet);
- assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
+ httpClient.execute(httpGet, response -> {
+ assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
+ return response;
+ });
}
}
@@ -39,20 +41,10 @@ class ApacheHttpClientUnitTest extends GetRequestMockServer {
void givenDeveloperUsedHttpClientBuilder_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpGet httpGet = new HttpGet(serviceOneUrl);
- HttpResponse response = httpClient.execute(httpGet);
- assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
- }
- }
-
- @Test
- void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
- try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
- HttpGet httpGet = new HttpGet(serviceOneUrl);
- try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
- HttpEntity entity = response.getEntity();
- EntityUtils.consume(entity);
+ httpClient.execute(httpGet, response -> {
assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
- }
+ return response;
+ });
}
}
@@ -60,18 +52,20 @@ class ApacheHttpClientUnitTest extends GetRequestMockServer {
void givenDeveloperUsedSingleClient_whenExecutingTwoGetRequest_thenStatusIsOk() throws IOException {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpGet httpGetOne = new HttpGet(serviceOneUrl);
- try (CloseableHttpResponse responseOne = httpClient.execute(httpGetOne)) {
+ httpClient.execute(httpGetOne, responseOne -> {
HttpEntity entityOne = responseOne.getEntity();
EntityUtils.consume(entityOne);
assertThat(responseOne.getCode()).isEqualTo(HttpStatus.SC_OK);
- }
+ return responseOne;
+ });
HttpGet httpGetTwo = new HttpGet(serviceTwoUrl);
- try (CloseableHttpResponse responseTwo = httpClient.execute(httpGetTwo)) {
- HttpEntity entityTwo = responseTwo.getEntity();
+ httpClient.execute(httpGetTwo, responseTwo -> {
+ HttpEntity entityTwo = httpGetTwo.getEntity();
EntityUtils.consume(entityTwo);
assertThat(responseTwo.getCode()).isEqualTo(HttpStatus.SC_OK);
- }
+ return responseTwo;
+ });
}
}
diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java
new file mode 100644
index 0000000000..d19e0e1d86
--- /dev/null
+++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestLiveTest.java
@@ -0,0 +1,40 @@
+package com.baeldung.httpclient;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
+import org.apache.hc.client5.http.impl.classic.HttpClients;
+import org.apache.hc.core5.http.HttpEntity;
+import org.apache.hc.core5.http.HttpStatus;
+import org.junit.jupiter.api.Test;
+
+class HttpClientCancelRequestLiveTest {
+
+ private static final String SAMPLE_URL = "http://www.github.com";
+
+ @Test
+ void whenRequestIsCanceled_thenCorrect() throws IOException {
+ HttpGet request = new HttpGet(SAMPLE_URL);
+ try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
+ httpClient.execute(request, response -> {
+ HttpEntity entity = response.getEntity();
+
+ System.out.println("----------------------------------------");
+ System.out.println(response.getCode());
+ if (entity != null) {
+ System.out.println("Response content length: " + entity.getContentLength());
+ }
+ System.out.println("----------------------------------------");
+ // Do not feel like reading the response body
+ // Call abort on the request object
+ request.abort();
+
+ assertThat(response.getCode()).isEqualTo(HttpStatus.SC_OK);
+ return response;
+ });
+ }
+ }
+}
diff --git a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java b/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java
index ef12c37412..4173909f7d 100644
--- a/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java
+++ b/apache-httpclient/src/test/java/com/baeldung/httpclient/base/HttpClientLiveTest.java
@@ -1,8 +1,8 @@
package com.baeldung.httpclient.base;
import com.baeldung.httpclient.ResponseUtil;
+
import org.apache.http.Header;
-import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
@@ -10,7 +10,6 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.junit.After;
import org.junit.Before;
@@ -73,30 +72,4 @@ public class HttpClientLiveTest {
assertThat(headers, not(emptyArray()));
}
- // tests - cancel request
-
- @Test
- public final void whenRequestIsCanceled_thenCorrect() throws IOException {
- instance = HttpClients.custom().build();
- final HttpGet request = new HttpGet(SAMPLE_URL);
- response = instance.execute(request);
-
- try {
- final HttpEntity entity = response.getEntity();
-
- System.out.println("----------------------------------------");
- System.out.println(response.getStatusLine());
- if (entity != null) {
- System.out.println("Response content length: " + entity.getContentLength());
- }
- System.out.println("----------------------------------------");
-
- // Do not feel like reading the response body
- // Call abort on the request object
- request.abort();
- } finally {
- response.close();
- }
- }
-
}
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/.gitignore b/apache-httpclient4/.gitignore
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/.gitignore
rename to apache-httpclient4/.gitignore
diff --git a/httpclient4/README.md b/apache-httpclient4/README.md
similarity index 55%
rename from httpclient4/README.md
rename to apache-httpclient4/README.md
index 445db1108b..22b0391e6b 100644
--- a/httpclient4/README.md
+++ b/apache-httpclient4/README.md
@@ -1,12 +1,16 @@
-## Apache HttpClient
+## Apache HttpClient 4
This module contains articles about Apache HttpClient 4.5
### Relevant Articles
+- [Apache HttpClient – Cancel Request](https://www.baeldung.com/httpclient-cancel-request)
- [Apache HttpClient with SSL](https://www.baeldung.com/httpclient-ssl)
- [Apache HttpClient Timeout](https://www.baeldung.com/httpclient-timeout)
- [Custom HTTP Header with the Apache HttpClient](https://www.baeldung.com/httpclient-custom-http-header)
+- [Apache HttpClient vs. CloseableHttpClient](https://www.baeldung.com/apache-httpclient-vs-closeablehttpclient)
+- [Expand Shortened URLs with Apache HttpClient](https://www.baeldung.com/apache-httpclient-expand-url)
+- [Retrying Requests using Apache HttpClient](https://www.baeldung.com/java-retrying-requests-using-apache-httpclient)
### Running the Tests
To run the live tests, use the command: mvn clean install -Plive
diff --git a/httpclient4/pom.xml b/apache-httpclient4/pom.xml
similarity index 95%
rename from httpclient4/pom.xml
rename to apache-httpclient4/pom.xml
index 8f896283b3..e0bf9dd5f6 100644
--- a/httpclient4/pom.xml
+++ b/apache-httpclient4/pom.xml
@@ -1,11 +1,11 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- httpclient4
+ apache-httpclient4
0.1-SNAPSHOT
- httpclient4
+ apache-httpclient4
war
@@ -152,6 +152,11 @@
+
+ org.mock-server
+ mockserver-netty
+ ${mockserver.version}
+
com.github.tomakehurst
wiremock
@@ -284,8 +289,10 @@
2.5.1
4.4.16
4.5.14
+ 5.11.2
1.6.1
+ 3.3.2
\ No newline at end of file
diff --git a/httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java b/apache-httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java
rename to apache-httpclient4/src/main/java/com/baeldung/basic/MyBasicAuthenticationEntryPoint.java
diff --git a/httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java b/apache-httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java
rename to apache-httpclient4/src/main/java/com/baeldung/client/HttpComponentsClientHttpRequestFactoryBasicAuth.java
diff --git a/httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java b/apache-httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java
rename to apache-httpclient4/src/main/java/com/baeldung/client/RestTemplateFactory.java
diff --git a/httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java b/apache-httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java
rename to apache-httpclient4/src/main/java/com/baeldung/client/spring/ClientConfig.java
diff --git a/httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java b/apache-httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java
rename to apache-httpclient4/src/main/java/com/baeldung/filter/CustomFilter.java
diff --git a/httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java b/apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java
rename to apache-httpclient4/src/main/java/com/baeldung/filter/CustomWebSecurityConfigurerAdapter.java
diff --git a/httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java b/apache-httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java
rename to apache-httpclient4/src/main/java/com/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java
diff --git a/httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java b/apache-httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java
rename to apache-httpclient4/src/main/java/com/baeldung/security/RestAuthenticationEntryPoint.java
diff --git a/httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java b/apache-httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java
rename to apache-httpclient4/src/main/java/com/baeldung/spring/SecSecurityConfig.java
diff --git a/httpclient4/src/main/java/com/baeldung/spring/WebConfig.java b/apache-httpclient4/src/main/java/com/baeldung/spring/WebConfig.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/spring/WebConfig.java
rename to apache-httpclient4/src/main/java/com/baeldung/spring/WebConfig.java
diff --git a/httpclient4/src/main/java/com/baeldung/web/controller/BarController.java b/apache-httpclient4/src/main/java/com/baeldung/web/controller/BarController.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/web/controller/BarController.java
rename to apache-httpclient4/src/main/java/com/baeldung/web/controller/BarController.java
diff --git a/httpclient4/src/main/java/com/baeldung/web/controller/FooController.java b/apache-httpclient4/src/main/java/com/baeldung/web/controller/FooController.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/web/controller/FooController.java
rename to apache-httpclient4/src/main/java/com/baeldung/web/controller/FooController.java
diff --git a/httpclient4/src/main/java/com/baeldung/web/dto/Bar.java b/apache-httpclient4/src/main/java/com/baeldung/web/dto/Bar.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/web/dto/Bar.java
rename to apache-httpclient4/src/main/java/com/baeldung/web/dto/Bar.java
diff --git a/httpclient4/src/main/java/com/baeldung/web/dto/Foo.java b/apache-httpclient4/src/main/java/com/baeldung/web/dto/Foo.java
similarity index 100%
rename from httpclient4/src/main/java/com/baeldung/web/dto/Foo.java
rename to apache-httpclient4/src/main/java/com/baeldung/web/dto/Foo.java
diff --git a/core-java-modules/core-java/src/main/resources/logback.xml b/apache-httpclient4/src/main/resources/logback.xml
similarity index 100%
rename from core-java-modules/core-java/src/main/resources/logback.xml
rename to apache-httpclient4/src/main/resources/logback.xml
diff --git a/httpclient4/src/main/resources/webSecurityConfig.xml b/apache-httpclient4/src/main/resources/webSecurityConfig.xml
similarity index 100%
rename from httpclient4/src/main/resources/webSecurityConfig.xml
rename to apache-httpclient4/src/main/resources/webSecurityConfig.xml
diff --git a/httpclient4/src/main/webapp/WEB-INF/api-servlet.xml b/apache-httpclient4/src/main/webapp/WEB-INF/api-servlet.xml
similarity index 100%
rename from httpclient4/src/main/webapp/WEB-INF/api-servlet.xml
rename to apache-httpclient4/src/main/webapp/WEB-INF/api-servlet.xml
diff --git a/httpclient4/src/main/webapp/WEB-INF/web.xml b/apache-httpclient4/src/main/webapp/WEB-INF/web.xml
similarity index 100%
rename from httpclient4/src/main/webapp/WEB-INF/web.xml
rename to apache-httpclient4/src/main/webapp/WEB-INF/web.xml
diff --git a/httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java
similarity index 100%
rename from httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java
rename to apache-httpclient4/src/test/java/com/baeldung/client/ClientLiveTest.java
diff --git a/httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java b/apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java
similarity index 100%
rename from httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java
rename to apache-httpclient4/src/test/java/com/baeldung/client/RestClientV4LiveManualTest.java
diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java
new file mode 100644
index 0000000000..226a7b8cf7
--- /dev/null
+++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientCancelRequestV4LiveTest.java
@@ -0,0 +1,57 @@
+package com.baeldung.httpclient;
+
+import java.io.IOException;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.client.HttpClients;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class HttpClientCancelRequestV4LiveTest {
+
+ private static final String SAMPLE_URL = "http://www.github.com";
+
+ private CloseableHttpClient instance;
+
+ private CloseableHttpResponse response;
+
+ @Before
+ public final void before() {
+ instance = HttpClientBuilder.create().build();
+ }
+
+ @After
+ public final void after() throws IllegalStateException, IOException {
+ ResponseUtil.closeResponse(response);
+ }
+
+ @Test
+ public final void whenRequestIsCanceled_thenCorrect() throws IOException {
+ instance = HttpClients.custom().build();
+ final HttpGet request = new HttpGet(SAMPLE_URL);
+ response = instance.execute(request);
+
+ try {
+ final HttpEntity entity = response.getEntity();
+
+ System.out.println("----------------------------------------");
+ System.out.println(response.getStatusLine());
+ if (entity != null) {
+ System.out.println("Response content length: " + entity.getContentLength());
+ }
+ System.out.println("----------------------------------------");
+
+ // Do not feel like reading the response body
+ // Call abort on the request object
+ request.abort();
+ } finally {
+ response.close();
+ }
+ }
+}
diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java
similarity index 100%
rename from httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java
rename to apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientHeaderV4LiveTest.java
diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java
similarity index 100%
rename from httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java
rename to apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpClientTimeoutV4LiveTest.java
diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java
similarity index 100%
rename from httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java
rename to apache-httpclient4/src/test/java/com/baeldung/httpclient/HttpsClientV4SslLiveTest.java
diff --git a/httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java
similarity index 100%
rename from httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java
rename to apache-httpclient4/src/test/java/com/baeldung/httpclient/ResponseUtil.java
diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java
similarity index 100%
rename from apache-httpclient-2/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java
rename to apache-httpclient4/src/test/java/com/baeldung/httpclient/expandurl/HttpClientExpandUrlLiveTest.java
diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java
new file mode 100644
index 0000000000..0d394b4ce7
--- /dev/null
+++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/ApacheHttpClientUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.httpclient.httpclient;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.util.EntityUtils;
+import org.junit.jupiter.api.Test;
+
+class ApacheHttpClientUnitTest extends GetRequestMockServer {
+
+
+ @Test
+ void givenDeveloperUsedCloseableHttpResponse_whenExecutingGetRequest_thenStatusIsOk() throws IOException {
+ try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
+ HttpGet httpGet = new HttpGet(serviceOneUrl);
+ try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
+ HttpEntity entity = response.getEntity();
+ EntityUtils.consume(entity);
+ assertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK);
+ }
+ }
+ }
+
+}
diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/GetRequestMockServer.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/GetRequestMockServer.java
new file mode 100644
index 0000000000..3473117cef
--- /dev/null
+++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/httpclient/GetRequestMockServer.java
@@ -0,0 +1,78 @@
+package com.baeldung.httpclient.httpclient;
+
+import org.apache.http.HttpStatus;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.mockserver.client.MockServerClient;
+import org.mockserver.integration.ClientAndServer;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.net.URISyntaxException;
+
+import static org.mockserver.integration.ClientAndServer.startClientAndServer;
+import static org.mockserver.matchers.Times.exactly;
+import static org.mockserver.model.HttpRequest.request;
+import static org.mockserver.model.HttpResponse.response;
+
+public class GetRequestMockServer {
+
+ public static ClientAndServer mockServer;
+ public static String serviceOneUrl;
+ public static String serviceTwoUrl;
+
+ private static int serverPort;
+
+ public static final String SERVER_ADDRESS = "127.0.0.1";
+ public static final String PATH_ONE = "/test1";
+ public static final String PATH_TWO = "/test2";
+ public static final String METHOD = "GET";
+
+ @BeforeAll
+ static void startServer() throws IOException, URISyntaxException {
+ serverPort = getFreePort();
+ serviceOneUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_ONE;
+ serviceTwoUrl = "http://" + SERVER_ADDRESS + ":" + serverPort + PATH_TWO;
+ mockServer = startClientAndServer(serverPort);
+ mockGetRequest();
+ }
+
+ @AfterAll
+ static void stopServer() {
+ mockServer.stop();
+ }
+
+ private static void mockGetRequest() {
+ new MockServerClient(SERVER_ADDRESS, serverPort)
+ .when(
+ request()
+ .withPath(PATH_ONE)
+ .withMethod(METHOD),
+ exactly(5)
+ )
+ .respond(
+ response()
+ .withStatusCode(HttpStatus.SC_OK)
+ .withBody("{\"status\":\"ok\"}")
+ );
+ new MockServerClient(SERVER_ADDRESS, serverPort)
+ .when(
+ request()
+ .withPath(PATH_TWO)
+ .withMethod(METHOD),
+ exactly(1)
+ )
+ .respond(
+ response()
+ .withStatusCode(HttpStatus.SC_OK)
+ .withBody("{\"status\":\"ok\"}")
+ );
+ }
+
+ private static int getFreePort () throws IOException {
+ try (ServerSocket serverSocket = new ServerSocket(0)) {
+ return serverSocket.getLocalPort();
+ }
+ }
+
+}
diff --git a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java
similarity index 99%
rename from apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java
rename to apache-httpclient4/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java
index 7625b415f2..4d88211d0d 100644
--- a/apache-httpclient-2/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java
+++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/readresponsebodystring/ApacheHttpClientUnitTest.java
@@ -25,4 +25,4 @@ public class ApacheHttpClientUnitTest {
logger.debug("Response -> {}", EntityUtils.toString(entity));
}
}
-}
+}
\ No newline at end of file
diff --git a/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java b/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java
new file mode 100644
index 0000000000..3a8ff252c2
--- /dev/null
+++ b/apache-httpclient4/src/test/java/com/baeldung/httpclient/retry/ApacheHttpClientRetryLiveTest.java
@@ -0,0 +1,168 @@
+package com.baeldung.httpclient.retry;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.UnknownHostException;
+import java.util.Objects;
+
+import org.apache.http.HttpRequestInterceptor;
+import org.apache.http.HttpResponseInterceptor;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPatch;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class ApacheHttpClientRetryLiveTest {
+
+ private Integer requestCounter;
+ private CloseableHttpClient httpClient;
+
+ @BeforeEach
+ void setUp() {
+ requestCounter = 0;
+ }
+
+ @AfterEach
+ void tearDown() throws IOException {
+ if (httpClient != null) {
+ httpClient.close();
+ }
+ }
+
+ private void createDefaultApacheHttpClient() {
+ this.httpClient = HttpClientBuilder
+ .create()
+ .addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> {
+ requestCounter++;
+ }).build();
+ }
+
+ private void createFailingHttpClient() {
+ this.httpClient = HttpClientBuilder
+ .create()
+ .addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> requestCounter++)
+ .addInterceptorLast((HttpResponseInterceptor) (httpResponse, httpContext) -> {
+ throw new IOException();
+ })
+ .build();
+ }
+
+ private void createHttpClientWithRetryHandler() {
+ this.httpClient = HttpClientBuilder
+ .create()
+ .addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> requestCounter++)
+ .addInterceptorLast((HttpResponseInterceptor) (httpRequest, httpContext) -> { throw new IOException(); })
+ .setRetryHandler(new DefaultHttpRequestRetryHandler(6, true))
+ .build();
+ }
+
+ private void createHttpClientWithCustomRetryHandler() {
+ this.httpClient = HttpClientBuilder
+ .create()
+ .addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> requestCounter++)
+ .addInterceptorLast((HttpResponseInterceptor) (httpRequest, httpContext) -> { throw new IOException(); })
+ .setRetryHandler((exception, executionCount, context) -> {
+ if (executionCount < 5 && Objects.equals("GET", ((HttpClientContext) context).getRequest().getRequestLine().getMethod())) {
+ return true;
+ } else {
+ return false;
+ }
+ })
+ .build();
+ }
+
+ private void createHttpClientWithRetriesDisabled() {
+ this.httpClient = HttpClientBuilder
+ .create()
+ .addInterceptorFirst((HttpRequestInterceptor) (httpRequest, httpContext) -> requestCounter++)
+ .addInterceptorLast((HttpResponseInterceptor) (httpRequest, httpContext) -> { throw new IOException(); })
+ .disableAutomaticRetries()
+ .build();
+ }
+
+ @Test
+ public void givenDefaultConfiguration_whenReceivedIOException_thenRetriesPerformed() {
+ createFailingHttpClient();
+ assertThrows(IOException.class, () -> httpClient.execute(new HttpGet("https://httpstat.us/200")));
+ assertThat(requestCounter).isEqualTo(4);
+ }
+
+ @Test
+ public void givenDefaultConfiguration_whenDomainNameNotResolved_thenNoRetryApplied() {
+ createDefaultApacheHttpClient();
+ HttpGet request = new HttpGet(URI.create("http://domain.that.does.not.exist:80/api/v1"));
+
+ assertThrows(UnknownHostException.class, () -> httpClient.execute(request));
+ assertThat(requestCounter).isEqualTo(1);
+ }
+
+ @Test
+ public void givenDefaultConfiguration_whenGotInternalServerError_thenNoRetryLogicApplied() throws IOException {
+ createDefaultApacheHttpClient();
+ HttpGet request = new HttpGet(URI.create("https://httpstat.us/500"));
+
+ CloseableHttpResponse response = assertDoesNotThrow(() -> httpClient.execute(request));
+ assertThat(response.getStatusLine().getStatusCode()).isEqualTo(500);
+ assertThat(requestCounter).isEqualTo(1);
+ response.close();
+ }
+
+ @Test
+ public void givenDefaultConfiguration_whenHttpPatchRequest_thenRetryIsNotApplied() {
+ createFailingHttpClient();
+ HttpPatch request = new HttpPatch(URI.create("https://httpstat.us/500"));
+
+ assertThrows(IOException.class, () -> httpClient.execute(request));
+ assertThat(requestCounter).isEqualTo(1);
+ }
+
+ @Test
+ public void givenDefaultConfiguration_whenHttpPutRequest_thenRetryIsNotApplied() {
+ createFailingHttpClient();
+ HttpPut request = new HttpPut(URI.create("https://httpstat.us/500"));
+
+ assertThrows(IOException.class, () -> httpClient.execute(request));
+ assertThat(requestCounter).isEqualTo(1);
+ }
+
+ @Test
+ public void givenConfiguredRetryHandler_whenHttpPostRequest_thenRetriesPerformed() {
+ createHttpClientWithRetryHandler();
+
+ HttpPost request = new HttpPost(URI.create("https://httpstat.us/200"));
+
+ assertThrows(IOException.class, () -> httpClient.execute(request));
+ assertThat(requestCounter).isEqualTo(7);
+ }
+
+ @Test
+ public void givenCustomRetryHandler_whenUnknownHostException_thenRetryAnyway() {
+ createHttpClientWithCustomRetryHandler();
+
+ HttpGet request = new HttpGet(URI.create("https://domain.that.does.not.exist/200"));
+
+ assertThrows(IOException.class, () -> httpClient.execute(request));
+ assertThat(requestCounter).isEqualTo(5);
+ }
+
+ @Test
+ public void givenDisabledRetries_whenExecutedHttpRequestEndUpWithIOException_thenRetryIsNotApplied() {
+ createHttpClientWithRetriesDisabled();
+ HttpGet request = new HttpGet(URI.create("https://httpstat.us/200"));
+
+ assertThrows(IOException.class, () -> httpClient.execute(request));
+ assertThat(requestCounter).isEqualTo(1);
+ }
+}
diff --git a/core-java-modules/core-java/src/test/resources/.gitignore b/apache-httpclient4/src/test/resources/.gitignore
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/.gitignore
rename to apache-httpclient4/src/test/resources/.gitignore
diff --git a/httpclient4/src/test/resources/test.in b/apache-httpclient4/src/test/resources/test.in
similarity index 100%
rename from httpclient4/src/test/resources/test.in
rename to apache-httpclient4/src/test/resources/test.in
diff --git a/apache-kafka-2/README.md b/apache-kafka-2/README.md
index ec9e8e2adc..157078f023 100644
--- a/apache-kafka-2/README.md
+++ b/apache-kafka-2/README.md
@@ -7,3 +7,4 @@ You can build the project from the command line using: *mvn clean install*, or i
### Relevant Articles:
- [Guide to Check if Apache Kafka Server Is Running](https://www.baeldung.com/apache-kafka-check-server-is-running)
+- [Add Custom Headers to a Kafka Message](https://www.baeldung.com/java-kafka-custom-headers)
diff --git a/apache-kafka-2/src/main/java/com/baeldung/kafka/headers/KafkaMessageHeaders.java b/apache-kafka-2/src/main/java/com/baeldung/kafka/headers/KafkaMessageHeaders.java
new file mode 100644
index 0000000000..2c8c14bfc5
--- /dev/null
+++ b/apache-kafka-2/src/main/java/com/baeldung/kafka/headers/KafkaMessageHeaders.java
@@ -0,0 +1,88 @@
+package com.baeldung.kafka.headers;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.common.header.Header;
+import org.apache.kafka.common.header.Headers;
+import org.apache.kafka.common.header.internals.RecordHeader;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class KafkaMessageHeaders {
+
+ private static Logger logger = LoggerFactory.getLogger(KafkaMessageHeaders.class);
+
+ private static String TOPIC = "baeldung";
+ private static String MESSAGE_KEY = "message";
+ private static String MESSAGE_VALUE = "Hello World";
+ private static String HEADER_KEY = "website";
+ private static String HEADER_VALUE = "baeldung.com";
+
+ private static KafkaProducer producer;
+ private static KafkaConsumer consumer;
+
+ public static void main(String[] args) {
+ setup();
+
+ publishMessageWithCustomHeaders();
+
+ consumeMessageWithCustomHeaders();
+ }
+
+ private static void consumeMessageWithCustomHeaders() {
+ consumer.subscribe(Arrays.asList(TOPIC));
+
+ ConsumerRecords records = consumer.poll(Duration.ofMinutes(1));
+ for (ConsumerRecord record : records) {
+ logger.info(record.key());
+ logger.info(record.value());
+
+ Headers headers = record.headers();
+ for (Header header : headers) {
+ logger.info(header.key());
+ logger.info(new String(header.value()));
+ }
+ }
+ }
+
+ private static void publishMessageWithCustomHeaders() {
+ List headers = new ArrayList<>();
+ headers.add(new RecordHeader(HEADER_KEY, HEADER_VALUE.getBytes()));
+
+ ProducerRecord record1 = new ProducerRecord<>(TOPIC, null, MESSAGE_KEY, MESSAGE_VALUE, headers);
+ producer.send(record1);
+
+ ProducerRecord record2 = new ProducerRecord<>(TOPIC, null, System.currentTimeMillis(), MESSAGE_KEY, MESSAGE_VALUE, headers);
+ producer.send(record2);
+ }
+
+ private static void setup() {
+ Properties producerProperties = new Properties();
+ producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
+ producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
+ producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
+
+ Properties consumerProperties = new Properties();
+ consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
+ consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+ consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+ consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
+
+ producer = new KafkaProducer<>(producerProperties);
+ consumer = new KafkaConsumer<>(consumerProperties);
+ }
+
+}
diff --git a/apache-kafka-2/src/test/java/com/baeldung/kafka/headers/KafkaMessageHeadersLiveTest.java b/apache-kafka-2/src/test/java/com/baeldung/kafka/headers/KafkaMessageHeadersLiveTest.java
new file mode 100644
index 0000000000..42cc572e07
--- /dev/null
+++ b/apache-kafka-2/src/test/java/com/baeldung/kafka/headers/KafkaMessageHeadersLiveTest.java
@@ -0,0 +1,104 @@
+package com.baeldung.kafka.headers;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+import org.apache.kafka.clients.consumer.ConsumerConfig;
+import org.apache.kafka.clients.consumer.ConsumerRecord;
+import org.apache.kafka.clients.consumer.ConsumerRecords;
+import org.apache.kafka.clients.consumer.KafkaConsumer;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.ProducerConfig;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.apache.kafka.clients.producer.RecordMetadata;
+import org.apache.kafka.common.header.Header;
+import org.apache.kafka.common.header.Headers;
+import org.apache.kafka.common.header.internals.RecordHeader;
+import org.apache.kafka.common.serialization.StringDeserializer;
+import org.apache.kafka.common.serialization.StringSerializer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.testcontainers.containers.KafkaContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+// This live test needs a Docker Daemon running so that a kafka container can be created
+
+@Testcontainers
+public class KafkaMessageHeadersLiveTest {
+
+ private static String TOPIC = "baeldung";
+ private static String MESSAGE_KEY = "message";
+ private static String MESSAGE_VALUE = "Hello World";
+ private static String HEADER_KEY = "website";
+ private static String HEADER_VALUE = "baeldung.com";
+
+ private static KafkaProducer producer;
+ private static KafkaConsumer consumer;
+
+ @Container
+ private static final KafkaContainer KAFKA_CONTAINER = new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:latest"));
+
+ @BeforeAll
+ static void setup() {
+ KAFKA_CONTAINER.addExposedPort(9092);
+
+ Properties producerProperties = new Properties();
+ producerProperties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
+ producerProperties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
+ producerProperties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
+
+ Properties consumerProperties = new Properties();
+ consumerProperties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CONTAINER.getBootstrapServers());
+ consumerProperties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+ consumerProperties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
+ consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, "ConsumerGroup1");
+
+ producer = new KafkaProducer<>(producerProperties);
+ consumer = new KafkaConsumer<>(consumerProperties);
+ }
+
+ @AfterAll
+ static void destroy() {
+ KAFKA_CONTAINER.stop();
+ }
+
+ @Test
+ void givenAMessageWithCustomHeaders_whenPublishedToKafkaAndConsumed_thenCheckForCustomHeaders() throws ExecutionException, InterruptedException {
+ List headers = new ArrayList<>();
+ headers.add(new RecordHeader(HEADER_KEY, HEADER_VALUE.getBytes()));
+
+ ProducerRecord record1 = new ProducerRecord<>(TOPIC, null, MESSAGE_KEY, MESSAGE_VALUE, headers);
+ Future future = producer.send(record1);
+
+ RecordMetadata metadata = future.get();
+
+ assertNotNull(metadata);
+
+ consumer.subscribe(Arrays.asList(TOPIC));
+
+ ConsumerRecords records = consumer.poll(Duration.ofMinutes(1));
+ for (ConsumerRecord record : records) {
+ assertEquals(MESSAGE_KEY, record.key());
+ assertEquals(MESSAGE_VALUE, record.value());
+
+ Headers consumedHeaders = record.headers();
+ assertNotNull(consumedHeaders);
+
+ for (Header header : consumedHeaders) {
+ assertEquals(HEADER_KEY, header.key());
+ assertEquals(HEADER_VALUE, new String(header.value()));
+ }
+ }
+ }
+}
diff --git a/apache-kafka/pom.xml b/apache-kafka/pom.xml
index 7bde041f32..494bc94961 100644
--- a/apache-kafka/pom.xml
+++ b/apache-kafka/pom.xml
@@ -35,12 +35,12 @@
org.apache.flink
- flink-connector-kafka-0.11_2.11
+ flink-connector-kafka
${flink.version}
org.apache.flink
- flink-streaming-java_2.11
+ flink-streaming-java
${flink.version}
@@ -67,7 +67,7 @@
org.apache.flink
- flink-test-utils_2.11
+ flink-test-utils
${flink.version}
test
@@ -163,11 +163,28 @@
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ --add-opens java.base/java.time=ALL-UNNAMED
+ --add-opens
+ java.base/java.nio=ALL-UNNAMED
+ --add-opens java.base/java.util=ALL-UNNAMED
+
+
+
+
+
+
- 2.8.0
+ 3.4.0
1.15.3
1.15.3
- 1.5.0
+ 1.16.1
3.0.0
2.4.8
0.8.1-spark3.0-s_2.12
diff --git a/apache-kafka/src/main/java/com/baeldung/flink/FlinkDataPipeline.java b/apache-kafka/src/main/java/com/baeldung/flink/FlinkDataPipeline.java
index 4502b628b2..8d15b79a63 100644
--- a/apache-kafka/src/main/java/com/baeldung/flink/FlinkDataPipeline.java
+++ b/apache-kafka/src/main/java/com/baeldung/flink/FlinkDataPipeline.java
@@ -9,8 +9,8 @@ import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
-import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011;
-import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011;
+import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
+import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import static com.baeldung.flink.connector.Consumers.*;
import static com.baeldung.flink.connector.Producers.*;
@@ -25,12 +25,12 @@ public class FlinkDataPipeline {
StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
- FlinkKafkaConsumer011 flinkKafkaConsumer = createStringConsumerForTopic(inputTopic, address, consumerGroup);
+ FlinkKafkaConsumer flinkKafkaConsumer = createStringConsumerForTopic(inputTopic, address, consumerGroup);
flinkKafkaConsumer.setStartFromEarliest();
DataStream stringInputStream = environment.addSource(flinkKafkaConsumer);
- FlinkKafkaProducer011 flinkKafkaProducer = createStringProducer(outputTopic, address);
+ FlinkKafkaProducer flinkKafkaProducer = createStringProducer(outputTopic, address);
stringInputStream.map(new WordsCapitalizer())
.addSink(flinkKafkaProducer);
@@ -48,11 +48,11 @@ public class FlinkDataPipeline {
environment.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
- FlinkKafkaConsumer011 flinkKafkaConsumer = createInputMessageConsumer(inputTopic, kafkaAddress, consumerGroup);
+ FlinkKafkaConsumer flinkKafkaConsumer = createInputMessageConsumer(inputTopic, kafkaAddress, consumerGroup);
flinkKafkaConsumer.setStartFromEarliest();
flinkKafkaConsumer.assignTimestampsAndWatermarks(new InputMessageTimestampAssigner());
- FlinkKafkaProducer011 flinkKafkaProducer = createBackupProducer(outputTopic, kafkaAddress);
+ FlinkKafkaProducer flinkKafkaProducer = createBackupProducer(outputTopic, kafkaAddress);
DataStream inputMessagesStream = environment.addSource(flinkKafkaConsumer);
diff --git a/apache-kafka/src/main/java/com/baeldung/flink/connector/Consumers.java b/apache-kafka/src/main/java/com/baeldung/flink/connector/Consumers.java
index c72cb8a2d6..358c9627f7 100644
--- a/apache-kafka/src/main/java/com/baeldung/flink/connector/Consumers.java
+++ b/apache-kafka/src/main/java/com/baeldung/flink/connector/Consumers.java
@@ -3,26 +3,26 @@ package com.baeldung.flink.connector;
import com.baeldung.flink.model.InputMessage;
import com.baeldung.flink.schema.InputMessageDeserializationSchema;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
-import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011;
+import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import java.util.Properties;
public class Consumers {
- public static FlinkKafkaConsumer011 createStringConsumerForTopic(String topic, String kafkaAddress, String kafkaGroup) {
+ public static FlinkKafkaConsumer createStringConsumerForTopic(String topic, String kafkaAddress, String kafkaGroup) {
Properties props = new Properties();
props.setProperty("bootstrap.servers", kafkaAddress);
props.setProperty("group.id", kafkaGroup);
- FlinkKafkaConsumer011 consumer = new FlinkKafkaConsumer011<>(topic, new SimpleStringSchema(), props);
+ FlinkKafkaConsumer consumer = new FlinkKafkaConsumer<>(topic, new SimpleStringSchema(), props);
return consumer;
}
- public static FlinkKafkaConsumer011 createInputMessageConsumer(String topic, String kafkaAddress, String kafkaGroup) {
+ public static FlinkKafkaConsumer createInputMessageConsumer(String topic, String kafkaAddress, String kafkaGroup) {
Properties properties = new Properties();
properties.setProperty("bootstrap.servers", kafkaAddress);
properties.setProperty("group.id", kafkaGroup);
- FlinkKafkaConsumer011 consumer = new FlinkKafkaConsumer011(topic, new InputMessageDeserializationSchema(), properties);
+ FlinkKafkaConsumer consumer = new FlinkKafkaConsumer(topic, new InputMessageDeserializationSchema(), properties);
return consumer;
}
diff --git a/apache-kafka/src/main/java/com/baeldung/flink/connector/Producers.java b/apache-kafka/src/main/java/com/baeldung/flink/connector/Producers.java
index 8e6f3f8f37..a4cb2d70c2 100644
--- a/apache-kafka/src/main/java/com/baeldung/flink/connector/Producers.java
+++ b/apache-kafka/src/main/java/com/baeldung/flink/connector/Producers.java
@@ -3,15 +3,15 @@ package com.baeldung.flink.connector;
import com.baeldung.flink.model.Backup;
import com.baeldung.flink.schema.BackupSerializationSchema;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
-import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011;
+import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
public class Producers {
- public static FlinkKafkaProducer011 createStringProducer(String topic, String kafkaAddress) {
- return new FlinkKafkaProducer011<>(kafkaAddress, topic, new SimpleStringSchema());
+ public static FlinkKafkaProducer createStringProducer(String topic, String kafkaAddress) {
+ return new FlinkKafkaProducer<>(kafkaAddress, topic, new SimpleStringSchema());
}
- public static FlinkKafkaProducer011 createBackupProducer(String topic, String kafkaAddress) {
- return new FlinkKafkaProducer011(kafkaAddress, topic, new BackupSerializationSchema());
+ public static FlinkKafkaProducer createBackupProducer(String topic, String kafkaAddress) {
+ return new FlinkKafkaProducer(kafkaAddress, topic, new BackupSerializationSchema());
}
}
diff --git a/apache-libraries/pom.xml b/apache-libraries/pom.xml
index b6418e6a04..c1def03bee 100644
--- a/apache-libraries/pom.xml
+++ b/apache-libraries/pom.xml
@@ -188,13 +188,13 @@
1.8.2
2.45.0
- 1.1.2
- 1.1.0.Final
- 1.2.0
+ 2.0.6
+ 2.0.1.Final
+ 1.2.15
3.10.0
- 1.2.1
- 1.2.1
- 1.2.1
+ 1.2.15
+ 1.2.15
+ 1.2.15
1.8.4
2.1.1-incubating
3.4.11
diff --git a/apache-libraries/src/test/java/com/baeldung/apache/beam/intro/WordCountUnitTest.java b/apache-libraries/src/test/java/com/baeldung/apache/beam/intro/WordCountIntegrationTest.java
similarity index 91%
rename from apache-libraries/src/test/java/com/baeldung/apache/beam/intro/WordCountUnitTest.java
rename to apache-libraries/src/test/java/com/baeldung/apache/beam/intro/WordCountIntegrationTest.java
index 77287066ac..5d51d8e5fa 100644
--- a/apache-libraries/src/test/java/com/baeldung/apache/beam/intro/WordCountUnitTest.java
+++ b/apache-libraries/src/test/java/com/baeldung/apache/beam/intro/WordCountIntegrationTest.java
@@ -7,7 +7,7 @@ import org.junit.Test;
import com.baeldung.apache.beam.intro.WordCount;
-public class WordCountUnitTest {
+public class WordCountIntegrationTest {
@Test
public void givenInputFile_whenWordCountRuns_thenJobFinishWithoutError() {
diff --git a/apache-poi/pom.xml b/apache-poi/pom.xml
index 546eedec5b..78781cf215 100644
--- a/apache-poi/pom.xml
+++ b/apache-poi/pom.xml
@@ -30,6 +30,16 @@
+
+ org.dhatim
+ fastexcel
+ ${fastexcel.version}
+
+
+ org.dhatim
+ fastexcel-reader
+ ${fastexcel.version}
+
@@ -52,6 +62,7 @@
5.2.0
1.0.6
+ 0.15.3
3.2.0
diff --git a/apache-poi/src/main/java/com/baeldung/fastexcel/FastexcelHelper.java b/apache-poi/src/main/java/com/baeldung/fastexcel/FastexcelHelper.java
new file mode 100644
index 0000000000..9d6041b66e
--- /dev/null
+++ b/apache-poi/src/main/java/com/baeldung/fastexcel/FastexcelHelper.java
@@ -0,0 +1,63 @@
+package com.baeldung.fastexcel;
+
+import org.dhatim.fastexcel.Workbook;
+import org.dhatim.fastexcel.Worksheet;
+import org.dhatim.fastexcel.reader.Cell;
+import org.dhatim.fastexcel.reader.ReadableWorkbook;
+import org.dhatim.fastexcel.reader.Row;
+import org.dhatim.fastexcel.reader.Sheet;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Stream;
+
+public class FastexcelHelper {
+
+ public Map> readExcel(String fileLocation) throws IOException {
+ Map> data = new HashMap<>();
+
+ try (FileInputStream file = new FileInputStream(fileLocation); ReadableWorkbook wb = new ReadableWorkbook(file)) {
+ Sheet sheet = wb.getFirstSheet();
+ try (Stream rows = sheet.openStream()) {
+ rows.forEach(r -> {
+ data.put(r.getRowNum(), new ArrayList<>());
+
+ for (Cell cell : r) {
+ data.get(r.getRowNum()).add(cell.getRawValue());
+ }
+ });
+ }
+ }
+
+ return data;
+ }
+
+ public void writeExcel() throws IOException {
+ File currDir = new File(".");
+ String path = currDir.getAbsolutePath();
+ String fileLocation = path.substring(0, path.length() - 1) + "fastexcel.xlsx";
+
+ try (OutputStream os = Files.newOutputStream(Paths.get(fileLocation)); Workbook wb = new Workbook(os, "MyApplication", "1.0")) {
+ Worksheet ws = wb.newWorksheet("Sheet 1");
+
+ ws.width(0, 25);
+ ws.width(1, 15);
+
+ ws.range(0, 0, 0, 1).style().fontName("Arial").fontSize(16).bold().fillColor("3366FF").set();
+ ws.value(0, 0, "Name");
+ ws.value(0, 1, "Age");
+
+ ws.range(2, 0, 2, 1).style().wrapText(true).set();
+ ws.value(2, 0, "John Smith");
+ ws.value(2, 1, 20L);
+ }
+ }
+}
diff --git a/apache-poi/src/test/java/com/baeldung/fastexcel/FastexcelIntegrationTest.java b/apache-poi/src/test/java/com/baeldung/fastexcel/FastexcelIntegrationTest.java
new file mode 100644
index 0000000000..a36c06e41f
--- /dev/null
+++ b/apache-poi/src/test/java/com/baeldung/fastexcel/FastexcelIntegrationTest.java
@@ -0,0 +1,49 @@
+package com.baeldung.fastexcel;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+
+public class FastexcelIntegrationTest {
+
+ private FastexcelHelper fastexcelHelper;
+ private static String FILE_NAME = "fastexcel.xlsx";
+ private String fileLocation;
+
+ @Before
+ public void generateExcelFile() throws IOException {
+
+ File currDir = new File(".");
+ String path = currDir.getAbsolutePath();
+ fileLocation = path.substring(0, path.length() - 1) + FILE_NAME;
+
+ fastexcelHelper = new FastexcelHelper();
+ fastexcelHelper.writeExcel();
+ }
+
+ @Test
+ public void whenParsingExcelFile_thenCorrect() throws IOException {
+ Map> data = fastexcelHelper.readExcel(fileLocation);
+
+ assertEquals("Name", data.get(1).get(0));
+ assertEquals("Age", data.get(1).get(1));
+
+ assertEquals("John Smith", data.get(3).get(0));
+ assertEquals("20", data.get(3).get(1));
+ }
+
+ @After
+ public void cleanup() {
+ File testFile = new File(fileLocation);
+ if (testFile.exists()) {
+ testFile.delete();
+ }
+ }
+}
diff --git a/apache-spark/pom.xml b/apache-spark/pom.xml
index 9e61e1340d..b5e97ee03d 100644
--- a/apache-spark/pom.xml
+++ b/apache-spark/pom.xml
@@ -7,7 +7,6 @@
1.0-SNAPSHOT
apache-spark
jar
- http://maven.apache.org
com.baeldung
diff --git a/aws-modules/aws-lambda/.gitignore b/aws-modules/aws-lambda-modules/.gitignore
similarity index 100%
rename from aws-modules/aws-lambda/.gitignore
rename to aws-modules/aws-lambda-modules/.gitignore
diff --git a/aws-modules/aws-lambda/README.md b/aws-modules/aws-lambda-modules/README.md
similarity index 100%
rename from aws-modules/aws-lambda/README.md
rename to aws-modules/aws-lambda-modules/README.md
diff --git a/aws-modules/aws-lambda/lambda/pom.xml b/aws-modules/aws-lambda-modules/lambda-function/pom.xml
similarity index 96%
rename from aws-modules/aws-lambda/lambda/pom.xml
rename to aws-modules/aws-lambda-modules/lambda-function/pom.xml
index 8e47bab4be..9fff7d1d9a 100644
--- a/aws-modules/aws-lambda/lambda/pom.xml
+++ b/aws-modules/aws-lambda-modules/lambda-function/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
- lambda
+ lambda-function
0.1.0-SNAPSHOT
- lambda
+ lambda-function
jar
com.baeldung
- aws-lambda
+ aws-lambda-modules
1.0.0-SNAPSHOT
diff --git a/aws-modules/aws-lambda/lambda/sam-templates/template-implicit.yaml b/aws-modules/aws-lambda-modules/lambda-function/sam-templates/template-implicit.yaml
similarity index 100%
rename from aws-modules/aws-lambda/lambda/sam-templates/template-implicit.yaml
rename to aws-modules/aws-lambda-modules/lambda-function/sam-templates/template-implicit.yaml
diff --git a/aws-modules/aws-lambda/lambda/sam-templates/template-inline-swagger.yaml b/aws-modules/aws-lambda-modules/lambda-function/sam-templates/template-inline-swagger.yaml
similarity index 100%
rename from aws-modules/aws-lambda/lambda/sam-templates/template-inline-swagger.yaml
rename to aws-modules/aws-lambda-modules/lambda-function/sam-templates/template-inline-swagger.yaml
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/LambdaMethodHandler.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/LambdaRequestHandler.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/LambdaRequestStreamHandler.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/apigateway/APIDemoHandler.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/apigateway/model/Person.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/apigateway/model/Person.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/apigateway/model/Person.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/dynamodb/SavePersonHandler.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonRequest.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java b/aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/java/com/baeldung/lambda/dynamodb/bean/PersonResponse.java
diff --git a/aws-modules/aws-lambda/lambda/src/main/resources/logback.xml b/aws-modules/aws-lambda-modules/lambda-function/src/main/resources/logback.xml
similarity index 100%
rename from aws-modules/aws-lambda/lambda/src/main/resources/logback.xml
rename to aws-modules/aws-lambda-modules/lambda-function/src/main/resources/logback.xml
diff --git a/aws-modules/aws-lambda/pom.xml b/aws-modules/aws-lambda-modules/pom.xml
similarity index 67%
rename from aws-modules/aws-lambda/pom.xml
rename to aws-modules/aws-lambda-modules/pom.xml
index bdd295c007..9886ff58d2 100644
--- a/aws-modules/aws-lambda/pom.xml
+++ b/aws-modules/aws-lambda-modules/pom.xml
@@ -3,8 +3,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- aws-lambda
- aws-lambda
+ aws-lambda-modules
+ aws-lambda-modules
pom
@@ -14,9 +14,9 @@
- lambda
- shipping-tracker/ShippingFunction
- todo-reminder/ToDoFunction
+ lambda-function
+ shipping-tracker-lambda/ShippingFunction
+ todo-reminder-lambda/ToDoFunction
\ No newline at end of file
diff --git a/aws-modules/aws-lambda/shipping-tracker/.gitignore b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/.gitignore
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/.gitignore
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/.gitignore
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/pom.xml b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml
similarity index 93%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/pom.xml
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml
index c36c81375d..abd22ea50c 100644
--- a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/pom.xml
+++ b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/pom.xml
@@ -2,7 +2,6 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
- com.baeldung
ShippingFunction
1.0
ShippingFunction
@@ -10,7 +9,7 @@
com.baeldung
- aws-lambda
+ aws-lambda-modules
1.0.0-SNAPSHOT
../../
@@ -69,8 +68,8 @@
- 1.8
- 1.8
+ 11
+ 11
5.4.21.Final
1.2.0
3.1.0
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/App.java b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/App.java
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/App.java
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/App.java
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Checkin.java b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Checkin.java
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Checkin.java
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Checkin.java
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Consignment.java b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Consignment.java
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Consignment.java
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Consignment.java
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Item.java b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Item.java
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Item.java
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/Item.java
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingDao.java b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingDao.java
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingDao.java
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingDao.java
diff --git a/aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingService.java b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingService.java
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingService.java
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/ShippingFunction/src/main/java/com/baeldung/lambda/shipping/ShippingService.java
diff --git a/aws-modules/aws-lambda/shipping-tracker/template.yaml b/aws-modules/aws-lambda-modules/shipping-tracker-lambda/template.yaml
similarity index 100%
rename from aws-modules/aws-lambda/shipping-tracker/template.yaml
rename to aws-modules/aws-lambda-modules/shipping-tracker-lambda/template.yaml
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/pom.xml b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml
similarity index 89%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/pom.xml
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml
index cb6dd08d1e..04295e1ab1 100644
--- a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/pom.xml
+++ b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/pom.xml
@@ -8,6 +8,13 @@
ToDoFunction
jar
+
+ com.baeldung
+ aws-lambda-modules
+ 1.0.0-SNAPSHOT
+ ../../
+
+
com.amazonaws
@@ -101,16 +108,16 @@
- 1.8
- 1.8
+ 11
+ 11
1.2.1
3.6.0
- 1.1.0
+ 1.2.1
1.2.0
2.13.2
11.2
- 5.0.1
- 1.2.0
+ 5.1.0
+ 2.0.2
4.1.0
3.19.0
5.8.1
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/App.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/App.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/App.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/App.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostApi.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostApi.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostApi.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostApi.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostItem.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostItem.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostItem.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/PostItem.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoApi.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoApi.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoApi.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoApi.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoItem.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoItem.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoItem.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/api/ToDoItem.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Config.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Config.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Config.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Config.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Credentials.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Credentials.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Credentials.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Credentials.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/ExecutionContext.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/ExecutionContext.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/ExecutionContext.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/ExecutionContext.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Services.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Services.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Services.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/config/Services.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/PostService.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/PostService.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/PostService.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/PostService.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/ToDoReaderService.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/ToDoReaderService.java
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/ToDoReaderService.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/java/com/baeldung/lambda/todo/service/ToDoReaderService.java
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/resources/configuration.yml b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/resources/configuration.yml
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/resources/configuration.yml
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/resources/configuration.yml
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/resources/log4j2.xml b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/resources/log4j2.xml
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/main/resources/log4j2.xml
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/main/resources/log4j2.xml
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/test/java/com/baeldung/lambda/todo/AppTest.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/test/java/com/baeldung/lambda/todo/AppUnitTest.java
similarity index 98%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/test/java/com/baeldung/lambda/todo/AppTest.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/test/java/com/baeldung/lambda/todo/AppUnitTest.java
index cbdc8c22cb..952a773f69 100644
--- a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/test/java/com/baeldung/lambda/todo/AppTest.java
+++ b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/test/java/com/baeldung/lambda/todo/AppUnitTest.java
@@ -21,7 +21,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
@RunWith(MockitoJUnitRunner.class)
-public class AppTest {
+public class AppUnitTest {
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private Context mockContext;
diff --git a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/test/java/com/baeldung/lambda/todo/service/ToDoReaderServiceTest.java b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/test/java/com/baeldung/lambda/todo/service/ToDoReaderServiceUnitTest.java
similarity index 94%
rename from aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/test/java/com/baeldung/lambda/todo/service/ToDoReaderServiceTest.java
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/test/java/com/baeldung/lambda/todo/service/ToDoReaderServiceUnitTest.java
index 634c5257ff..dd5b52d073 100644
--- a/aws-modules/aws-lambda/todo-reminder/ToDoFunction/src/test/java/com/baeldung/lambda/todo/service/ToDoReaderServiceTest.java
+++ b/aws-modules/aws-lambda-modules/todo-reminder-lambda/ToDoFunction/src/test/java/com/baeldung/lambda/todo/service/ToDoReaderServiceUnitTest.java
@@ -7,7 +7,7 @@ import uk.org.webcompere.systemstubs.rules.SystemOutRule;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
-public class ToDoReaderServiceTest {
+public class ToDoReaderServiceUnitTest {
@Rule
public SystemOutRule systemOutRule = new SystemOutRule();
diff --git a/aws-modules/aws-lambda/todo-reminder/template.yaml b/aws-modules/aws-lambda-modules/todo-reminder-lambda/template.yaml
similarity index 100%
rename from aws-modules/aws-lambda/todo-reminder/template.yaml
rename to aws-modules/aws-lambda-modules/todo-reminder-lambda/template.yaml
diff --git a/aws-modules/aws-s3/README.md b/aws-modules/aws-s3/README.md
index efebf7d933..109a898405 100644
--- a/aws-modules/aws-s3/README.md
+++ b/aws-modules/aws-s3/README.md
@@ -6,4 +6,5 @@ This module contains articles about Simple Storage Service (S3) on AWS
- [AWS S3 with Java](https://www.baeldung.com/aws-s3-java)
- [Multipart Uploads in Amazon S3 with Java](https://www.baeldung.com/aws-s3-multipart-upload)
-- [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3)
\ No newline at end of file
+- [Using the JetS3t Java Client With Amazon S3](https://www.baeldung.com/jets3t-amazon-s3)
+- [Check if a Specified Key Exists in a Given S3 Bucket Using Java](https://www.baeldung.com/java-aws-s3-check-specified-key-exists)
diff --git a/aws-modules/pom.xml b/aws-modules/pom.xml
index 72c5017c32..02473815b5 100644
--- a/aws-modules/pom.xml
+++ b/aws-modules/pom.xml
@@ -15,7 +15,7 @@
aws-app-sync
- aws-lambda
+ aws-lambda-modules
aws-miscellaneous
aws-reactive
aws-s3
diff --git a/axon/pom.xml b/axon/pom.xml
index 42e32758ea..5eed742aab 100644
--- a/axon/pom.xml
+++ b/axon/pom.xml
@@ -95,6 +95,22 @@
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ --add-opens java.base/java.util=ALL-UNNAMED
+ --add-opens
+ java.base/java.util.concurrent=ALL-UNNAMED
+
+
+
+
+
+
4.6.3
3.4.8
diff --git a/azure/pom.xml b/azure/pom.xml
index 6a06282a71..aae84db0c6 100644
--- a/azure/pom.xml
+++ b/azure/pom.xml
@@ -122,6 +122,7 @@
${azure.containerRegistry}.azurecr.io
1.1.0
1.1.0
+ 3.3.2
\ No newline at end of file
diff --git a/checker-plugin/README.md b/checker-framework/README.md
similarity index 100%
rename from checker-plugin/README.md
rename to checker-framework/README.md
diff --git a/checker-plugin/pom.xml b/checker-framework/pom.xml
similarity index 97%
rename from checker-plugin/pom.xml
rename to checker-framework/pom.xml
index 28958db89d..a348745343 100644
--- a/checker-plugin/pom.xml
+++ b/checker-framework/pom.xml
@@ -3,11 +3,10 @@
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
- checker-plugin
+ checker-framework
1.0-SNAPSHOT
- checker-plugin
+ checker-framework
jar
- http://maven.apache.org
com.baeldung
diff --git a/checker-plugin/src/main/java/com/baeldung/typechecker/FakeNumExample.java b/checker-framework/src/main/java/com/baeldung/typechecker/FakeNumExample.java
similarity index 100%
rename from checker-plugin/src/main/java/com/baeldung/typechecker/FakeNumExample.java
rename to checker-framework/src/main/java/com/baeldung/typechecker/FakeNumExample.java
diff --git a/checker-plugin/src/main/java/com/baeldung/typechecker/FormatExample.java b/checker-framework/src/main/java/com/baeldung/typechecker/FormatExample.java
similarity index 100%
rename from checker-plugin/src/main/java/com/baeldung/typechecker/FormatExample.java
rename to checker-framework/src/main/java/com/baeldung/typechecker/FormatExample.java
diff --git a/checker-plugin/src/main/java/com/baeldung/typechecker/KeyForExample.java b/checker-framework/src/main/java/com/baeldung/typechecker/KeyForExample.java
similarity index 100%
rename from checker-plugin/src/main/java/com/baeldung/typechecker/KeyForExample.java
rename to checker-framework/src/main/java/com/baeldung/typechecker/KeyForExample.java
diff --git a/checker-plugin/src/main/java/com/baeldung/typechecker/MonotonicNotNullExample.java b/checker-framework/src/main/java/com/baeldung/typechecker/MonotonicNotNullExample.java
similarity index 100%
rename from checker-plugin/src/main/java/com/baeldung/typechecker/MonotonicNotNullExample.java
rename to checker-framework/src/main/java/com/baeldung/typechecker/MonotonicNotNullExample.java
diff --git a/checker-plugin/src/main/java/com/baeldung/typechecker/NonNullExample.java b/checker-framework/src/main/java/com/baeldung/typechecker/NonNullExample.java
similarity index 100%
rename from checker-plugin/src/main/java/com/baeldung/typechecker/NonNullExample.java
rename to checker-framework/src/main/java/com/baeldung/typechecker/NonNullExample.java
diff --git a/checker-plugin/src/main/java/com/baeldung/typechecker/RegexExample.java b/checker-framework/src/main/java/com/baeldung/typechecker/RegexExample.java
similarity index 100%
rename from checker-plugin/src/main/java/com/baeldung/typechecker/RegexExample.java
rename to checker-framework/src/main/java/com/baeldung/typechecker/RegexExample.java
diff --git a/checker-plugin/src/main/resources/logback.xml b/checker-framework/src/main/resources/logback.xml
similarity index 100%
rename from checker-plugin/src/main/resources/logback.xml
rename to checker-framework/src/main/resources/logback.xml
diff --git a/clojure/ring/.gitignore b/clojure-modules/clojure-ring/.gitignore
similarity index 100%
rename from clojure/ring/.gitignore
rename to clojure-modules/clojure-ring/.gitignore
diff --git a/clojure/ring/README.md b/clojure-modules/clojure-ring/README.md
similarity index 100%
rename from clojure/ring/README.md
rename to clojure-modules/clojure-ring/README.md
diff --git a/clojure/ring/project.clj b/clojure-modules/clojure-ring/project.clj
similarity index 100%
rename from clojure/ring/project.clj
rename to clojure-modules/clojure-ring/project.clj
diff --git a/clojure/ring/src/ring/core.clj b/clojure-modules/clojure-ring/src/ring/core.clj
similarity index 100%
rename from clojure/ring/src/ring/core.clj
rename to clojure-modules/clojure-ring/src/ring/core.clj
diff --git a/core-groovy-modules/core-groovy-2/README.md b/core-groovy-modules/core-groovy-2/README.md
index 9f81ac6c16..f128b43092 100644
--- a/core-groovy-modules/core-groovy-2/README.md
+++ b/core-groovy-modules/core-groovy-2/README.md
@@ -14,4 +14,4 @@ This module contains articles about core Groovy concepts
- [A Quick Guide to Working with Web Services in Groovy](https://www.baeldung.com/groovy-web-services)
- [Categories in Groovy](https://www.baeldung.com/groovy-categories)
- [How to Determine the Data Type in Groovy](https://www.baeldung.com/groovy-determine-data-type)
-- [[<-- Prev]](/core-groovy)
+- [[<-- Prev]](/core-groovy-modules/core-groovy)
diff --git a/core-groovy-modules/core-groovy-2/pom.xml b/core-groovy-modules/core-groovy-2/pom.xml
index 2b864ec7a1..de750daf0f 100644
--- a/core-groovy-modules/core-groovy-2/pom.xml
+++ b/core-groovy-modules/core-groovy-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-groovy-2
- 1.0-SNAPSHOT
core-groovy-2
jar
@@ -83,7 +82,7 @@
org.codehaus.groovy
groovy-eclipse-batch
- ${groovy.version}-01
+ ${groovy-eclipse-batch.version}
@@ -153,19 +152,12 @@
-
-
- maven_central
- Maven Central
- https://repo.maven.apache.org/maven2/
-
-
-
1.1.3
- 3.1.0
- 3.8.0
- 3.3.0-01
+ 3.4.2
+ 3.8.1
+ 3.7.0
+ 3.0.8-01
diff --git a/core-groovy-modules/core-groovy-collections/pom.xml b/core-groovy-modules/core-groovy-collections/pom.xml
index 6d43ce7d18..08589f54e3 100644
--- a/core-groovy-modules/core-groovy-collections/pom.xml
+++ b/core-groovy-modules/core-groovy-collections/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-groovy-collections
- 1.0-SNAPSHOT
core-groovy-collections
jar
@@ -111,13 +110,4 @@
-
-
- maven_central
- Maven Central
- https://repo.maven.apache.org/maven2/
-
-
-
-
diff --git a/core-groovy-modules/core-groovy-strings/pom.xml b/core-groovy-modules/core-groovy-strings/pom.xml
index fac0f25219..ac68849431 100644
--- a/core-groovy-modules/core-groovy-strings/pom.xml
+++ b/core-groovy-modules/core-groovy-strings/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-groovy-strings
- 1.0-SNAPSHOT
core-groovy-strings
jar
@@ -101,12 +100,4 @@
-
-
- maven_central
- Maven Central
- https://repo.maven.apache.org/maven2/
-
-
-
diff --git a/core-groovy-modules/core-groovy/pom.xml b/core-groovy-modules/core-groovy/pom.xml
index cf6cca9e18..6668f62235 100644
--- a/core-groovy-modules/core-groovy/pom.xml
+++ b/core-groovy-modules/core-groovy/pom.xml
@@ -3,9 +3,7 @@
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
-
core-groovy
- 1.0-SNAPSHOT
core-groovy
jar
@@ -102,12 +100,4 @@
-
-
- maven_central
- Maven Central
- https://repo.maven.apache.org/maven2/
-
-
-
diff --git a/core-groovy-modules/pom.xml b/core-groovy-modules/pom.xml
index 2d1120e435..6faa7f94c8 100644
--- a/core-groovy-modules/pom.xml
+++ b/core-groovy-modules/pom.xml
@@ -21,12 +21,12 @@
- 3.0.8
- 3.0.8
- 3.0.8
- 2.4.0
+ 3.0.15
+ 3.0.15
+ 3.0.15
+ 2.7.1
2.3-groovy-3.0
- 1.6
+ 2.1.0
diff --git a/core-java-modules/core-java-10/pom.xml b/core-java-modules/core-java-10/pom.xml
index e2ac8db919..7eccb098a0 100644
--- a/core-java-modules/core-java-10/pom.xml
+++ b/core-java-modules/core-java-10/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-10
- 0.1.0-SNAPSHOT
core-java-10
jar
diff --git a/core-java-modules/core-java-11-2/pom.xml b/core-java-modules/core-java-11-2/pom.xml
index 64a486b5c4..4647814048 100644
--- a/core-java-modules/core-java-11-2/pom.xml
+++ b/core-java-modules/core-java-11-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-11-2
- 0.1.0-SNAPSHOT
core-java-11-2
jar
diff --git a/core-java-modules/core-java-11-3/pom.xml b/core-java-modules/core-java-11-3/pom.xml
index ccccae5ba1..22db9e62ab 100644
--- a/core-java-modules/core-java-11-3/pom.xml
+++ b/core-java-modules/core-java-11-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-11-3
- 0.1.0-SNAPSHOT
core-java-11-3
jar
@@ -14,7 +13,7 @@
1.0.0-SNAPSHOT
../../pom.xml
-
+
com.google.code.gson
diff --git a/core-java-modules/core-java-11/pom.xml b/core-java-modules/core-java-11/pom.xml
index 28a218c400..d0c2c0acaa 100644
--- a/core-java-modules/core-java-11/pom.xml
+++ b/core-java-modules/core-java-11/pom.xml
@@ -4,10 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-11
- 0.1.0-SNAPSHOT
core-java-11
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-12/pom.xml b/core-java-modules/core-java-12/pom.xml
index 9f95b1bc3f..ba6dfc62bc 100644
--- a/core-java-modules/core-java-12/pom.xml
+++ b/core-java-modules/core-java-12/pom.xml
@@ -4,10 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-12
- 0.1.0-SNAPSHOT
core-java-12
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-13/pom.xml b/core-java-modules/core-java-13/pom.xml
index 9e42838971..11d6ee7007 100644
--- a/core-java-modules/core-java-13/pom.xml
+++ b/core-java-modules/core-java-13/pom.xml
@@ -3,12 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.baeldung
core-java-13
- 0.1.0-SNAPSHOT
core-java-13
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-14/README.md b/core-java-modules/core-java-14/README.md
index 97be9391fb..7260891f7a 100644
--- a/core-java-modules/core-java-14/README.md
+++ b/core-java-modules/core-java-14/README.md
@@ -13,3 +13,4 @@ This module contains articles about Java 14.
- [New Features in Java 14](https://www.baeldung.com/java-14-new-features)
- [Java 14 Record vs. Lombok](https://www.baeldung.com/java-record-vs-lombok)
- [Record vs. Final Class in Java](https://www.baeldung.com/java-record-vs-final-class)
+- [Custom Constructor in Java Records](https://www.baeldung.com/java-records-custom-constructor)
diff --git a/core-java-modules/core-java-14/pom.xml b/core-java-modules/core-java-14/pom.xml
index f78edd622a..9f48c0b8b2 100644
--- a/core-java-modules/core-java-14/pom.xml
+++ b/core-java-modules/core-java-14/pom.xml
@@ -6,7 +6,6 @@
core-java-14
core-java-14
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordsCustomConstructors/StudentClassic.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordsCustomConstructors/StudentClassic.java
new file mode 100644
index 0000000000..cfaa3e1cd4
--- /dev/null
+++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordsCustomConstructors/StudentClassic.java
@@ -0,0 +1,61 @@
+package org.example;
+
+import java.util.Objects;
+
+public class StudentClassic {
+ private String name;
+ private int rollNo;
+ private int marks;
+
+ public StudentClassic(String name, int rollNo, int marks) {
+ this.name = name;
+ this.rollNo = rollNo;
+ this.marks = marks;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getRollNo() {
+ return rollNo;
+ }
+
+ public int getMarks() {
+ return marks;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setRollNo(int rollNo) {
+ this.rollNo = rollNo;
+ }
+
+ public void setMarks(int marks) {
+ this.marks = marks;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ StudentClassic that = (StudentClassic) o;
+ return rollNo == that.rollNo && marks == that.marks && Objects.equals(name, that.name);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, rollNo, marks);
+ }
+
+ @Override
+ public String toString() {
+ return "StudentClassic{" +
+ "name='" + name + '\'' +
+ ", rollNo=" + rollNo +
+ ", marks=" + marks +
+ '}';
+ }
+}
diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordsCustomConstructors/StudentRecord.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordsCustomConstructors/StudentRecord.java
new file mode 100644
index 0000000000..84633c5c5e
--- /dev/null
+++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordsCustomConstructors/StudentRecord.java
@@ -0,0 +1,19 @@
+package org.example;
+
+import java.util.Comparator;
+import java.util.List;
+
+public record StudentRecord(String name, int rollNo, int marks) {
+ public StudentRecord(String name){
+ this(name, 0,0);
+ }
+ public StudentRecord {
+ if (marks < 0 || marks > 100) {
+ throw new IllegalArgumentException("Marks should be between 0 and 100.");
+ }
+ if (name == null) {
+ throw new IllegalArgumentException("Name cannot be null");
+ }
+ }
+}
+
diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordsCustomConstructors/StudentRecordV2.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordsCustomConstructors/StudentRecordV2.java
new file mode 100644
index 0000000000..07b2193fcc
--- /dev/null
+++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordsCustomConstructors/StudentRecordV2.java
@@ -0,0 +1,22 @@
+package org.example;
+
+record StudentRecordV2(String name, int rollNo, int marks, char grade) {
+ public StudentRecordV2(String name, int rollNo, int marks) {
+ this(name, rollNo, marks, calculateGrade(marks));
+ }
+
+ private static char calculateGrade(int marks) {
+ if (marks >= 90) {
+ return 'A';
+ } else if (marks >= 80) {
+ return 'B';
+ } else if (marks >= 70) {
+ return 'C';
+ } else if (marks >= 60) {
+ return 'D';
+ } else {
+ return 'F';
+ }
+ }
+}
+
diff --git a/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordsCustomConstructors/StudentRecordV3.java b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordsCustomConstructors/StudentRecordV3.java
new file mode 100644
index 0000000000..b1035d5b10
--- /dev/null
+++ b/core-java-modules/core-java-14/src/main/java/com/baeldung/java14/recordsCustomConstructors/StudentRecordV3.java
@@ -0,0 +1,11 @@
+package org.example;
+
+import java.util.UUID;
+
+record StudentRecordV3(String name, int rollNo, int marks, String id) {
+
+ public StudentRecordV3(String name, int rollNo, int marks) {
+ this(name, rollNo, marks, UUID.randomUUID().toString());
+ }
+}
+
diff --git a/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/recordsCustomConstructors/StudentRecordJUnitTest.java b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/recordsCustomConstructors/StudentRecordJUnitTest.java
new file mode 100644
index 0000000000..3d932541ba
--- /dev/null
+++ b/core-java-modules/core-java-14/src/test/java/com/baeldung/java14/recordsCustomConstructors/StudentRecordJUnitTest.java
@@ -0,0 +1,37 @@
+import org.example.StudentRecord;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+public class StudentRecordJUnitTest {
+
+ @Test
+ public void givenStudentRecordData_whenCreated_thenStudentPropertiesMatch() {
+ StudentRecord s1 = new StudentRecord("John", 1, 90);
+ StudentRecord s2 = new StudentRecord("Jane", 2, 80);
+ assertEquals("John", s1.name());
+ assertEquals(1, s1.rollNo());
+ assertEquals(90, s1.marks());
+ assertEquals("Jane", s2.name());
+ assertEquals(2, s2.rollNo());
+ assertEquals(80, s2.marks());
+ }
+ @Test
+ public void givenStudentRecordsList_whenSortingDataWithName_thenStudentsSorted(){
+ List studentRecords = List.of(
+ new StudentRecord("Dana", 1, 85),
+ new StudentRecord("Jim", 2, 90),
+ new StudentRecord("Jane", 3, 80)
+ );
+
+ List mutableStudentRecords = new ArrayList<>(studentRecords);
+ mutableStudentRecords.sort(Comparator.comparing(StudentRecord::name));
+
+ List sortedStudentRecords = List.copyOf(mutableStudentRecords);
+ assertEquals("Jane", sortedStudentRecords.get(1).name());
+ }
+}
diff --git a/core-java-modules/core-java-15/pom.xml b/core-java-modules/core-java-15/pom.xml
index a4923054ac..059e2cc8f3 100644
--- a/core-java-modules/core-java-15/pom.xml
+++ b/core-java-modules/core-java-15/pom.xml
@@ -6,7 +6,6 @@
core-java-15
core-java-15
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-16/pom.xml b/core-java-modules/core-java-16/pom.xml
index a2c0d4855b..f8d287880a 100644
--- a/core-java-modules/core-java-16/pom.xml
+++ b/core-java-modules/core-java-16/pom.xml
@@ -4,10 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-16
- 0.1.0-SNAPSHOT
core-java-16
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-17/README.md b/core-java-modules/core-java-17/README.md
index 9f39b0289f..1af860b7c4 100644
--- a/core-java-modules/core-java-17/README.md
+++ b/core-java-modules/core-java-17/README.md
@@ -6,3 +6,4 @@
- [New Features in Java 17](https://www.baeldung.com/java-17-new-features)
- [Random Number Generators in Java 17](https://www.baeldung.com/java-17-random-number-generators)
- [Sealed Classes and Interfaces in Java](https://www.baeldung.com/java-sealed-classes-interfaces)
+- [Migrate From Java 8 to Java 17](https://www.baeldung.com/java-migrate-8-to-17)
diff --git a/core-java-modules/core-java-17/pom.xml b/core-java-modules/core-java-17/pom.xml
index bc949d9050..e2d854be44 100644
--- a/core-java-modules/core-java-17/pom.xml
+++ b/core-java-modules/core-java-17/pom.xml
@@ -4,10 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-17
- 0.1.0-SNAPSHOT
core-java-17
jar
- http://maven.apache.org
com.baeldung
diff --git a/core-java-modules/core-java-19/README.md b/core-java-modules/core-java-19/README.md
index 6a9c6c7fdd..68244d9f91 100644
--- a/core-java-modules/core-java-19/README.md
+++ b/core-java-modules/core-java-19/README.md
@@ -1,3 +1,4 @@
## Relevant Articles
- [Record Patterns in Java 19](https://www.baeldung.com/java-19-record-patterns)
- [Structured Concurrency in Java 19](https://www.baeldung.com/java-structured-concurrency)
+- [Possible Root Causes for High CPU Usage in Java](https://www.baeldung.com/java-high-cpu-usage-causes)
diff --git a/core-java-modules/core-java-19/pom.xml b/core-java-modules/core-java-19/pom.xml
index 096b13e679..930b37391c 100644
--- a/core-java-modules/core-java-19/pom.xml
+++ b/core-java-modules/core-java-19/pom.xml
@@ -1,21 +1,17 @@
+ 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
+ core-java-19
+ core-java-19
+
com.baeldung.core-java-modules
core-java-modules
0.0.1-SNAPSHOT
- core-java-19
-
-
- 19
- 19
- UTF-8
-
@@ -30,4 +26,10 @@
+
+ 19
+ 19
+ UTF-8
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-19/src/main/java/com/baeldung/highcpu/Application.java b/core-java-modules/core-java-19/src/main/java/com/baeldung/highcpu/Application.java
new file mode 100644
index 0000000000..82162406b3
--- /dev/null
+++ b/core-java-modules/core-java-19/src/main/java/com/baeldung/highcpu/Application.java
@@ -0,0 +1,20 @@
+package com.baeldung.highcpu;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.function.IntUnaryOperator;
+import java.util.stream.IntStream;
+
+public class Application {
+
+ static List generateList() {
+ return IntStream.range(0, 10000000).parallel().map(IntUnaryOperator.identity()).collect(LinkedList::new, List::add, List::addAll);
+ }
+
+ public static void main(String[] args) {
+ List list = generateList();
+ long start = System.nanoTime();
+ int value = list.get(9500000);
+ System.out.printf("Found value %d in %d nanos\n", value, (System.nanoTime() - start));
+ }
+}
diff --git a/core-java-modules/core-java-20/README.md b/core-java-modules/core-java-20/README.md
new file mode 100644
index 0000000000..aba4e9e240
--- /dev/null
+++ b/core-java-modules/core-java-20/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Scoped Values in Java 20](https://www.baeldung.com/java-20-scoped-values)
diff --git a/core-java-modules/core-java-20/pom.xml b/core-java-modules/core-java-20/pom.xml
new file mode 100644
index 0000000000..9562a41b1c
--- /dev/null
+++ b/core-java-modules/core-java-20/pom.xml
@@ -0,0 +1,65 @@
+
+
+ 4.0.0
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+ core-java-20
+
+
+ 20
+ 20
+ UTF-8
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ 20
+
+ --enable-preview
+ --add-modules=jdk.incubator.concurrent
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+ --enable-preview --add-modules=jdk.incubator.concurrent
+
+
+
+
+
+
+
+ jakarta.servlet
+ jakarta.servlet-api
+ 6.0.0
+ provided
+
+
+ org.assertj
+ assertj-core
+ 3.24.2
+ test
+
+
+ org.mockito
+ mockito-junit-jupiter
+ 5.2.0
+ test
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Controller.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Controller.java
new file mode 100644
index 0000000000..92edc57e48
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Controller.java
@@ -0,0 +1,33 @@
+package com.baeldung.scopedvalues.classic;
+
+import com.baeldung.scopedvalues.data.Data;
+import com.baeldung.scopedvalues.data.User;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Optional;
+
+public class Controller {
+
+ private final Service service = new Service();
+
+ public void processRequest(HttpServletRequest request, HttpServletResponse response, User loggedInUser) {
+ Optional data = service.getData(request, loggedInUser);
+ if (data.isPresent()) {
+ try {
+ PrintWriter out = response.getWriter();
+ response.setContentType("application/json");
+ out.print(data.get());
+ out.flush();
+ response.setStatus(200);
+ } catch (IOException e) {
+ response.setStatus(500);
+ }
+ } else {
+ response.setStatus(400);
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Repository.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Repository.java
new file mode 100644
index 0000000000..3085b3be58
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Repository.java
@@ -0,0 +1,16 @@
+package com.baeldung.scopedvalues.classic;
+
+import com.baeldung.scopedvalues.data.Data;
+import com.baeldung.scopedvalues.data.User;
+
+import java.util.Optional;
+
+public class Repository {
+
+ public Optional getData(String id, User user) {
+ return user.isAdmin()
+ ? Optional.of(new Data(id, "Title 1", "Description 1"))
+ : Optional.empty();
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Server.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Server.java
new file mode 100644
index 0000000000..71afa9e675
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Server.java
@@ -0,0 +1,42 @@
+package com.baeldung.scopedvalues.classic;
+
+import com.baeldung.scopedvalues.data.User;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.*;
+
+public class Server {
+
+ private static final List AUTHENTICATED_USERS = List.of(
+ new User("1", "admin", "123456", true),
+ new User("2", "user", "123456", false)
+ );
+ private final Controller controller = new Controller();
+ private final ExecutorService executor = Executors.newFixedThreadPool(5);
+
+ public void serve(HttpServletRequest request, HttpServletResponse response) throws InterruptedException, ExecutionException {
+ Optional user = authenticateUser(request);
+ if (user.isPresent()) {
+ Future> future = executor.submit(() ->
+ controller.processRequest(request, response, user.get()));
+ future.get();
+ } else {
+ response.setStatus(401);
+ }
+ }
+
+ private Optional authenticateUser(HttpServletRequest request) {
+ return AUTHENTICATED_USERS.stream()
+ .filter(user -> checkUserPassword(user, request))
+ .findFirst();
+ }
+
+ private boolean checkUserPassword(User user, HttpServletRequest request) {
+ return user.name().equals(request.getParameter("user_name"))
+ && user.password().equals(request.getParameter("user_pw"));
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Service.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Service.java
new file mode 100644
index 0000000000..011f793001
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/classic/Service.java
@@ -0,0 +1,18 @@
+package com.baeldung.scopedvalues.classic;
+
+import com.baeldung.scopedvalues.data.Data;
+import com.baeldung.scopedvalues.data.User;
+import jakarta.servlet.http.HttpServletRequest;
+
+import java.util.Optional;
+
+public class Service {
+
+ private final Repository repository = new Repository();
+
+ public Optional getData(HttpServletRequest request, User loggedInUser) {
+ String id = request.getParameter("data_id");
+ return repository.getData(id, loggedInUser);
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/data/Data.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/data/Data.java
new file mode 100644
index 0000000000..70be41c1ac
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/data/Data.java
@@ -0,0 +1,3 @@
+package com.baeldung.scopedvalues.data;
+
+public record Data(String id, String title, String description) {}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/data/User.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/data/User.java
new file mode 100644
index 0000000000..22e0a4243f
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/data/User.java
@@ -0,0 +1,3 @@
+package com.baeldung.scopedvalues.data;
+
+public record User(String id, String name, String password, boolean isAdmin) {}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Controller.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Controller.java
new file mode 100644
index 0000000000..239ee88f19
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Controller.java
@@ -0,0 +1,37 @@
+package com.baeldung.scopedvalues.scoped;
+
+import com.baeldung.scopedvalues.data.Data;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jdk.incubator.concurrent.ScopedValue;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Optional;
+
+public class Controller {
+
+ private final Service internalService = new Service();
+
+ public void processRequest(HttpServletRequest request, HttpServletResponse response) {
+ Optional data = internalService.getData(request);
+
+ ScopedValue.where(Server.LOGGED_IN_USER, null)
+ .run(internalService::extractData);
+
+ if (data.isPresent()) {
+ try {
+ PrintWriter out = response.getWriter();
+ response.setContentType("application/json");
+ out.print(data.get());
+ out.flush();
+ response.setStatus(200);
+ } catch (IOException e) {
+ response.setStatus(500);
+ }
+ } else {
+ response.setStatus(400);
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Repository.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Repository.java
new file mode 100644
index 0000000000..a40191eb3c
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Repository.java
@@ -0,0 +1,17 @@
+package com.baeldung.scopedvalues.scoped;
+
+import com.baeldung.scopedvalues.data.Data;
+import com.baeldung.scopedvalues.data.User;
+
+import java.util.Optional;
+
+public class Repository {
+
+ public Optional getData(String id) {
+ User loggedInUser = Server.LOGGED_IN_USER.get();
+ return loggedInUser.isAdmin()
+ ? Optional.of(new Data(id, "Title 1", "Description 1"))
+ : Optional.empty();
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Server.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Server.java
new file mode 100644
index 0000000000..559e4efd56
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Server.java
@@ -0,0 +1,41 @@
+package com.baeldung.scopedvalues.scoped;
+
+import com.baeldung.scopedvalues.data.User;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jdk.incubator.concurrent.ScopedValue;
+
+import java.util.List;
+import java.util.Optional;
+
+public class Server {
+
+ private static final List AUTHENTICATED_USERS = List.of(
+ new User("1", "admin", "123456", true),
+ new User("2", "user", "123456", false)
+ );
+ public final static ScopedValue LOGGED_IN_USER = ScopedValue.newInstance();
+ private final Controller controller = new Controller();
+
+ public void serve(HttpServletRequest request, HttpServletResponse response) {
+ Optional user = authenticateUser(request);
+ if (user.isPresent()) {
+ ScopedValue.where(LOGGED_IN_USER, user.get())
+ .run(() -> controller.processRequest(request, response));
+ } else {
+ response.setStatus(401);
+ }
+ }
+
+ private Optional authenticateUser(HttpServletRequest request) {
+ return AUTHENTICATED_USERS.stream()
+ .filter(user -> checkUserPassword(user, request))
+ .findFirst();
+ }
+
+ private boolean checkUserPassword(User user, HttpServletRequest request) {
+ return user.name().equals(request.getParameter("user_name"))
+ && user.password().equals(request.getParameter("user_pw"));
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Service.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Service.java
new file mode 100644
index 0000000000..e35d98cae5
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/Service.java
@@ -0,0 +1,23 @@
+package com.baeldung.scopedvalues.scoped;
+
+import com.baeldung.scopedvalues.data.Data;
+import com.baeldung.scopedvalues.data.User;
+import jakarta.servlet.http.HttpServletRequest;
+
+import java.util.Optional;
+
+public class Service {
+
+ private final Repository repository = new Repository();
+
+ public Optional getData(HttpServletRequest request) {
+ String id = request.getParameter("data_id");
+ return repository.getData(id);
+ }
+
+ public void extractData() {
+ User loggedInUser = Server.LOGGED_IN_USER.get();
+ assert loggedInUser == null;
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Controller.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Controller.java
new file mode 100644
index 0000000000..e4742c0998
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Controller.java
@@ -0,0 +1,44 @@
+package com.baeldung.scopedvalues.scoped.inheriting;
+
+import com.baeldung.scopedvalues.data.Data;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jdk.incubator.concurrent.StructuredTaskScope;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Optional;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+public class Controller {
+
+ private final InternalService internalService = new InternalService();
+ private final ExternalService externalService = new ExternalService();
+
+ public void processRequest(HttpServletRequest request, HttpServletResponse response) {
+ try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
+ Future> internalData = scope.fork(() -> internalService.getData(request));
+ Future externalData = scope.fork(externalService::getData);
+ try {
+ scope.join();
+ scope.throwIfFailed();
+
+ Optional data = internalData.resultNow();
+ if (data.isPresent()) {
+ PrintWriter out = response.getWriter();
+ response.setContentType("application/json");
+ out.println(data.get());
+ out.print(externalData.resultNow());
+ out.flush();
+ response.setStatus(200);
+ } else {
+ response.setStatus(400);
+ }
+ } catch (InterruptedException | ExecutionException | IOException e) {
+ response.setStatus(500);
+ }
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/ExternalService.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/ExternalService.java
new file mode 100644
index 0000000000..88fa4dfb74
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/ExternalService.java
@@ -0,0 +1,9 @@
+package com.baeldung.scopedvalues.scoped.inheriting;
+
+public class ExternalService {
+
+ public String getData() {
+ return "External data";
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/InternalService.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/InternalService.java
new file mode 100644
index 0000000000..ace46b254c
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/InternalService.java
@@ -0,0 +1,17 @@
+package com.baeldung.scopedvalues.scoped.inheriting;
+
+import com.baeldung.scopedvalues.data.Data;
+import jakarta.servlet.http.HttpServletRequest;
+
+import java.util.Optional;
+
+public class InternalService {
+
+ private final Repository repository = new Repository();
+
+ public Optional getData(HttpServletRequest request) {
+ String id = request.getParameter("data_id");
+ return repository.getData(id);
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Repository.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Repository.java
new file mode 100644
index 0000000000..22d18b2fac
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Repository.java
@@ -0,0 +1,17 @@
+package com.baeldung.scopedvalues.scoped.inheriting;
+
+import com.baeldung.scopedvalues.data.Data;
+import com.baeldung.scopedvalues.data.User;
+
+import java.util.Optional;
+
+public class Repository {
+
+ public Optional getData(String id) {
+ User loggedInUser = Server.LOGGED_IN_USER.get();
+ return loggedInUser.isAdmin()
+ ? Optional.of(new Data(id, "Title 1", "Description 1"))
+ : Optional.empty();
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Server.java b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Server.java
new file mode 100644
index 0000000000..5f04a1eedd
--- /dev/null
+++ b/core-java-modules/core-java-20/src/main/java/com/baeldung/scopedvalues/scoped/inheriting/Server.java
@@ -0,0 +1,41 @@
+package com.baeldung.scopedvalues.scoped.inheriting;
+
+import com.baeldung.scopedvalues.data.User;
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import jdk.incubator.concurrent.ScopedValue;
+
+import java.util.List;
+import java.util.Optional;
+
+public class Server {
+
+ private static final List AUTHENTICATED_USERS = List.of(
+ new User("1", "admin", "123456", true),
+ new User("2", "user", "123456", false)
+ );
+ public final static ScopedValue LOGGED_IN_USER = ScopedValue.newInstance();
+ private final Controller controller = new Controller();
+
+ public void serve(HttpServletRequest request, HttpServletResponse response) {
+ Optional user = authenticateUser(request);
+ if (user.isPresent()) {
+ ScopedValue.where(LOGGED_IN_USER, user.get())
+ .run(() -> controller.processRequest(request, response));
+ } else {
+ response.setStatus(401);
+ }
+ }
+
+ private Optional authenticateUser(HttpServletRequest request) {
+ return AUTHENTICATED_USERS.stream()
+ .filter(user -> checkUserPassword(user, request))
+ .findFirst();
+ }
+
+ private boolean checkUserPassword(User user, HttpServletRequest request) {
+ return user.name().equals(request.getParameter("user_name"))
+ && user.password().equals(request.getParameter("user_pw"));
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/classic/ServerUnitTest.java b/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/classic/ServerUnitTest.java
new file mode 100644
index 0000000000..e0b9366c22
--- /dev/null
+++ b/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/classic/ServerUnitTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.scopedvalues.classic;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.concurrent.ExecutionException;
+
+import static org.mockito.Mockito.*;
+import static org.assertj.core.api.Assertions.*;
+@ExtendWith(MockitoExtension.class)
+public class ServerUnitTest {
+
+ @Mock
+ private HttpServletRequest request;
+
+ @Mock
+ private HttpServletResponse response;
+
+ private final StringWriter writer = new StringWriter();
+
+ private final Server server = new Server();
+
+ @Test
+ void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws InterruptedException, IOException, ExecutionException {
+ when(request.getParameter("user_name")).thenReturn("admin");
+ when(request.getParameter("user_pw")).thenReturn("123456");
+ when(request.getParameter("data_id")).thenReturn("1");
+ when(response.getWriter()).thenReturn(new PrintWriter(writer));
+
+ server.serve(request, response);
+
+ assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]");
+ }
+
+ @Test
+ void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws InterruptedException, ExecutionException {
+ when(request.getParameter("user_name")).thenReturn("user");
+ when(request.getParameter("user_pw")).thenReturn("123456");
+
+ server.serve(request, response);
+
+ assertThat(writer.toString()).isEqualTo("");
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/scoped/ServerUnitTest.java b/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/scoped/ServerUnitTest.java
new file mode 100644
index 0000000000..034e6683e3
--- /dev/null
+++ b/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/scoped/ServerUnitTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.scopedvalues.scoped;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+public class ServerUnitTest {
+
+ @Mock
+ private HttpServletRequest request;
+
+ @Mock
+ private HttpServletResponse response;
+
+ private final StringWriter writer = new StringWriter();
+
+ private final Server server = new Server();
+
+ @Test
+ void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws IOException {
+ when(request.getParameter("user_name")).thenReturn("admin");
+ when(request.getParameter("user_pw")).thenReturn("123456");
+ when(request.getParameter("data_id")).thenReturn("1");
+ when(response.getWriter()).thenReturn(new PrintWriter(writer));
+
+ server.serve(request, response);
+
+ assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]");
+ }
+
+ @Test
+ void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws IOException {
+ when(request.getParameter("user_name")).thenReturn("user");
+ when(request.getParameter("user_pw")).thenReturn("123456");
+
+ server.serve(request, response);
+
+ assertThat(writer.toString()).isEqualTo("");
+ }
+
+}
diff --git a/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/scoped/inheriting/ServerUnitTest.java b/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/scoped/inheriting/ServerUnitTest.java
new file mode 100644
index 0000000000..230b017c18
--- /dev/null
+++ b/core-java-modules/core-java-20/src/test/java/com/baeldung/scopedvalues/scoped/inheriting/ServerUnitTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.scopedvalues.scoped.inheriting;
+
+import jakarta.servlet.http.HttpServletRequest;
+import jakarta.servlet.http.HttpServletResponse;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+public class ServerUnitTest {
+
+ @Mock
+ private HttpServletRequest request;
+
+ @Mock
+ private HttpServletResponse response;
+
+ private final StringWriter writer = new StringWriter();
+
+ private final Server server = new Server();
+
+ @Test
+ void givenMockedRequestWithAdminCredentials_whenServeMethodIsCalled_thenDataIsReturned() throws IOException {
+ when(request.getParameter("user_name")).thenReturn("admin");
+ when(request.getParameter("user_pw")).thenReturn("123456");
+ when(request.getParameter("data_id")).thenReturn("1");
+ when(response.getWriter()).thenReturn(new PrintWriter(writer));
+
+ server.serve(request, response);
+
+ assertThat(writer.toString()).isEqualTo("Data[id=1, title=Title 1, description=Description 1]\nExternal data");
+ }
+
+ @Test
+ void givenMockedRequestWithUserCredentials_whenServeMethodIsCalled_thenNoDataIsReturned() throws IOException {
+ when(request.getParameter("user_name")).thenReturn("user");
+ when(request.getParameter("user_pw")).thenReturn("123456");
+
+ server.serve(request, response);
+
+ assertThat(writer.toString()).isEqualTo("");
+ }
+
+}
diff --git a/core-java-modules/core-java-8-2/README.md b/core-java-modules/core-java-8-2/README.md
index c0bc63f21f..c723a827b1 100644
--- a/core-java-modules/core-java-8-2/README.md
+++ b/core-java-modules/core-java-8-2/README.md
@@ -10,4 +10,7 @@ This module contains articles about Java 8 core features
- [Interface With Default Methods vs Abstract Class](https://www.baeldung.com/java-interface-default-method-vs-abstract-class)
- [Convert Between Byte Array and UUID in Java](https://www.baeldung.com/java-byte-array-to-uuid)
- [Create a Simple “Rock-Paper-Scissors” Game in Java](https://www.baeldung.com/java-rock-paper-scissors)
+- [VarArgs vs Array Input Parameters in Java](https://www.baeldung.com/varargs-vs-array)
+- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)
+- [Java Helper vs. Utility Classes](https://www.baeldung.com/java-helper-vs-utility-classes)
- [[<-- Prev]](/core-java-modules/core-java-8)
diff --git a/core-java-modules/core-java-8-2/pom.xml b/core-java-modules/core-java-8-2/pom.xml
index 7db1e1ed4e..589e384613 100644
--- a/core-java-modules/core-java-8-2/pom.xml
+++ b/core-java-modules/core-java-8-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-8-2
- 0.1.0-SNAPSHOT
core-java-8-2
jar
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java
rename to core-java-modules/core-java-8-2/src/main/java/com/baeldung/anonymousclass/AnonymousClassExample.java
diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/helpervsutilityclasses/MyHelperClass.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/helpervsutilityclasses/MyHelperClass.java
new file mode 100644
index 0000000000..40b58bf200
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/helpervsutilityclasses/MyHelperClass.java
@@ -0,0 +1,40 @@
+package com.baeldung.helpervsutilityclasses;
+
+class MyHelperClass {
+ public double discount;
+ public MyHelperClass(double discount) {
+ if (discount > 0 && discount < 1) {
+ this.discount = discount;
+ }
+ }
+ public double discountedPrice(double price) {
+ return price - (price * discount);
+ }
+
+ public static int getMaxNumber(int[] numbers) {
+ if (numbers.length == 0) {
+ throw new IllegalArgumentException("Ensure array is not empty");
+ }
+ int max = numbers[0];
+ for (int i = 1; i < numbers.length; i++) {
+ if (numbers[i] > max) {
+ max = numbers[i];
+ }
+ }
+ return max;
+ }
+
+ public static int getMinNumber(int[] numbers) {
+ if (numbers.length == 0) {
+ throw new IllegalArgumentException("Ensure array is not empty");
+ }
+ int min = numbers[0];
+ for (int i = 1; i < numbers.length; i++) {
+ if (numbers[i] < min) {
+ min = numbers[i];
+ }
+ }
+ return min;
+ }
+
+}
diff --git a/core-java-modules/core-java-8-2/src/main/java/com/baeldung/helpervsutilityclasses/MyUtilityClass.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/helpervsutilityclasses/MyUtilityClass.java
new file mode 100644
index 0000000000..1f0075995c
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/helpervsutilityclasses/MyUtilityClass.java
@@ -0,0 +1,19 @@
+package com.baeldung.helpervsutilityclasses;
+
+public final class MyUtilityClass {
+
+ private MyUtilityClass(){}
+
+ public static String returnUpperCase(String stringInput) {
+ return stringInput.toUpperCase();
+ }
+
+ public static String returnLowerCase(String stringInput) {
+ return stringInput.toLowerCase();
+ }
+
+ public static String[] splitStringInput(String stringInput, String delimiter) {
+ return stringInput.split(delimiter);
+ }
+
+}
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/lambdaexpression/LambdaExpressionExample.java b/core-java-modules/core-java-8-2/src/main/java/com/baeldung/lambdaexpression/LambdaExpressionExample.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/lambdaexpression/LambdaExpressionExample.java
rename to core-java-modules/core-java-8-2/src/main/java/com/baeldung/lambdaexpression/LambdaExpressionExample.java
diff --git a/core-java-modules/core-java-8-2/src/test/java/com/baeldung/helpervsutilityclasses/MyHelperClassUnitTest.java b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/helpervsutilityclasses/MyHelperClassUnitTest.java
new file mode 100644
index 0000000000..a0c1afea52
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/helpervsutilityclasses/MyHelperClassUnitTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.helpervsutilityclasses;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class MyHelperClassUnitTest {
+
+ @Test
+ void whenCreatingHelperObject_thenHelperObjectShouldBeCreated() {
+ MyHelperClass myHelperClassObject = new MyHelperClass(0.10);
+ int[] numberArray = {15, 23, 66, 3, 51, 79};
+
+ assertNotNull(myHelperClassObject);
+
+ assertEquals(90, myHelperClassObject.discountedPrice(100.00));
+ assertEquals( 79, MyHelperClass.getMaxNumber(numberArray));
+ assertEquals(3, MyHelperClass.getMinNumber(numberArray));
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-8-2/src/test/java/com/baeldung/helpervsutilityclasses/MyUtilityClassUnitTest.java b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/helpervsutilityclasses/MyUtilityClassUnitTest.java
new file mode 100644
index 0000000000..8b29f51959
--- /dev/null
+++ b/core-java-modules/core-java-8-2/src/test/java/com/baeldung/helpervsutilityclasses/MyUtilityClassUnitTest.java
@@ -0,0 +1,15 @@
+package com.baeldung.helpervsutilityclasses;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class MyUtilityClassUnitTest {
+
+ @Test
+ void whenUsingUtilityMethods_thenAccessMethodsViaClassName(){
+ assertEquals( "INIUBONG", MyUtilityClass.returnUpperCase("iniubong"));
+ assertEquals("accra", MyUtilityClass.returnLowerCase("AcCrA"));
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-8-datetime-2/README.md b/core-java-modules/core-java-8-datetime-2/README.md
index f16563aacc..56f66c10fb 100644
--- a/core-java-modules/core-java-8-datetime-2/README.md
+++ b/core-java-modules/core-java-8-datetime-2/README.md
@@ -2,4 +2,5 @@
- [Generating Random Dates in Java](https://www.baeldung.com/java-random-dates)
- [Creating a LocalDate with Values in Java](https://www.baeldung.com/java-creating-localdate-with-values)
-- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
\ No newline at end of file
+- [Parsing Date Strings with Varying Formats](https://www.baeldung.com/java-parsing-dates-many-formats)
+- [[<-- Prev]](/core-java-modules/core-java-datetime-java8-1)
diff --git a/core-java-modules/core-java-8-datetime-2/pom.xml b/core-java-modules/core-java-8-datetime-2/pom.xml
index 9e54b0ee12..ce349d9dc3 100644
--- a/core-java-modules/core-java-8-datetime-2/pom.xml
+++ b/core-java-modules/core-java-8-datetime-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-8-datetime-2
- ${project.parent.version}
core-java-8-datetime-2
jar
diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateTimeFormat.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateTimeFormat.java
new file mode 100644
index 0000000000..a82f3bce2b
--- /dev/null
+++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateTimeFormat.java
@@ -0,0 +1,20 @@
+package com.baeldung.parsingDates;
+
+import java.util.Arrays;
+import java.util.List;
+import org.joda.time.LocalDate;
+import org.joda.time.format.DateTimeFormat;
+
+public class SimpleDateTimeFormat {
+
+ public static LocalDate parseDate(String date) {
+ List patternList = Arrays.asList("MM/dd/yyyy", "dd.MM.yyyy", "yyyy-MM-dd");
+ for (String pattern : patternList) {
+ try {
+ return DateTimeFormat.forPattern(pattern).parseLocalDate(date);
+ } catch (IllegalArgumentException e) {
+ }
+ }
+ return null;
+ }
+}
diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateTimeFormater.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateTimeFormater.java
new file mode 100644
index 0000000000..aa12038032
--- /dev/null
+++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateTimeFormater.java
@@ -0,0 +1,17 @@
+package com.baeldung.parsingDates;
+
+import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeFormatterBuilder;
+
+public class SimpleDateTimeFormater {
+
+ public static LocalDate parseDate(String date) {
+ DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
+ .append(DateTimeFormatter.ofPattern("[MM/dd/yyyy]" + "[dd-MM-yyyy]" + "[yyyy-MM-dd]"));
+
+ DateTimeFormatter dateTimeFormatter = dateTimeFormatterBuilder.toFormatter();
+
+ return LocalDate.parse(date, dateTimeFormatter);
+ }
+}
diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateUtils.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateUtils.java
new file mode 100644
index 0000000000..8a154d3cd8
--- /dev/null
+++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleDateUtils.java
@@ -0,0 +1,18 @@
+package com.baeldung.parsingDates;
+
+import java.text.ParseException;
+import java.util.Date;
+import org.apache.commons.lang3.time.DateUtils;
+
+public class SimpleDateUtils {
+
+ public static Date parseDate(String date) {
+ try {
+ return DateUtils.parseDateStrictly(date,
+ new String[]{"yyyy/MM/dd", "dd/MM/yyyy", "yyyy-MM-dd"});
+ } catch (ParseException ex) {
+ return null;
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleParseDate.java b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleParseDate.java
new file mode 100644
index 0000000000..cb024eea53
--- /dev/null
+++ b/core-java-modules/core-java-8-datetime-2/src/main/java/com/baeldung/parsingDates/SimpleParseDate.java
@@ -0,0 +1,19 @@
+package com.baeldung.parsingDates;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+
+public class SimpleParseDate {
+
+ public Date parseDate(String dateString, List formatStrings) {
+ for (String formatString : formatStrings) {
+ try {
+ return new SimpleDateFormat(formatString).parse(dateString);
+ } catch (ParseException e) {
+ }
+ }
+ return null;
+ }
+}
diff --git a/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/parsingDates/SimpleParseDateUnitTest.java b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/parsingDates/SimpleParseDateUnitTest.java
new file mode 100644
index 0000000000..d7cbb6a834
--- /dev/null
+++ b/core-java-modules/core-java-8-datetime-2/src/test/java/com/baeldung/parsingDates/SimpleParseDateUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.parsingDates;
+
+import com.baeldung.parsingDates.SimpleDateTimeFormat;
+import com.baeldung.parsingDates.SimpleDateTimeFormater;
+import com.baeldung.parsingDates.SimpleDateUtils;
+import com.baeldung.parsingDates.SimpleParseDate;
+import java.time.format.DateTimeParseException;
+import java.util.Arrays;
+import org.junit.*;
+import static org.junit.Assert.*;
+import org.joda.time.LocalDate;
+
+public class SimpleParseDateUnitTest {
+
+ @Test
+ public void whenInvalidInput_thenGettingUnexpectedResult() {
+ SimpleParseDate simpleParseDate = new SimpleParseDate();
+ String date = "2022-40-40";
+ assertEquals("Sat May 10 00:00:00 UTC 2025", simpleParseDate.parseDate(date, Arrays.asList("MM/dd/yyyy", "dd.MM.yyyy", "yyyy-MM-dd")).toString());
+ }
+
+ @Test
+ public void whenInvalidDate_thenAssertThrows() {
+ SimpleDateTimeFormater simpleDateTimeFormater = new SimpleDateTimeFormater();
+ assertEquals(java.time.LocalDate.parse("2022-12-04"), simpleDateTimeFormater.parseDate("2022-12-04"));
+ assertThrows(DateTimeParseException.class, () -> simpleDateTimeFormater.parseDate("2022-13-04"));
+ }
+
+ @Test
+ public void whenDateIsCorrect_thenParseCorrect() {
+ SimpleDateUtils simpleDateUtils = new SimpleDateUtils();
+ assertNull(simpleDateUtils.parseDate("53/10/2014"));
+ assertEquals("Wed Sep 10 00:00:00 UTC 2014", simpleDateUtils.parseDate("10/09/2014").toString());
+ }
+
+ @Test
+ public void whenDateIsCorrect_thenResultCorrect() {
+ SimpleDateTimeFormat simpleDateTimeFormat = new SimpleDateTimeFormat();
+ assertNull(simpleDateTimeFormat.parseDate("53/10/2014"));
+ assertEquals(LocalDate.parse("2014-10-10"), simpleDateTimeFormat.parseDate("2014-10-10"));
+ }
+
+}
diff --git a/core-java-modules/core-java-8-datetime/pom.xml b/core-java-modules/core-java-8-datetime/pom.xml
index 01ec6c0b76..481b1a6a69 100644
--- a/core-java-modules/core-java-8-datetime/pom.xml
+++ b/core-java-modules/core-java-8-datetime/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-8-datetime
- ${project.parent.version}
core-java-8-datetime
jar
diff --git a/core-java-modules/core-java-8/pom.xml b/core-java-modules/core-java-8/pom.xml
index 89925bdbbb..fff7b7f2f9 100644
--- a/core-java-modules/core-java-8/pom.xml
+++ b/core-java-modules/core-java-8/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-8
- 0.1.0-SNAPSHOT
core-java-8
jar
diff --git a/core-java-modules/core-java-9-improvements/pom.xml b/core-java-modules/core-java-9-improvements/pom.xml
index 56d4ccff9f..f6f13ff409 100644
--- a/core-java-modules/core-java-9-improvements/pom.xml
+++ b/core-java-modules/core-java-9-improvements/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-9-improvements
- 0.2-SNAPSHOT
core-java-9-improvements
diff --git a/core-java-modules/core-java-9-jigsaw/README.md b/core-java-modules/core-java-9-jigsaw/README.md
index cfffb86588..73905e6033 100644
--- a/core-java-modules/core-java-9-jigsaw/README.md
+++ b/core-java-modules/core-java-9-jigsaw/README.md
@@ -8,5 +8,5 @@ This module contains articles about Project Jigsaw and the Java Platform Module
- [A Guide to Java 9 Modularity](https://www.baeldung.com/java-9-modularity)
- [Java 9 java.lang.Module API](https://www.baeldung.com/java-9-module-api)
- [Java 9 Illegal Reflective Access Warning](https://www.baeldung.com/java-illegal-reflective-access)
-
+- [Java Modularity and Unit Testing](https://www.baeldung.com/java-modularity-unit-testing)
diff --git a/core-java-modules/core-java-9-jigsaw/compile-library-core-module.sh b/core-java-modules/core-java-9-jigsaw/compile-library-core-module.sh
new file mode 100644
index 0000000000..fa0d4d5f14
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/compile-library-core-module.sh
@@ -0,0 +1,2 @@
+#!/usr/bin/env bash
+javac -d mods/com.baeldung.library.core $(find library-core/src/main -name "*.java")
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/compile-library-core-tests.sh b/core-java-modules/core-java-9-jigsaw/compile-library-core-tests.sh
new file mode 100644
index 0000000000..751906103b
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/compile-library-core-tests.sh
@@ -0,0 +1,10 @@
+#!/usr/bin/env bash
+javac --class-path outDir/library-core/:\
+libs/junit-jupiter-engine-5.9.2.jar:\
+libs/junit-platform-engine-1.9.2.jar:\
+libs/apiguardian-api-1.1.2.jar:\
+libs/junit-jupiter-params-5.9.2.jar:\
+libs/junit-jupiter-api-5.9.2.jar:\
+libs/opentest4j-1.2.0.jar:\
+libs/junit-platform-commons-1.9.2.jar \
+-d outDir/library-test library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/compile-library-core-with-tests.sh b/core-java-modules/core-java-9-jigsaw/compile-library-core-with-tests.sh
new file mode 100644
index 0000000000..c873a9003c
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/compile-library-core-with-tests.sh
@@ -0,0 +1,13 @@
+#!/usr/bin/env bash
+javac --class-path libs/junit-jupiter-engine-5.9.2.jar:\
+libs/junit-platform-engine-1.9.2.jar:\
+libs/apiguardian-api-1.1.2.jar:\
+libs/junit-jupiter-params-5.9.2.jar:\
+libs/junit-jupiter-api-5.9.2.jar:\
+libs/opentest4j-1.2.0.jar:\
+libs/junit-platform-commons-1.9.2.jar \
+-d outDir/library-core \
+library-core/src/main/java/com/baeldung/library/core/Book.java \
+library-core/src/main/java/com/baeldung/library/core/Library.java \
+library-core/src/main/java/com/baeldung/library/core/Main.java \
+library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/compile-library-core.sh b/core-java-modules/core-java-9-jigsaw/compile-library-core.sh
new file mode 100644
index 0000000000..7531148d0f
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/compile-library-core.sh
@@ -0,0 +1,12 @@
+#!/usr/bin/env bash
+javac --class-path libs/junit-jupiter-engine-5.9.2.jar:\
+libs/junit-platform-engine-1.9.2.jar:\
+libs/apiguardian-api-1.1.2.jar:\
+libs/junit-jupiter-params-5.9.2.jar:\
+libs/junit-jupiter-api-5.9.2.jar:\
+libs/opentest4j-1.2.0.jar:\
+libs/junit-platform-commons-1.9.2.jar \
+-d outDir/library-core \
+library-core/src/main/java/com/baeldung/library/core/Book.java \
+library-core/src/main/java/com/baeldung/library/core/Library.java \
+library-core/src/main/java/com/baeldung/library/core/Main.java
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/compile-library-test-module.sh b/core-java-modules/core-java-9-jigsaw/compile-library-test-module.sh
new file mode 100644
index 0000000000..c6fd614fd0
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/compile-library-test-module.sh
@@ -0,0 +1,2 @@
+#!/usr/bin/env bash
+javac --module-path mods:libs -d mods/com.baeldung.library.test $(find library-test/src/test -name "*.java")
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/download-junit-dependencies.sh b/core-java-modules/core-java-9-jigsaw/download-junit-dependencies.sh
new file mode 100644
index 0000000000..64c72a5429
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/download-junit-dependencies.sh
@@ -0,0 +1,10 @@
+#!/usr/bin/env bash
+wget -P libs/ https://repo1.maven.org/maven2/org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-commons/1.9.2/junit-platform-commons-1.9.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-engine/1.9.2/junit-platform-engine-1.9.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-reporting/1.9.2/junit-platform-reporting-1.9.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-console/1.9.2/junit-platform-console-1.9.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/1.9.2/junit-platform-launcher-1.9.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/jupiter/junit-jupiter-engine/5.9.2/junit-jupiter-engine-5.9.2.jar /
+wget -P libs/ https://repo1.maven.org/maven2/org/junit/jupiter/junit-jupiter-params/5.9.2/junit-jupiter-params-5.9.2.jar
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/library-core/pom.xml b/core-java-modules/core-java-9-jigsaw/library-core/pom.xml
new file mode 100644
index 0000000000..b860d89932
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-core/pom.xml
@@ -0,0 +1,55 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ core-java-9-jigsaw
+ 0.2-SNAPSHOT
+
+
+ library-core
+
+
+ 19
+ 19
+ UTF-8
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter-api
+ 5.9.2
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ 5.9.2
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.8.1
+
+ 9
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 3.0.0-M5
+
+ false
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Book.java b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Book.java
new file mode 100644
index 0000000000..782de8fa10
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Book.java
@@ -0,0 +1,52 @@
+package com.baeldung.library.core;
+
+import java.util.Objects;
+
+public class Book {
+
+ private String title;
+ private String author;
+
+ public Book(String title, String author) {
+ this.title = title;
+ this.author = author;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public String getAuthor() {
+ return author;
+ }
+
+
+ @Override
+ public String toString() {
+ return "Book [title=" + title + ", author=" + author + "]";
+ }
+
+ @Override
+ public boolean equals(final Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ final Book book = (Book) o;
+
+ if (!Objects.equals(title, book.title)) {
+ return false;
+ }
+ return Objects.equals(author, book.author);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = title != null ? title.hashCode() : 0;
+ result = 31 * result + (author != null ? author.hashCode() : 0);
+ return result;
+ }
+}
diff --git a/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Library.java b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Library.java
new file mode 100644
index 0000000000..ee2225810d
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Library.java
@@ -0,0 +1,25 @@
+package com.baeldung.library.core;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class Library {
+
+ private List books = new ArrayList<>();
+
+ public void addBook(Book book) {
+ books.add(book);
+ }
+
+ public List getBooks() {
+ return books;
+ }
+
+ void removeBook(Book book) {
+ books.remove(book);
+ }
+
+ protected void removeBookByAuthor(String author) {
+ books.removeIf(book -> book.getAuthor().equals(author));
+ }
+}
diff --git a/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Main.java b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Main.java
new file mode 100644
index 0000000000..18839602c2
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/com/baeldung/library/core/Main.java
@@ -0,0 +1,16 @@
+package com.baeldung.library.core;
+
+public class Main {
+
+ public static void main(String[] args) {
+ Library library = new Library();
+ library.addBook(new Book("The Lord of the Rings", "J.R.R. Tolkien"));
+ library.addBook(new Book("The Hobbit", "J.R.R. Tolkien"));
+ library.addBook(new Book("The Silmarillion", "J.R.R. Tolkien"));
+ library.addBook(new Book("The Chronicles of Narnia", "C.S. Lewis"));
+ library.addBook(new Book("The Lion, the Witch and the Wardrobe", "C.S. Lewis"));
+ System.out.println("Welcome to our library!");
+ System.out.println("We have the following books:");
+ library.getBooks().forEach(System.out::println);
+ }
+}
diff --git a/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/module-info.java b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/module-info.java
new file mode 100644
index 0000000000..bdf88d8bc9
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-core/src/main/java/module-info.java
@@ -0,0 +1,3 @@
+module com.baeldung.library.core {
+ exports com.baeldung.library.core;
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java b/core-java-modules/core-java-9-jigsaw/library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java
new file mode 100644
index 0000000000..20a4889e8c
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-core/src/test/java/com/baeldung/library/core/LibraryUnitTest.java
@@ -0,0 +1,47 @@
+package com.baeldung.library.core;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class LibraryUnitTest {
+
+ @Test
+ void givenEmptyLibrary_whenAddABook_thenLibraryHasOneBook() {
+ Library library = new Library();
+ Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
+ library.addBook(theLordOfTheRings);
+ int expected = 1;
+ int actual = library.getBooks().size();
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ void givenTheLibraryWithABook_whenRemoveABook_thenLibraryIsEmpty() {
+ Library library = new Library();
+ Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
+ library.addBook(theLordOfTheRings);
+ library.removeBook(theLordOfTheRings);
+ int expected = 0;
+ int actual = library.getBooks().size();
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ void givenTheLibraryWithSeveralBook_whenRemoveABookByAuthor_thenLibraryHasNoBooksByTheAuthor() {
+ Library library = new Library();
+ Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
+ Book theHobbit = new Book("The Hobbit", "J.R.R. Tolkien");
+ Book theSilmarillion = new Book("The Silmarillion", "J.R.R. Tolkien");
+ Book theHungerGames = new Book("The Hunger Games", "Suzanne Collins");
+ library.addBook(theLordOfTheRings);
+ library.addBook(theHobbit);
+ library.addBook(theSilmarillion);
+ library.addBook(theHungerGames);
+ library.removeBookByAuthor("J.R.R. Tolkien");
+ int expected = 1;
+ int actual = library.getBooks().size();
+ assertEquals(expected, actual);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/com/baeldung/library/test/LibraryUnitTest.java b/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/com/baeldung/library/test/LibraryUnitTest.java
new file mode 100644
index 0000000000..31eae89bba
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/com/baeldung/library/test/LibraryUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.library.test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import com.baeldung.library.core.Book;
+import com.baeldung.library.core.Library;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import org.junit.jupiter.api.Test;
+
+class LibraryUnitTest {
+
+ @Test
+ void givenEmptyLibrary_whenAddABook_thenLibraryHasOneBook() {
+ Library library = new Library();
+ Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
+ library.addBook(theLordOfTheRings);
+ int expected = 1;
+ int actual = library.getBooks().size();
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ void givenTheLibraryWithABook_whenRemoveABook_thenLibraryIsEmpty()
+ throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
+ Library library = new Library();
+ Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
+ library.addBook(theLordOfTheRings);
+ Method removeBook = Library.class.getDeclaredMethod("removeBook", Book.class);
+ removeBook.setAccessible(true);
+ removeBook.invoke(library, theLordOfTheRings);
+ int expected = 0;
+ int actual = library.getBooks().size();
+ assertEquals(expected, actual);
+ }
+@Test
+void givenTheLibraryWithSeveralBook_whenRemoveABookByAuthor_thenLibraryHasNoBooksByTheAuthor() {
+ TestLibrary library = new TestLibrary();
+ Book theLordOfTheRings = new Book("The Lord of the Rings", "J.R.R. Tolkien");
+ Book theHobbit = new Book("The Hobbit", "J.R.R. Tolkien");
+ Book theSilmarillion = new Book("The Silmarillion", "J.R.R. Tolkien");
+ Book theHungerGames = new Book("The Hunger Games", "Suzanne Collins");
+ library.addBook(theLordOfTheRings);
+ library.addBook(theHobbit);
+ library.addBook(theSilmarillion);
+ library.addBook(theHungerGames);
+ library.removeBookByAuthor("J.R.R. Tolkien");
+ int expected = 1;
+ int actual = library.getBooks().size();
+ assertEquals(expected, actual);
+}
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/com/baeldung/library/test/TestLibrary.java b/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/com/baeldung/library/test/TestLibrary.java
new file mode 100644
index 0000000000..8ee3b0e3fe
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/com/baeldung/library/test/TestLibrary.java
@@ -0,0 +1,10 @@
+package com.baeldung.library.test;
+
+import com.baeldung.library.core.Library;
+
+public class TestLibrary extends Library {
+ @Override
+ public void removeBookByAuthor(final String author) {
+ super.removeBookByAuthor(author);
+ }
+}
diff --git a/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/module-info.java b/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/module-info.java
new file mode 100644
index 0000000000..8d60b574f2
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/library-test/src/test/java/module-info.java
@@ -0,0 +1,5 @@
+module com.baeldung.library.test {
+ requires com.baeldung.library.core;
+ requires org.junit.jupiter.api;
+ opens com.baeldung.library.test to org.junit.platform.commons;
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/pom.xml b/core-java-modules/core-java-9-jigsaw/pom.xml
index a26a88f4b0..288254b9cf 100644
--- a/core-java-modules/core-java-9-jigsaw/pom.xml
+++ b/core-java-modules/core-java-9-jigsaw/pom.xml
@@ -4,8 +4,11 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-9-jigsaw
- 0.2-SNAPSHOT
core-java-9-jigsaw
+ pom
+
+ library-core
+
com.baeldung
diff --git a/core-java-modules/core-java-9-jigsaw/run-library-core-module-with-patch.sh b/core-java-modules/core-java-9-jigsaw/run-library-core-module-with-patch.sh
new file mode 100644
index 0000000000..70772a3589
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/run-library-core-module-with-patch.sh
@@ -0,0 +1,7 @@
+#!/usr/bin/env bash
+java --module-path mods:libs \
+--add-modules com.baeldung.library.core \
+--add-opens com.baeldung.library.core/com.baeldung.library.core=org.junit.platform.commons \
+--add-reads com.baeldung.library.core=org.junit.jupiter.api \
+--patch-module com.baeldung.library.core=outDir/library-test \
+--module org.junit.platform.console --select-class com.baeldung.library.core.LibraryUnitTest
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/run-library-core-module.sh b/core-java-modules/core-java-9-jigsaw/run-library-core-module.sh
new file mode 100644
index 0000000000..f2bb976512
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/run-library-core-module.sh
@@ -0,0 +1,2 @@
+#!/usr/bin/env bash
+java --module-path mods --module com.baeldung.library.core/com.baeldung.library.core.Main
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/run-library-test-class-path.sh b/core-java-modules/core-java-9-jigsaw/run-library-test-class-path.sh
new file mode 100644
index 0000000000..73e3d504bf
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/run-library-test-class-path.sh
@@ -0,0 +1,5 @@
+#!/usr/bin/env bash
+java --module-path libs \
+org.junit.platform.console.ConsoleLauncher \
+--classpath ./outDir/library-core \
+--select-class com.baeldung.library.core.LibraryUnitTest
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-jigsaw/run-library-test-module-path.sh b/core-java-modules/core-java-9-jigsaw/run-library-test-module-path.sh
new file mode 100644
index 0000000000..08d149dbd7
--- /dev/null
+++ b/core-java-modules/core-java-9-jigsaw/run-library-test-module-path.sh
@@ -0,0 +1,5 @@
+#!/usr/bin/env bash
+java --module-path mods:libs \
+--add-modules com.baeldung.library.test \
+--add-opens com.baeldung.library.core/com.baeldung.library.core=com.baeldung.library.test \
+org.junit.platform.console.ConsoleLauncher --select-class com.baeldung.library.test.LibraryUnitTest
\ No newline at end of file
diff --git a/core-java-modules/core-java-9-new-features/pom.xml b/core-java-modules/core-java-9-new-features/pom.xml
index 78ffaff010..6821c9c340 100644
--- a/core-java-modules/core-java-9-new-features/pom.xml
+++ b/core-java-modules/core-java-9-new-features/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-9-new-features
- 0.2-SNAPSHOT
core-java-9-new-features
diff --git a/core-java-modules/core-java-9-streams/pom.xml b/core-java-modules/core-java-9-streams/pom.xml
index d3f81780d1..903194b3b3 100644
--- a/core-java-modules/core-java-9-streams/pom.xml
+++ b/core-java-modules/core-java-9-streams/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-9-streams
- 0.1.0-SNAPSHOT
core-java-9-streams
jar
diff --git a/core-java-modules/core-java-9/README.md b/core-java-modules/core-java-9/README.md
index 38965d88f1..bd7df0c8a6 100644
--- a/core-java-modules/core-java-9/README.md
+++ b/core-java-modules/core-java-9/README.md
@@ -5,7 +5,6 @@ This module contains articles about Java 9 core features
### Relevant Articles:
- [Method Handles in Java](https://www.baeldung.com/java-method-handles)
-- [Introduction to Chronicle Queue](https://www.baeldung.com/java-chronicle-queue)
- [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)
- [Immutable ArrayList in Java](https://www.baeldung.com/java-immutable-list)
diff --git a/core-java-modules/core-java-9/pom.xml b/core-java-modules/core-java-9/pom.xml
index 272af327cb..bcfdacdf1d 100644
--- a/core-java-modules/core-java-9/pom.xml
+++ b/core-java-modules/core-java-9/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-9
- 0.2-SNAPSHOT
core-java-9
diff --git a/core-java-modules/core-java-annotations/pom.xml b/core-java-modules/core-java-annotations/pom.xml
index a1f84ab563..6b1b9d802f 100644
--- a/core-java-modules/core-java-annotations/pom.xml
+++ b/core-java-modules/core-java-annotations/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-annotations
- 0.1.0-SNAPSHOT
core-java-annotations
jar
@@ -24,4 +23,12 @@
+
+
+ javax.annotation
+ javax.annotation-api
+ 1.3.2
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-annotations/src/main/java/com/baeldung/annotations/ClassWithSuppressWarningsNames.java b/core-java-modules/core-java-annotations/src/main/java/com/baeldung/annotations/ClassWithSuppressWarningsNames.java
index aad7cf49eb..d0a325a155 100644
--- a/core-java-modules/core-java-annotations/src/main/java/com/baeldung/annotations/ClassWithSuppressWarningsNames.java
+++ b/core-java-modules/core-java-annotations/src/main/java/com/baeldung/annotations/ClassWithSuppressWarningsNames.java
@@ -17,7 +17,7 @@ public class ClassWithSuppressWarningsNames implements Serializable {
list.add(Integer.valueOf(value));
}
- @SuppressWarnings("deprecated")
+ @SuppressWarnings("deprecation")
void suppressDeprecatedWarning() {
ClassWithSuppressWarningsNames cls = new ClassWithSuppressWarningsNames();
cls.deprecatedMethod(); // no warning here
diff --git a/core-java-modules/core-java-arrays-operations-basic/README.md b/core-java-modules/core-java-arrays-operations-basic/README.md
index 2e1268e00c..76f4044355 100644
--- a/core-java-modules/core-java-arrays-operations-basic/README.md
+++ b/core-java-modules/core-java-arrays-operations-basic/README.md
@@ -11,3 +11,5 @@ This module contains articles about Java array fundamentals. They assume no prev
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Extending an Array’s Length](https://www.baeldung.com/java-array-add-element-at-the-end)
- [Initializing a Boolean Array in Java](https://www.baeldung.com/java-initializing-boolean-array)
+- [Find the Index of an Element in a Java Array](https://www.baeldung.com/java-array-find-index)
+- [Comparing Two Byte Arrays in Java](https://www.baeldung.com/java-comparing-byte-arrays)
diff --git a/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/arrayindex/ArrayIndex.java b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/arrayindex/ArrayIndex.java
new file mode 100644
index 0000000000..596e0d424f
--- /dev/null
+++ b/core-java-modules/core-java-arrays-operations-basic/src/main/java/com/baeldung/arrayindex/ArrayIndex.java
@@ -0,0 +1,28 @@
+package com.baeldung.arrayindex;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.IntStream;
+
+class ArrayIndex {
+ static int forLoop(int[] numbers, int target) {
+ for (int index = 0; index < numbers.length; index++) {
+ if (numbers[index] == target) {
+ return index;
+ }
+ }
+ return -1;
+ }
+
+ static int listIndexOf(Integer[] numbers, int target) {
+ List list = Arrays.asList(numbers);
+ return list.indexOf(target);
+ }
+
+ static int intStream(int[] numbers, int target) {
+ return IntStream.range(0, numbers.length)
+ .filter(i -> numbers[i] == target)
+ .findFirst()
+ .orElse(-1);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/compare/CompareByteArraysUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/compare/CompareByteArraysUnitTest.java
new file mode 100644
index 0000000000..4274acf83d
--- /dev/null
+++ b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/array/compare/CompareByteArraysUnitTest.java
@@ -0,0 +1,39 @@
+package com.baeldung.array.compare;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.Arrays;
+
+import org.junit.jupiter.api.Test;
+
+public class CompareByteArraysUnitTest {
+ private final static String INPUT = "I am a magic string.";
+ private final static byte[] ARRAY1 = INPUT.getBytes();
+ private final static byte[] ARRAY2 = INPUT.getBytes();
+
+ @Test
+ void whenUsingEqualsSign_thenTwoArraysAreNotEqual() {
+ assertFalse(ARRAY1 == ARRAY2);
+ }
+
+ @Test
+ void whenUsingEquals_thenTwoArraysAreNotEqual() {
+ assertFalse(ARRAY1.equals(ARRAY2));
+ }
+
+ @Test
+ void whenUsingArrayEquals_thenTwoArraysAreEqual() {
+ assertTrue(Arrays.equals(ARRAY1, ARRAY2));
+ }
+
+ @Test
+ void whenComparingStringArrays_thenGetExpectedResult() {
+ String[] strArray1 = new String[] { "Java", "is", "great" };
+ String[] strArray2 = new String[] { "Java", "is", "great" };
+
+ assertFalse(strArray1 == strArray2);
+ assertFalse(strArray1.equals(strArray2));
+ assertTrue(Arrays.equals(strArray1, strArray2));
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/arrayindex/ArrayIndexUnitTest.java b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/arrayindex/ArrayIndexUnitTest.java
new file mode 100644
index 0000000000..84c868d5e0
--- /dev/null
+++ b/core-java-modules/core-java-arrays-operations-basic/src/test/java/com/baeldung/arrayindex/ArrayIndexUnitTest.java
@@ -0,0 +1,106 @@
+package com.baeldung.arrayindex;
+
+import static com.baeldung.arrayindex.ArrayIndex.forLoop;
+import static com.baeldung.arrayindex.ArrayIndex.intStream;
+import static com.baeldung.arrayindex.ArrayIndex.listIndexOf;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Arrays;
+
+import org.apache.commons.lang3.ArrayUtils;
+import org.junit.jupiter.api.Test;
+
+import com.google.common.primitives.Ints;
+
+class ArrayIndexUnitTest {
+
+ @Test
+ void givenIntegerArray_whenUseForLoop_thenWillGetElementIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(2, forLoop(numbers, 30));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseForLoop_thenWillGetElementMinusOneIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, forLoop(numbers, 100));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseIndexOf_thenWillGetElementIndex() {
+ Integer[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(2, listIndexOf(numbers, 30));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseIndexOf_thenWillGetElementMinusOneIndex() {
+ Integer[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, listIndexOf(numbers, 100));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseIntStream_thenWillGetElementIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(2, intStream(numbers, 30));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseIntStream_thenWillGetElementMinusOneIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, intStream(numbers, 100));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseBinarySearch_thenWillGetElementIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(2, Arrays.binarySearch(numbers, 30));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseBinarySearch_thenWillGetUpperBoundMinusIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-6, Arrays.binarySearch(numbers, 100));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseBinarySearch_thenWillGetInArrayMinusIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-2, Arrays.binarySearch(numbers, 15));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseBinarySearch_thenWillGetLowerBoundMinusIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, Arrays.binarySearch(numbers, -15));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseApacheCommons_thenWillGetElementIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(2, ArrayUtils.indexOf(numbers, 30));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseApacheCommonsStartingFromIndex_thenWillGetNegativeIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, ArrayUtils.indexOf(numbers, 30, 3));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseApacheCommons_thenWillGetElementMinusOneIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, ArrayUtils.indexOf(numbers, 100));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseGuavaInts_thenWillGetElementIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(2, Ints.indexOf(numbers, 30));
+ }
+
+ @Test
+ void givenIntegerArray_whenUseGuavaInts_thenWillGetElementMinusOneIndex() {
+ int[] numbers = { 10, 20, 30, 40, 50 };
+ assertEquals(-1, Ints.indexOf(numbers, 100));
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-booleans/README.md b/core-java-modules/core-java-booleans/README.md
new file mode 100644
index 0000000000..fe7068c6f4
--- /dev/null
+++ b/core-java-modules/core-java-booleans/README.md
@@ -0,0 +1,6 @@
+## Core Java Booleans
+
+This module contains articles about Java Booleans.
+
+### Relevant Articles:
+- [Convert Boolean to String in Java](https://www.baeldung.com/java-convert-boolean-to-string)
diff --git a/core-java-modules/core-java-booleans/pom.xml b/core-java-modules/core-java-booleans/pom.xml
new file mode 100644
index 0000000000..3b0c28208f
--- /dev/null
+++ b/core-java-modules/core-java-booleans/pom.xml
@@ -0,0 +1,16 @@
+
+
+ 4.0.0
+ core-java-booleans
+ core-java-booleans
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-booleans/src/test/java/com/baeldung/booleans/BooleanToStringUnitTest.java b/core-java-modules/core-java-booleans/src/test/java/com/baeldung/booleans/BooleanToStringUnitTest.java
new file mode 100644
index 0000000000..e20cc3508f
--- /dev/null
+++ b/core-java-modules/core-java-booleans/src/test/java/com/baeldung/booleans/BooleanToStringUnitTest.java
@@ -0,0 +1,48 @@
+package com.baeldung.booleans;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+public class BooleanToStringUnitTest {
+ String optionToString(String optionName, boolean optionValue) {
+ return String.format("The option '%s' is %s.", optionName, optionValue ? "Enabled" : "Disabled");
+ }
+
+ @Test
+ void givenPrimitiveBoolean_whenConvertingUsingTernaryOperator_thenSuccess() {
+ boolean primitiveBoolean = true;
+ assertEquals("true", primitiveBoolean ? "true" : "false");
+
+ primitiveBoolean = false;
+ assertEquals("false", primitiveBoolean ? "true" : "false");
+
+ assertEquals("The option 'IgnoreWarnings' is Enabled.", optionToString("IgnoreWarnings", true));
+ }
+
+
+ @Test
+ void givenBooleanObject_whenConvertingUsingBooleanToString_thenSuccess() {
+ Boolean myBoolean = Boolean.TRUE;
+ assertEquals("true", myBoolean.toString());
+
+ myBoolean = Boolean.FALSE;
+ assertEquals("false", myBoolean.toString());
+
+ Boolean nullBoolean = null;
+ assertThrows(NullPointerException.class, () -> nullBoolean.toString());
+ }
+
+ @Test
+ void givenBooleanObject_whenConvertingUsingStringValueOf_thenSuccess() {
+ Boolean myBoolean = Boolean.TRUE;
+ assertEquals("true", String.valueOf(myBoolean));
+
+ myBoolean = Boolean.FALSE;
+ assertEquals("false", String.valueOf(myBoolean));
+
+ Boolean nullBoolean = null;
+ assertEquals("null", String.valueOf(nullBoolean));
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-char/README.md b/core-java-modules/core-java-char/README.md
index 5f33aa6914..e4af3121c5 100644
--- a/core-java-modules/core-java-char/README.md
+++ b/core-java-modules/core-java-char/README.md
@@ -4,3 +4,4 @@ This module contains articles about Java Character Class
### Relevant Articles:
- [Character#isAlphabetic vs. Character#isLetter](https://www.baeldung.com/java-character-isletter-isalphabetic)
+- [Difference Between Java’s “char” and “String”](https://www.baeldung.com/java-char-vs-string)
diff --git a/core-java-modules/core-java-char/pom.xml b/core-java-modules/core-java-char/pom.xml
index 7dc0923fb5..eb6cbee952 100644
--- a/core-java-modules/core-java-char/pom.xml
+++ b/core-java-modules/core-java-char/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-char
- 0.1.0-SNAPSHOT
core-java-char
jar
diff --git a/core-java-modules/core-java-char/src/test/java/com/baeldung/charandstring/DifferenceBetweenCharAndStringUnitTest.java b/core-java-modules/core-java-char/src/test/java/com/baeldung/charandstring/DifferenceBetweenCharAndStringUnitTest.java
new file mode 100644
index 0000000000..b4e1da6d71
--- /dev/null
+++ b/core-java-modules/core-java-char/src/test/java/com/baeldung/charandstring/DifferenceBetweenCharAndStringUnitTest.java
@@ -0,0 +1,56 @@
+package com.baeldung.charandstring;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+
+import org.junit.jupiter.api.Test;
+
+public class DifferenceBetweenCharAndStringUnitTest {
+
+ @Test
+ void whenPlusTwoChars_thenGetSumAsInteger() {
+ char h = 'H'; // the value is 72
+ char i = 'i'; // the value is 105
+ assertEquals(177, h + i);
+ assertInstanceOf(Integer.class, h + i);
+ }
+
+ @Test
+ void whenPlusTwoStrings_thenConcatenateThem() {
+ String i = "i";
+ String h = "H";
+ assertEquals("Hi", h + i);
+ }
+
+ @Test
+ void whenPlusCharsAndStrings_thenGetExpectedValues() {
+ char c = 'C';
+ assertEquals("C", "" + c);
+
+ char h = 'H'; // the value is 72
+ char i = 'i'; // the value is 105
+ assertEquals("Hi", "" + h + i);
+ assertEquals("Hi", h + "" + i);
+ assertEquals("177", h + i + "");
+ }
+
+ @Test
+ void whenStringChars_thenGetCharArray() {
+ char h = 'h';
+ char e = 'e';
+ char l = 'l';
+ char o = 'o';
+
+ String hello = "hello";
+ assertEquals(h, hello.charAt(0));
+ assertEquals(e, hello.charAt(1));
+ assertEquals(l, hello.charAt(2));
+ assertEquals(l, hello.charAt(3));
+ assertEquals(o, hello.charAt(4));
+
+ char[] chars = new char[] { h, e, l, l, o };
+ char[] charsFromString = hello.toCharArray();
+ assertArrayEquals(chars, charsFromString);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-2/README.md b/core-java-modules/core-java-collections-2/README.md
index 644cc93be7..5a9bae8f9f 100644
--- a/core-java-modules/core-java-collections-2/README.md
+++ b/core-java-modules/core-java-collections-2/README.md
@@ -13,4 +13,4 @@
- [Getting the Size of an Iterable in Java](https://www.baeldung.com/java-iterable-size)
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
- [Differences Between Iterator and Iterable and How to Use Them?](https://www.baeldung.com/java-iterator-vs-iterable)
-- More articles: [[<-- prev]](/core-java-modules/core-java-collections-1) [[next -->]](/core-java-modules/core-java-collections-3)
\ No newline at end of file
+- More articles: [[<-- prev]](/core-java-modules/core-java-collections) [[next -->]](/core-java-modules/core-java-collections-3)
diff --git a/core-java-modules/core-java-collections-3/pom.xml b/core-java-modules/core-java-collections-3/pom.xml
index 6ef8e3c81a..373dc9db14 100644
--- a/core-java-modules/core-java-collections-3/pom.xml
+++ b/core-java-modules/core-java-collections-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-3
- 0.1.0-SNAPSHOT
core-java-collections-3
jar
diff --git a/core-java-modules/core-java-collections-4/pom.xml b/core-java-modules/core-java-collections-4/pom.xml
index e88d5a6740..1a59411ecb 100644
--- a/core-java-modules/core-java-collections-4/pom.xml
+++ b/core-java-modules/core-java-collections-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-4
- 0.1.0-SNAPSHOT
core-java-collections-4
jar
diff --git a/core-java-modules/core-java-collections-5/README.md b/core-java-modules/core-java-collections-5/README.md
index cf479ec507..0d9b12b842 100644
--- a/core-java-modules/core-java-collections-5/README.md
+++ b/core-java-modules/core-java-collections-5/README.md
@@ -3,5 +3,5 @@
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
-
-- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
\ No newline at end of file
+- [Introduction to Roaring Bitmap](https://www.baeldung.com/java-roaring-bitmap-intro)
+- More articles: [[<-- prev]](/core-java-modules/core-java-collections-4)
diff --git a/core-java-modules/core-java-collections-5/pom.xml b/core-java-modules/core-java-collections-5/pom.xml
index 67c9f7120c..6baecc2802 100644
--- a/core-java-modules/core-java-collections-5/pom.xml
+++ b/core-java-modules/core-java-collections-5/pom.xml
@@ -1,10 +1,9 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-5
- 0.0.1-SNAPSHOT
core-java-collections-5
jar
@@ -55,4 +54,5 @@
0.9.38
1.36
+
diff --git a/core-java-modules/core-java-collections-array-list/pom.xml b/core-java-modules/core-java-collections-array-list/pom.xml
index e3a115854c..ee0b102bb0 100644
--- a/core-java-modules/core-java-collections-array-list/pom.xml
+++ b/core-java-modules/core-java-collections-array-list/pom.xml
@@ -4,34 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-array-list
- 0.1.0-SNAPSHOT
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
-
-
- ${maven-compiler-plugin.target}
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- ${surefire.plugin.version}
-
-
- --add-opens java.base/java.util=ALL-UNNAMED
-
-
-
-
-
-
- 16
- 16
- 3.0.0-M3
-
core-java-collections-array-list
jar
@@ -55,4 +27,33 @@
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ ${maven-compiler-plugin.target}
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ ${surefire.plugin.version}
+
+
+ --add-opens java.base/java.util=ALL-UNNAMED
+
+
+
+
+
+
+
+ 16
+ 16
+ 3.0.0-M3
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-collections-conversions-2/README.md b/core-java-modules/core-java-collections-conversions-2/README.md
index 742b52aad5..904e876032 100644
--- a/core-java-modules/core-java-collections-conversions-2/README.md
+++ b/core-java-modules/core-java-collections-conversions-2/README.md
@@ -10,4 +10,5 @@ This module contains articles about conversions among Collection types and array
- [Arrays.asList vs new ArrayList(Arrays.asList())](https://www.baeldung.com/java-arrays-aslist-vs-new-arraylist)
- [Iterate Over a Set in Java](https://www.baeldung.com/java-iterate-set)
- [Convert a List of Integers to a List of Strings](https://www.baeldung.com/java-convert-list-integers-to-list-strings)
+- [Combining Two Lists Into a Map in Java](https://www.baeldung.com/java-combine-two-lists-into-map)
- More articles: [[<-- prev]](../core-java-collections-conversions)
diff --git a/core-java-modules/core-java-collections-conversions-2/pom.xml b/core-java-modules/core-java-collections-conversions-2/pom.xml
index f6775a7a42..8cd0a6932b 100644
--- a/core-java-modules/core-java-collections-conversions-2/pom.xml
+++ b/core-java-modules/core-java-collections-conversions-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-conversions-2
- 0.1.0-SNAPSHOT
core-java-collections-conversions-2
jar
diff --git a/core-java-modules/core-java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserList.java b/core-java-modules/core-java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserList.java
index 7b6bed807b..5907c159cb 100644
--- a/core-java-modules/core-java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserList.java
+++ b/core-java-modules/core-java-collections-conversions-2/src/main/java/com/baeldung/modelmapper/UserList.java
@@ -9,6 +9,7 @@ import java.util.Collection;
*/
public class UserList {
+ public UserList() {}
private Collection users;
public Collection getUsers() {
diff --git a/core-java-modules/core-java-collections-conversions/pom.xml b/core-java-modules/core-java-collections-conversions/pom.xml
index 08a452da51..78e9847c0a 100644
--- a/core-java-modules/core-java-collections-conversions/pom.xml
+++ b/core-java-modules/core-java-collections-conversions/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-conversions
- 0.1.0-SNAPSHOT
core-java-collections-conversions
jar
diff --git a/core-java-modules/core-java-collections-list-2/pom.xml b/core-java-modules/core-java-collections-list-2/pom.xml
index 59ab8c5f27..a305cdffc8 100644
--- a/core-java-modules/core-java-collections-list-2/pom.xml
+++ b/core-java-modules/core-java-collections-list-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-list-2
- 0.1.0-SNAPSHOT
core-java-collections-list-2
jar
diff --git a/core-java-modules/core-java-collections-list-3/pom.xml b/core-java-modules/core-java-collections-list-3/pom.xml
index 912204bcc6..f01fe1f3b9 100644
--- a/core-java-modules/core-java-collections-list-3/pom.xml
+++ b/core-java-modules/core-java-collections-list-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-list-3
- 0.1.0-SNAPSHOT
core-java-collections-list-3
jar
diff --git a/core-java-modules/core-java-collections-list-4/pom.xml b/core-java-modules/core-java-collections-list-4/pom.xml
index 964ea4f5a1..6d068298ec 100644
--- a/core-java-modules/core-java-collections-list-4/pom.xml
+++ b/core-java-modules/core-java-collections-list-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-list-4
- 0.1.0-SNAPSHOT
core-java-collections-list-4
jar
diff --git a/core-java-modules/core-java-collections-list-5/README.md b/core-java-modules/core-java-collections-list-5/README.md
index 78959e7d5d..4929ca4e4e 100644
--- a/core-java-modules/core-java-collections-list-5/README.md
+++ b/core-java-modules/core-java-collections-list-5/README.md
@@ -4,3 +4,5 @@ This module contains articles about the Java List collection
### Relevant Articles:
- [Java List Interface](https://www.baeldung.com/java-list-interface)
+- [Finding All Duplicates in a List in Java](https://www.baeldung.com/java-list-find-duplicates)
+- [Moving Items Around in an Arraylist](https://www.baeldung.com/java-arraylist-move-items)
diff --git a/core-java-modules/core-java-collections-list-5/pom.xml b/core-java-modules/core-java-collections-list-5/pom.xml
index 0807f7612c..b51dda4091 100644
--- a/core-java-modules/core-java-collections-list-5/pom.xml
+++ b/core-java-modules/core-java-collections-list-5/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-list-5
- 0.1.0-SNAPSHOT
core-java-collections-list-5
jar
diff --git a/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/listduplicate/ListDuplicate.java b/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/listduplicate/ListDuplicate.java
new file mode 100644
index 0000000000..5e3e845916
--- /dev/null
+++ b/core-java-modules/core-java-collections-list-5/src/main/java/com/baeldung/listduplicate/ListDuplicate.java
@@ -0,0 +1,69 @@
+package com.baeldung.listduplicate;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+public class ListDuplicate {
+ public List listDuplicateUsingSet(List list) {
+ List duplicates = new ArrayList<>();
+ Set set = new HashSet<>();
+ for (Integer i : list) {
+ if (set.contains(i)) {
+ duplicates.add(i);
+ } else {
+ set.add(i);
+ }
+ }
+ return duplicates;
+ }
+
+ public List listDuplicateUsingMap(List list) {
+ List duplicates = new ArrayList<>();
+ Map frequencyMap = new HashMap<>();
+ for (Integer number : list) {
+ frequencyMap.put(number, frequencyMap.getOrDefault(number, 0) + 1);
+ }
+ for (int number : frequencyMap.keySet()) {
+ if (frequencyMap.get(number) != 1) {
+ duplicates.add(number);
+ }
+ }
+ return duplicates;
+ }
+
+ public List listDuplicateUsingFilterAndSetAdd(List list) {
+ Set elements = new HashSet();
+ return list.stream()
+ .filter(n -> !elements.add(n))
+ .collect(Collectors.toList());
+ }
+
+ public List listDuplicateUsingCollectionsFrequency(List list) {
+ List duplicates = new ArrayList<>();
+ Set set = list.stream()
+ .filter(i -> Collections.frequency(list, i) > 1)
+ .collect(Collectors.toSet());
+ duplicates.addAll(set);
+ return duplicates;
+ }
+
+ public List listDuplicateUsingMapAndCollectorsGroupingBy(List list) {
+ List duplicates = new ArrayList<>();
+ Set set = list.stream()
+ .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
+ .entrySet()
+ .stream()
+ .filter(m -> m.getValue() > 1)
+ .map(Map.Entry::getKey)
+ .collect(Collectors.toSet());
+ duplicates.addAll(set);
+ return duplicates;
+ }
+}
diff --git a/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/MovingItemsInArrayListUnitTest.java b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/MovingItemsInArrayListUnitTest.java
new file mode 100644
index 0000000000..121d240a85
--- /dev/null
+++ b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/java/list/MovingItemsInArrayListUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.java.list;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+
+import org.junit.Test;
+
+public class MovingItemsInArrayListUnitTest {
+
+ @Test
+ public void givenAList_whenManuallyReordering_thenOneItemMovesPosition() {
+ ArrayList arrayList = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five"));
+
+ String removed = arrayList.remove(3);
+ arrayList.add(2, removed);
+
+ ArrayList expectedResult = new ArrayList<>(Arrays.asList("one", "two", "four", "three", "five"));
+ assertEquals(expectedResult, arrayList);
+ }
+
+ @Test
+ public void givenAList_whenUsingSwap_thenItemsSwapPositions() {
+ ArrayList arrayList = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five"));
+
+ Collections.swap(arrayList, 1, 3);
+
+ ArrayList expectedResult = new ArrayList<>(Arrays.asList("one", "four", "three", "two", "five"));
+ assertEquals(expectedResult, arrayList);
+ }
+
+ @Test
+ public void givenAList_whenUsingRotateWithPositiveDistance_thenItemsMoveToTheRight() {
+ ArrayList arrayList = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five"));
+
+ Collections.rotate(arrayList, 2);
+
+ ArrayList expectedResult = new ArrayList<>(Arrays.asList("four", "five", "one", "two", "three"));
+ assertEquals(expectedResult, arrayList);
+ }
+
+ @Test
+ public void givenAList_whenUsingRotateWithNegativeDistance_thenItemsMoveToTheLeft() {
+ ArrayList arrayList = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five"));
+
+ Collections.rotate(arrayList, -2);
+
+ ArrayList expectedResult = new ArrayList<>(Arrays.asList("three", "four", "five", "one", "two"));
+ assertEquals(expectedResult, arrayList);
+ }
+}
diff --git a/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/listduplicate/ListDuplicateUnitTest.java b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/listduplicate/ListDuplicateUnitTest.java
new file mode 100644
index 0000000000..0d81387aea
--- /dev/null
+++ b/core-java-modules/core-java-collections-list-5/src/test/java/com/baeldung/listduplicate/ListDuplicateUnitTest.java
@@ -0,0 +1,68 @@
+package com.baeldung.listduplicate;
+
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class ListDuplicateUnitTest {
+ private static ListDuplicate listDuplicate;
+
+ @BeforeClass
+ public static void setup() {
+ listDuplicate = new ListDuplicate();
+ }
+
+ @Test
+ public void givenList_whenUsingSet_thenReturnDuplicateElements() {
+ List list = Arrays.asList(1, 2, 3, 3, 4, 4, 5);
+ List duplicates = listDuplicate.listDuplicateUsingSet(list);
+ Assert.assertEquals(duplicates.size(), 2);
+ Assert.assertEquals(duplicates.contains(3), true);
+ Assert.assertEquals(duplicates.contains(4), true);
+ Assert.assertEquals(duplicates.contains(1), false);
+ }
+
+ @Test
+ public void givenList_whenUsingFrequencyMap_thenReturnDuplicateElements() {
+ List list = Arrays.asList(1, 2, 3, 3, 4, 4, 5);
+ List duplicates = listDuplicate.listDuplicateUsingMap(list);
+ Assert.assertEquals(duplicates.size(), 2);
+ Assert.assertEquals(duplicates.contains(3), true);
+ Assert.assertEquals(duplicates.contains(4), true);
+ Assert.assertEquals(duplicates.contains(1), false);
+ }
+
+ @Test
+ public void givenList_whenUsingFilterAndSetAdd_thenReturnDuplicateElements() {
+ List list = Arrays.asList(1, 2, 3, 3, 4, 4, 5);
+ List duplicates = listDuplicate.listDuplicateUsingFilterAndSetAdd(list);
+ Assert.assertEquals(duplicates.size(), 2);
+ Assert.assertEquals(duplicates.contains(3), true);
+ Assert.assertEquals(duplicates.contains(4), true);
+ Assert.assertEquals(duplicates.contains(1), false);
+ }
+
+ @Test
+ public void givenList_whenUsingCollectionsFrequency_thenReturnDuplicateElements() {
+ List list = Arrays.asList(1, 2, 3, 3, 4, 4, 5);
+ List duplicates = listDuplicate.listDuplicateUsingCollectionsFrequency(list);
+ Assert.assertEquals(duplicates.size(), 2);
+ Assert.assertEquals(duplicates.contains(3), true);
+ Assert.assertEquals(duplicates.contains(4), true);
+ Assert.assertEquals(duplicates.contains(1), false);
+ }
+
+ @Test
+ public void givenList_whenUsingMapAndCollectorsGroupingBy_thenReturnDuplicateElements() {
+ List list = Arrays.asList(1, 2, 3, 3, 4, 4, 5);
+ List duplicates = listDuplicate.listDuplicateUsingCollectionsFrequency(list);
+ Assert.assertEquals(duplicates.size(), 2);
+ Assert.assertEquals(duplicates.contains(3), true);
+ Assert.assertEquals(duplicates.contains(4), true);
+ Assert.assertEquals(duplicates.contains(1), false);
+ }
+
+}
diff --git a/core-java-modules/core-java-collections-list/pom.xml b/core-java-modules/core-java-collections-list/pom.xml
index 0cc8828a0d..94abb334e0 100644
--- a/core-java-modules/core-java-collections-list/pom.xml
+++ b/core-java-modules/core-java-collections-list/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-list
- 0.1.0-SNAPSHOT
core-java-collections-list
jar
diff --git a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java
index c2cc39c685..e634fddab8 100644
--- a/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java
+++ b/core-java-modules/core-java-collections-list/src/test/java/com/baeldung/java8/Java8MaxMinUnitTest.java
@@ -6,6 +6,7 @@ import com.baeldung.java_8_features.Person;
import org.junit.Test;
import java.util.Arrays;
+import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
@@ -71,4 +72,17 @@ public class Java8MaxMinUnitTest {
assertEquals(bugatti, maxBySpeed);
}
+
+ @Test
+ public void givenIntegerList_whenGetMinAndIndex_thenSuccess() {
+ final List listOfIntegers = Arrays.asList(11, 13, 9, 20, 7, 3, 30);
+ final Integer expectedMinValue = 3;
+ final Integer expectedMinIndex = 5;
+
+ Integer minValue = Collections.min(listOfIntegers);
+ Integer minIndex = listOfIntegers.indexOf(minValue);
+
+ assertEquals(minValue, expectedMinValue);
+ assertEquals(minIndex, expectedMinIndex);
+ }
}
diff --git a/core-java-modules/core-java-collections-maps-2/pom.xml b/core-java-modules/core-java-collections-maps-2/pom.xml
index 1e526ef892..15ca688ad2 100644
--- a/core-java-modules/core-java-collections-maps-2/pom.xml
+++ b/core-java-modules/core-java-collections-maps-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-maps-2
- 0.1.0-SNAPSHOT
core-java-collections-maps-2
jar
diff --git a/core-java-modules/core-java-collections-maps-3/pom.xml b/core-java-modules/core-java-collections-maps-3/pom.xml
index a5bb6dc338..98a0d18fe9 100644
--- a/core-java-modules/core-java-collections-maps-3/pom.xml
+++ b/core-java-modules/core-java-collections-maps-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-maps-3
- 0.1.0-SNAPSHOT
core-java-collections-maps-3
jar
diff --git a/core-java-modules/core-java-collections-maps-4/pom.xml b/core-java-modules/core-java-collections-maps-4/pom.xml
index a85e2cde2a..f1734b7379 100644
--- a/core-java-modules/core-java-collections-maps-4/pom.xml
+++ b/core-java-modules/core-java-collections-maps-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-maps-4
- 0.1.0-SNAPSHOT
core-java-collections-maps-4
jar
diff --git a/core-java-modules/core-java-collections-maps-5/pom.xml b/core-java-modules/core-java-collections-maps-5/pom.xml
index f12e044b23..593ec5a8f6 100644
--- a/core-java-modules/core-java-collections-maps-5/pom.xml
+++ b/core-java-modules/core-java-collections-maps-5/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-maps-5
- 0.1.0-SNAPSHOT
core-java-collections-maps-5
jar
diff --git a/core-java-modules/core-java-collections-maps-6/README.md b/core-java-modules/core-java-collections-maps-6/README.md
new file mode 100644
index 0000000000..fc12a1bb25
--- /dev/null
+++ b/core-java-modules/core-java-collections-maps-6/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Copying All Keys and Values From One Hashmap Onto Another Without Replacing Existing Keys and Values](https://www.baeldung.com/java-copy-hashmap-no-changes)
diff --git a/core-java-modules/core-java-collections-maps-6/pom.xml b/core-java-modules/core-java-collections-maps-6/pom.xml
index 9910d08691..70a04c352b 100644
--- a/core-java-modules/core-java-collections-maps-6/pom.xml
+++ b/core-java-modules/core-java-collections-maps-6/pom.xml
@@ -1,17 +1,17 @@
+ 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
core-java-collections-maps-6
- 0.1.0-SNAPSHOT
core-java-collections-maps-6
jar
+
core-java-modules
com.baeldung.core-java-modules
0.0.1-SNAPSHOT
- 4.0.0
5.2.5.RELEASE
diff --git a/core-java-modules/core-java-collections-maps/pom.xml b/core-java-modules/core-java-collections-maps/pom.xml
index 3a1bf0d8a1..5e19117e08 100644
--- a/core-java-modules/core-java-collections-maps/pom.xml
+++ b/core-java-modules/core-java-collections-maps/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-maps
- 0.1.0-SNAPSHOT
core-java-collections-maps
jar
diff --git a/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java
index d308aac7eb..4ac562ef04 100644
--- a/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java
+++ b/core-java-modules/core-java-collections-maps/src/test/java/com/baeldung/map/ImmutableMapUnitTest.java
@@ -1,84 +1,126 @@
package com.baeldung.map;
-import com.google.common.collect.ImmutableMap;
-import org.junit.jupiter.api.Test;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import java.util.AbstractMap;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.jupiter.api.Assertions.*;
+import org.hamcrest.collection.IsMapContaining;
+import org.junit.jupiter.api.Test;
+import com.google.common.collect.ImmutableMap;
-public class ImmutableMapUnitTest {
+class ImmutableMapUnitTest {
- @Test
- public void whenCollectionsUnModifiableMapMethod_thenOriginalCollectionChangesReflectInUnmodifiableMap() {
+ @Test
+ void whenCollectionsUnModifiableMapMethod_thenOriginalCollectionChangesReflectInUnmodifiableMap() {
- Map mutableMap = new HashMap<>();
- mutableMap.put("USA", "North America");
+ Map mutableMap = new HashMap<>();
+ mutableMap.put("USA", "North America");
- Map unmodifiableMap = Collections.unmodifiableMap(mutableMap);
- assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("Canada", "North America"));
-
- mutableMap.remove("USA");
- assertFalse(unmodifiableMap.containsKey("USA"));
-
- mutableMap.put("Mexico", "North America");
- assertTrue(unmodifiableMap.containsKey("Mexico"));
- }
-
- @Test
- @SuppressWarnings("deprecation")
- public void whenGuavaImmutableMapFromCopyOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
+ Map unmodifiableMap = Collections.unmodifiableMap(mutableMap);
+ assertThrows(UnsupportedOperationException.class, () -> unmodifiableMap.put("Canada", "North America"));
- Map mutableMap = new HashMap<>();
- mutableMap.put("USA", "North America");
+ mutableMap.remove("USA");
+ assertFalse(unmodifiableMap.containsKey("USA"));
- ImmutableMap immutableMap = ImmutableMap.copyOf(mutableMap);
- assertTrue(immutableMap.containsKey("USA"));
-
- assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
-
- mutableMap.remove("USA");
- assertTrue(immutableMap.containsKey("USA"));
-
- mutableMap.put("Mexico", "North America");
- assertFalse(immutableMap.containsKey("Mexico"));
- }
-
- @Test
- @SuppressWarnings("deprecation")
- public void whenGuavaImmutableMapFromBuilderMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
+ mutableMap.put("Mexico", "North America");
+ assertTrue(unmodifiableMap.containsKey("Mexico"));
+ }
- Map mutableMap = new HashMap<>();
- mutableMap.put("USA", "North America");
+ @Test
+ @SuppressWarnings("deprecation")
+ void whenGuavaImmutableMapFromCopyOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
- ImmutableMap immutableMap = ImmutableMap.builder()
- .putAll(mutableMap)
- .put("Costa Rica", "North America")
- .build();
- assertTrue(immutableMap.containsKey("USA"));
- assertTrue(immutableMap.containsKey("Costa Rica"));
-
- assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
-
- mutableMap.remove("USA");
- assertTrue(immutableMap.containsKey("USA"));
-
- mutableMap.put("Mexico", "North America");
- assertFalse(immutableMap.containsKey("Mexico"));
- }
-
- @Test
- @SuppressWarnings("deprecation")
- public void whenGuavaImmutableMapFromOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
+ Map mutableMap = new HashMap<>();
+ mutableMap.put("USA", "North America");
- ImmutableMap immutableMap = ImmutableMap.of("USA", "North America", "Costa Rica", "North America");
- assertTrue(immutableMap.containsKey("USA"));
- assertTrue(immutableMap.containsKey("Costa Rica"));
+ ImmutableMap immutableMap = ImmutableMap.copyOf(mutableMap);
+ assertTrue(immutableMap.containsKey("USA"));
+
+ assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
+
+ mutableMap.remove("USA");
+ assertTrue(immutableMap.containsKey("USA"));
+
+ mutableMap.put("Mexico", "North America");
+ assertFalse(immutableMap.containsKey("Mexico"));
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ void whenGuavaImmutableMapFromBuilderMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
+
+ Map mutableMap = new HashMap<>();
+ mutableMap.put("USA", "North America");
+
+ ImmutableMap immutableMap = ImmutableMap.builder()
+ .putAll(mutableMap)
+ .put("Costa Rica", "North America")
+ .build();
+ assertTrue(immutableMap.containsKey("USA"));
+ assertTrue(immutableMap.containsKey("Costa Rica"));
+
+ assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
+
+ mutableMap.remove("USA");
+ assertTrue(immutableMap.containsKey("USA"));
+
+ mutableMap.put("Mexico", "North America");
+ assertFalse(immutableMap.containsKey("Mexico"));
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ void whenGuavaImmutableMapFromOfMethod_thenOriginalCollectionChangesDoNotReflectInImmutableMap() {
+
+ ImmutableMap immutableMap = ImmutableMap.of("USA", "North America", "Costa Rica", "North America");
+ assertTrue(immutableMap.containsKey("USA"));
+ assertTrue(immutableMap.containsKey("Costa Rica"));
+
+ assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
+ }
+
+ @Test
+ @SuppressWarnings("deprecation")
+ void givenGuavaImmutableMapFromOfEntriesMethodwhenModifyEntry_thenThrowUnsupportedOperationException() {
+
+ ImmutableMap immutableMap = ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(1, "USA"), new AbstractMap.SimpleEntry<>(2, "Canada"));
+
+ assertThrows(UnsupportedOperationException.class, () -> immutableMap.put(2, "Mexico"));
+ }
+
+ @Test
+ void givenEntrieswhenCreatingGuavaImmutableMapFromOfEntriesMethod_thenCorrect() {
+
+ ImmutableMap immutableMap = ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(1, "USA"));
+
+ assertEquals(1, immutableMap.size());
+ assertThat(immutableMap, IsMapContaining.hasEntry(1, "USA"));
+ }
+
+ @Test
+ void givenGuavaImmutableMapFromOfEntriesMethodwhenEntryKeyExists_thenThrowIllegalArgumentException() {
+
+ assertThrows(IllegalArgumentException.class, () -> ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(1, "USA"), new AbstractMap.SimpleEntry<>(1, "Canada")));
+ }
+
+ @Test
+ void givenGuavaImmutableMapFromOfEntriesMethodwhenEntryKeyIsNull_thenThrowNullPointerException() {
+
+ assertThrows(NullPointerException.class, () -> ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(null, "USA")));
+ }
+
+ @Test
+ void givenGuavaImmutableMapFromOfEntriesMethodwhenEntryValueIsNull_thenThrowNullPointerException() {
+
+ assertThrows(NullPointerException.class, () -> ImmutableMap.ofEntries(new AbstractMap.SimpleEntry<>(1, null)));
+ }
- assertThrows(UnsupportedOperationException.class, () -> immutableMap.put("Canada", "North America"));
- }
-
}
diff --git a/core-java-modules/core-java-collections-set-2/pom.xml b/core-java-modules/core-java-collections-set-2/pom.xml
index b1aadb0c22..680c01d8ca 100644
--- a/core-java-modules/core-java-collections-set-2/pom.xml
+++ b/core-java-modules/core-java-collections-set-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-set-2
- 0.0.1-SNAPSHOT
core-java-collections-set-2
jar
diff --git a/core-java-modules/core-java-collections-set/pom.xml b/core-java-modules/core-java-collections-set/pom.xml
index 0b6e324c78..e130837f1c 100644
--- a/core-java-modules/core-java-collections-set/pom.xml
+++ b/core-java-modules/core-java-collections-set/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections-set
- 0.1.0-SNAPSHOT
core-java-collections-set
jar
diff --git a/core-java-modules/core-java-collections/pom.xml b/core-java-modules/core-java-collections/pom.xml
index eab7a35584..be91492d06 100644
--- a/core-java-modules/core-java-collections/pom.xml
+++ b/core-java-modules/core-java-collections/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-collections
- 0.1.0-SNAPSHOT
core-java-collections
jar
diff --git a/core-java-modules/core-java-compiler/README.md b/core-java-modules/core-java-compiler/README.md
new file mode 100644
index 0000000000..2a1e609194
--- /dev/null
+++ b/core-java-modules/core-java-compiler/README.md
@@ -0,0 +1,6 @@
+## Core Java Compiler
+
+### Relevant Articles:
+
+- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
+- [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error)
diff --git a/core-java-modules/core-java-compiler/pom.xml b/core-java-modules/core-java-compiler/pom.xml
new file mode 100644
index 0000000000..8f2be3f142
--- /dev/null
+++ b/core-java-modules/core-java-compiler/pom.xml
@@ -0,0 +1,29 @@
+
+
+ 4.0.0
+ core-java-compiler
+ 0.1.0-SNAPSHOT
+ core-java-compiler
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ com.google.gdata
+ core
+ ${gdata.version}
+
+
+
+
+ 1.47.1
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/javac/Data.java b/core-java-modules/core-java-compiler/src/main/java/com/baeldung/javac/Data.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/javac/Data.java
rename to core-java-modules/core-java-compiler/src/main/java/com/baeldung/javac/Data.java
diff --git a/core-java-modules/core-java/src/main/java/javac-args/arguments b/core-java-modules/core-java-compiler/src/main/java/javac-args/arguments
similarity index 100%
rename from core-java-modules/core-java/src/main/java/javac-args/arguments
rename to core-java-modules/core-java-compiler/src/main/java/javac-args/arguments
diff --git a/core-java-modules/core-java/src/main/java/javac-args/options b/core-java-modules/core-java-compiler/src/main/java/javac-args/options
similarity index 100%
rename from core-java-modules/core-java/src/main/java/javac-args/options
rename to core-java-modules/core-java-compiler/src/main/java/javac-args/options
diff --git a/core-java-modules/core-java/src/main/java/javac-args/types b/core-java-modules/core-java-compiler/src/main/java/javac-args/types
similarity index 100%
rename from core-java-modules/core-java/src/main/java/javac-args/types
rename to core-java-modules/core-java-compiler/src/main/java/javac-args/types
diff --git a/core-java-modules/core-java/src/main/java/javac-args/xlint-ops b/core-java-modules/core-java-compiler/src/main/java/javac-args/xlint-ops
similarity index 100%
rename from core-java-modules/core-java/src/main/java/javac-args/xlint-ops
rename to core-java-modules/core-java-compiler/src/main/java/javac-args/xlint-ops
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/illegalcharacter/IllegalCharacterUnitTest.java b/core-java-modules/core-java-compiler/src/test/java/com/baeldung/illegalcharacter/IllegalCharacterUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/illegalcharacter/IllegalCharacterUnitTest.java
rename to core-java-modules/core-java-compiler/src/test/java/com/baeldung/illegalcharacter/IllegalCharacterUnitTest.java
diff --git a/core-java-modules/core-java/src/test/resources/bom-file.txt b/core-java-modules/core-java-compiler/src/test/resources/bom-file.txt
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/bom-file.txt
rename to core-java-modules/core-java-compiler/src/test/resources/bom-file.txt
diff --git a/core-java-modules/core-java-concurrency-2/pom.xml b/core-java-modules/core-java-concurrency-2/pom.xml
index c61f28a6b3..e373c829cc 100644
--- a/core-java-modules/core-java-concurrency-2/pom.xml
+++ b/core-java-modules/core-java-concurrency-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-2
- 0.1.0-SNAPSHOT
core-java-concurrency-2
jar
diff --git a/core-java-modules/core-java-concurrency-advanced-2/pom.xml b/core-java-modules/core-java-concurrency-advanced-2/pom.xml
index 1f19dc8cca..5c96684311 100644
--- a/core-java-modules/core-java-concurrency-advanced-2/pom.xml
+++ b/core-java-modules/core-java-concurrency-advanced-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-advanced-2
- 0.1.0-SNAPSHOT
core-java-concurrency-advanced-2
jar
diff --git a/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerUnitTest.java b/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerManualTest.java
similarity index 93%
rename from core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerUnitTest.java
rename to core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerManualTest.java
index 20e6a5ef5b..bd71cfc263 100644
--- a/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerUnitTest.java
+++ b/core-java-modules/core-java-concurrency-advanced-2/src/test/java/com/baeldung/concurrent/prioritytaskexecution/PriorityJobSchedulerManualTest.java
@@ -2,7 +2,8 @@ package com.baeldung.concurrent.prioritytaskexecution;
import org.junit.Test;
-public class PriorityJobSchedulerUnitTest {
+//Converted to ManualTest due to thread sleep
+public class PriorityJobSchedulerManualTest {
private static final int POOL_SIZE = 1;
private static final int QUEUE_SIZE = 10;
diff --git a/core-java-modules/core-java-concurrency-advanced-3/pom.xml b/core-java-modules/core-java-concurrency-advanced-3/pom.xml
index 49a72112b4..7fa859c2d5 100644
--- a/core-java-modules/core-java-concurrency-advanced-3/pom.xml
+++ b/core-java-modules/core-java-concurrency-advanced-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-advanced-3
- 0.1.0-SNAPSHOT
core-java-concurrency-advanced-3
jar
diff --git a/core-java-modules/core-java-concurrency-advanced-4/pom.xml b/core-java-modules/core-java-concurrency-advanced-4/pom.xml
index 5bd7ccfa07..2ffe19b13c 100644
--- a/core-java-modules/core-java-concurrency-advanced-4/pom.xml
+++ b/core-java-modules/core-java-concurrency-advanced-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-advanced-4
- 0.1.0-SNAPSHOT
core-java-concurrency-advanced-4
jar
@@ -14,9 +13,6 @@
0.0.1-SNAPSHOT
-
-
-
core-java-concurrency-advanced-4
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Consumer.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Consumer.java
index 5a059b74df..933a1b5f52 100644
--- a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Consumer.java
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Consumer.java
@@ -1,12 +1,13 @@
package com.baeldung.producerconsumer;
+import java.util.logging.Logger;
+
public class Consumer implements Runnable {
+ private static final Logger log = Logger.getLogger(Consumer.class.getCanonicalName());
private final DataQueue dataQueue;
- private volatile boolean runFlag;
public Consumer(DataQueue dataQueue) {
this.dataQueue = dataQueue;
- runFlag = true;
}
@Override
@@ -15,29 +16,31 @@ public class Consumer implements Runnable {
}
public void consume() {
- while (runFlag) {
- Message message;
- if (dataQueue.isEmpty()) {
- try {
- dataQueue.waitOnEmpty();
- } catch (InterruptedException e) {
- e.printStackTrace();
+ while (dataQueue.runFlag) {
+ synchronized (dataQueue) {
+ while (dataQueue.isEmpty() && dataQueue.runFlag) {
+ try {
+ dataQueue.waitOnEmpty();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ break;
+ }
+ }
+ if (!dataQueue.runFlag) {
break;
}
+ Message message = dataQueue.remove();
+ dataQueue.notifyAllForFull();
+ useMessage(message);
}
- if (!runFlag) {
- break;
- }
- message = dataQueue.remove();
- dataQueue.notifyAllForFull();
- useMessage(message);
}
- System.out.println("Consumer Stopped");
+ log.info("Consumer Stopped");
}
private void useMessage(Message message) {
if (message != null) {
- System.out.printf("[%s] Consuming Message. Id: %d, Data: %f\n", Thread.currentThread().getName(), message.getId(), message.getData());
+ log.info(String.format("[%s] Consuming Message. Id: %d, Data: %f%n",
+ Thread.currentThread().getName(), message.getId(), message.getData()));
//Sleeping on random time to make it realistic
ThreadUtil.sleep((long) (message.getData() * 100));
@@ -45,7 +48,7 @@ public class Consumer implements Runnable {
}
public void stop() {
- runFlag = false;
+ dataQueue.runFlag = false;
dataQueue.notifyAllForEmpty();
}
}
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/DataQueue.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/DataQueue.java
index 6ab4fa2bc3..8867ddeb63 100644
--- a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/DataQueue.java
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/DataQueue.java
@@ -9,6 +9,8 @@ public class DataQueue {
private final Object FULL_QUEUE = new Object();
private final Object EMPTY_QUEUE = new Object();
+ public boolean runFlag = true;
+
DataQueue(int maxSize) {
this.maxSize = maxSize;
}
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Producer.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Producer.java
index 80d693bd97..ca89d0c866 100644
--- a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Producer.java
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/Producer.java
@@ -1,14 +1,15 @@
package com.baeldung.producerconsumer;
+import java.util.logging.Logger;
+
public class Producer implements Runnable {
+ private static final Logger log = Logger.getLogger(Producer.class.getCanonicalName());
private final DataQueue dataQueue;
- private volatile boolean runFlag;
private static int idSequence = 0;
public Producer(DataQueue dataQueue) {
this.dataQueue = dataQueue;
- runFlag = true;
}
@Override
@@ -17,28 +18,31 @@ public class Producer implements Runnable {
}
public void produce() {
- while (runFlag) {
- Message message = generateMessage();
- while (dataQueue.isFull()) {
- try {
- dataQueue.waitOnFull();
- } catch (InterruptedException e) {
- e.printStackTrace();
+ while (dataQueue.runFlag) {
+ synchronized (dataQueue) {
+ while (dataQueue.isFull() && dataQueue.runFlag) {
+ try {
+ dataQueue.waitOnFull();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ break;
+ }
+ }
+ if (!dataQueue.runFlag) {
break;
}
+ Message message = generateMessage();
+ dataQueue.add(message);
+ dataQueue.notifyAllForEmpty();
}
- if (!runFlag) {
- break;
- }
- dataQueue.add(message);
- dataQueue.notifyAllForEmpty();
}
- System.out.println("Producer Stopped");
+ log.info("Producer Stopped");
}
private Message generateMessage() {
- Message message = new Message(++idSequence, Math.random());
- System.out.printf("[%s] Generated Message. Id: %d, Data: %f\n", Thread.currentThread().getName(), message.getId(), message.getData());
+ Message message = new Message(incrementAndGetId(), Math.random());
+ log.info(String.format("[%s] Generated Message. Id: %d, Data: %f%n",
+ Thread.currentThread().getName(), message.getId(), message.getData()));
//Sleeping on random time to make it realistic
ThreadUtil.sleep((long) (message.getData() * 100));
@@ -46,8 +50,12 @@ public class Producer implements Runnable {
return message;
}
+ private static int incrementAndGetId() {
+ return ++idSequence;
+ }
+
public void stop() {
- runFlag = false;
+ dataQueue.runFlag = false;
dataQueue.notifyAllForFull();
}
}
diff --git a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/SimpleProducerConsumerDemonstrator.java b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/SimpleProducerConsumerDemonstrator.java
index f1f6e1cc9c..500dc9ca07 100644
--- a/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/SimpleProducerConsumerDemonstrator.java
+++ b/core-java-modules/core-java-concurrency-advanced-4/src/main/java/com/baeldung/producerconsumer/SimpleProducerConsumerDemonstrator.java
@@ -2,10 +2,12 @@ package com.baeldung.producerconsumer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
+import java.util.logging.Logger;
import static com.baeldung.producerconsumer.ThreadUtil.sleep;
public class SimpleProducerConsumerDemonstrator {
+ private static final Logger log = Logger.getLogger(SimpleProducerConsumerDemonstrator.class.getCanonicalName());
BlockingQueue blockingQueue = new LinkedBlockingDeque<>(5);
private void produce() {
@@ -17,7 +19,7 @@ public class SimpleProducerConsumerDemonstrator {
e.printStackTrace();
break;
}
- System.out.printf("[%s] Value produced: %f\n", Thread.currentThread().getName(), value);
+ log.info(String.format("[%s] Value produced: %f%n", Thread.currentThread().getName(), value));
}
}
@@ -31,7 +33,7 @@ public class SimpleProducerConsumerDemonstrator {
break;
}
// Consume value
- System.out.printf("[%s] Value consumed: %f\n", Thread.currentThread().getName(), value);
+ log.info(String.format("[%s] Value consumed: %f%n", Thread.currentThread().getName(), value));
}
}
diff --git a/core-java-modules/core-java-concurrency-advanced/pom.xml b/core-java-modules/core-java-concurrency-advanced/pom.xml
index 3c726e1284..18cfc5371c 100644
--- a/core-java-modules/core-java-concurrency-advanced/pom.xml
+++ b/core-java-modules/core-java-concurrency-advanced/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-advanced
- 0.1.0-SNAPSHOT
core-java-concurrency-advanced
jar
diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java
index 389e25719b..d23f1faa69 100644
--- a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java
+++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/countdownlatch/Worker.java
@@ -1,9 +1,14 @@
package com.baeldung.concurrent.countdownlatch;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class Worker implements Runnable {
+
+ private static Logger log = LoggerFactory.getLogger(Worker.class);
private final List outputScraper;
private final CountDownLatch countDownLatch;
@@ -15,7 +20,7 @@ public class Worker implements Runnable {
@Override
public void run() {
// Do some work
- System.out.println("Doing some logic");
+ log.debug("Doing some logic");
outputScraper.add("Counted down");
countDownLatch.countDown();
}
diff --git a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java
index c022c02085..44f84ad77c 100644
--- a/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java
+++ b/core-java-modules/core-java-concurrency-advanced/src/main/java/com/baeldung/concurrent/phaser/LongRunningAction.java
@@ -1,8 +1,13 @@
package com.baeldung.concurrent.phaser;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.util.concurrent.Phaser;
class LongRunningAction implements Runnable {
+
+ private static Logger log = LoggerFactory.getLogger(LongRunningAction.class);
private String threadName;
private Phaser ph;
@@ -14,18 +19,18 @@ class LongRunningAction implements Runnable {
@Override
public void run() {
- System.out.println("This is phase " + ph.getPhase());
- System.out.println("Thread " + threadName + " before long running action");
+ log.info("This is phase {}", ph.getPhase());
+ log.info("Thread {} before long running action", threadName);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
-
- System.out.println("Thread " + threadName + " action completed and waiting for others");
+
+ log.debug("Thread {} action completed and waiting for others", threadName);
ph.arriveAndAwaitAdvance();
- System.out.println("Thread " + threadName + " proceeding in phase " + ph.getPhase());
+ log.debug("Thread {} proceeding in phase {}", threadName, ph.getPhase());
ph.arriveAndDeregister();
}
diff --git a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java
index 88c18b5149..384a1837c1 100644
--- a/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java
+++ b/core-java-modules/core-java-concurrency-advanced/src/test/java/com/baeldung/concurrent/phaser/PhaserUnitTest.java
@@ -4,6 +4,9 @@ import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
@@ -13,6 +16,8 @@ import static junit.framework.TestCase.assertEquals;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PhaserUnitTest {
+ private static Logger log = LoggerFactory.getLogger(PhaserUnitTest.class);
+
@Test
public void givenPhaser_whenCoordinateWorksBetweenThreads_thenShouldCoordinateBetweenMultiplePhases() {
//given
@@ -26,19 +31,19 @@ public class PhaserUnitTest {
executorService.submit(new LongRunningAction("thread-3", ph));
//then
- System.out.println("Thread " + Thread.currentThread().getName() + " waiting for others");
+ log.debug("Thread {} waiting for others", Thread.currentThread().getName());
ph.arriveAndAwaitAdvance();
- System.out.println("Thread " + Thread.currentThread().getName() + " proceeding in phase " + ph.getPhase());
+ log.debug("Thread {} proceeding in phase {}", Thread.currentThread().getName(), ph.getPhase());
assertEquals(1, ph.getPhase());
//and
executorService.submit(new LongRunningAction("thread-4", ph));
executorService.submit(new LongRunningAction("thread-5", ph));
-
- System.out.println("Thread " + Thread.currentThread().getName() + " waiting for others");
+
+ log.debug("Thread {} waiting for others", Thread.currentThread().getName());
ph.arriveAndAwaitAdvance();
- System.out.println("Thread " + Thread.currentThread().getName() + " proceeding in phase " + ph.getPhase());
+ log.debug("Thread {} proceeding in phase {}", Thread.currentThread().getName(), ph.getPhase());
assertEquals(2, ph.getPhase());
diff --git a/httpclient4/src/main/resources/logback.xml b/core-java-modules/core-java-concurrency-advanced/src/test/resources/logback-test.xml
similarity index 100%
rename from httpclient4/src/main/resources/logback.xml
rename to core-java-modules/core-java-concurrency-advanced/src/test/resources/logback-test.xml
diff --git a/core-java-modules/core-java-concurrency-basic-2/pom.xml b/core-java-modules/core-java-concurrency-basic-2/pom.xml
index 9ca12da7fb..0cdfd68f03 100644
--- a/core-java-modules/core-java-concurrency-basic-2/pom.xml
+++ b/core-java-modules/core-java-concurrency-basic-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-basic-2
- 0.1.0-SNAPSHOT
core-java-concurrency-basic-2
jar
diff --git a/core-java-modules/core-java-concurrency-basic-3/README.md b/core-java-modules/core-java-concurrency-basic-3/README.md
index 477f37e00a..da148599b0 100644
--- a/core-java-modules/core-java-concurrency-basic-3/README.md
+++ b/core-java-modules/core-java-concurrency-basic-3/README.md
@@ -5,4 +5,6 @@ This module contains articles about basic Java concurrency.
### Relevant Articles:
- [How to Handle InterruptedException in Java](https://www.baeldung.com/java-interrupted-exception)
+- [Thread.sleep() vs Awaitility.await()](https://www.baeldung.com/java-thread-sleep-vs-awaitility-await)
+- [Is CompletableFuture Non-blocking?](https://www.baeldung.com/java-completablefuture-non-blocking)
- [[<-- Prev]](../core-java-concurrency-basic-2)
diff --git a/core-java-modules/core-java-concurrency-basic-3/pom.xml b/core-java-modules/core-java-concurrency-basic-3/pom.xml
index 7289877550..1983d3c163 100644
--- a/core-java-modules/core-java-concurrency-basic-3/pom.xml
+++ b/core-java-modules/core-java-concurrency-basic-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-basic-3
- 0.1.0-SNAPSHOT
core-java-concurrency-basic-3
jar
@@ -14,6 +13,15 @@
0.0.1-SNAPSHOT
+
+
+ org.awaitility
+ awaitility
+ ${awaitility.version}
+ test
+
+
+
core-java-concurrency-basic-3
@@ -28,12 +36,4 @@
4.2.0
-
-
- org.awaitility
- awaitility
- ${awaitility.version}
- test
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/NonBlockingExample.java b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/NonBlockingExample.java
new file mode 100644
index 0000000000..b97f7d0dee
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-basic-3/src/main/java/com/baeldung/concurrent/completablefuture/NonBlockingExample.java
@@ -0,0 +1,17 @@
+package com.baeldung.concurrent.completablefuture;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.CompletableFuture;
+
+public class NonBlockingExample {
+
+ private static final Logger logger = LoggerFactory.getLogger(NonBlockingExample.class);
+
+ public static void main(String[] args) {
+ CompletableFuture.supplyAsync(() -> "Baeldung")
+ .thenApply(String::length)
+ .thenAccept(s -> logger.info(String.valueOf(s)));
+ }
+}
diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java
index c437b08b34..4a400f7beb 100644
--- a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java
+++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/RequestProcessorUnitTest.java
@@ -20,7 +20,8 @@ public class RequestProcessorUnitTest {
void whenWaitingWithThreadSleep_thenStatusIsDone() throws InterruptedException {
String requestId = requestProcessor.processRequest();
- Thread.sleep(2000);
+ //The sleep value should be greater than the maximum time the request takes to complete
+ Thread.sleep(2010);
assertEquals("DONE", requestProcessor.getStatus(requestId));
}
@@ -31,7 +32,8 @@ public class RequestProcessorUnitTest {
String requestId = requestProcessor.processRequest();
Awaitility.await()
- .atMost(2, TimeUnit.SECONDS)
+ //The timeout value should exceed the maximum time the request takes to complete, for the time amount of a poll (500 ms)
+ .atMost(2501, TimeUnit.MILLISECONDS)
.pollDelay(500, TimeUnit.MILLISECONDS)
.until(() -> requestProcessor.getStatus(requestId), not(equalTo("PROCESSING")));
diff --git a/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/BlockingUnitTest.java b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/BlockingUnitTest.java
new file mode 100644
index 0000000000..75d8d73c2f
--- /dev/null
+++ b/core-java-modules/core-java-concurrency-basic-3/src/test/java/com/baeldung/concurrent/completablefuture/BlockingUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.concurrent.completablefuture;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+class BlockingUnitTest {
+
+ @Test
+ void givenCompletableFuture_whenGet_thenReturnResult()
+ throws ExecutionException, InterruptedException {
+ CompletableFuture completableFuture = CompletableFuture
+ .supplyAsync(() -> "Baeldung")
+ .thenApply(String::toUpperCase);
+
+ assertEquals("BAELDUNG", completableFuture.get());
+ }
+
+ @Test
+ void givenCompletableFuture_whenJoin_thenReturnResult() {
+ CompletableFuture completableFuture = CompletableFuture
+ .supplyAsync(() -> "Blocking")
+ .thenApply(s -> s + " Operation")
+ .thenApply(String::toLowerCase);
+
+ assertEquals("blocking operation", completableFuture.join());
+ }
+}
diff --git a/core-java-modules/core-java-concurrency-basic/pom.xml b/core-java-modules/core-java-concurrency-basic/pom.xml
index 1e3157291a..36d59f254c 100644
--- a/core-java-modules/core-java-concurrency-basic/pom.xml
+++ b/core-java-modules/core-java-concurrency-basic/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-basic
- 0.1.0-SNAPSHOT
core-java-concurrency-basic
jar
diff --git a/core-java-modules/core-java-concurrency-collections-2/pom.xml b/core-java-modules/core-java-concurrency-collections-2/pom.xml
index 9a95662fae..a85721e474 100644
--- a/core-java-modules/core-java-concurrency-collections-2/pom.xml
+++ b/core-java-modules/core-java-concurrency-collections-2/pom.xml
@@ -3,7 +3,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-collections-2
- 0.1.0-SNAPSHOT
core-java-concurrency-collections-2
jar
diff --git a/core-java-modules/core-java-concurrency-collections/pom.xml b/core-java-modules/core-java-concurrency-collections/pom.xml
index 8b8d2fe03b..a35da4ce49 100644
--- a/core-java-modules/core-java-concurrency-collections/pom.xml
+++ b/core-java-modules/core-java-concurrency-collections/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-collections
- 0.1.0-SNAPSHOT
core-java-concurrency-collections
jar
diff --git a/core-java-modules/core-java-concurrency-simple/pom.xml b/core-java-modules/core-java-concurrency-simple/pom.xml
index 159a105035..a16df4fc97 100644
--- a/core-java-modules/core-java-concurrency-simple/pom.xml
+++ b/core-java-modules/core-java-concurrency-simple/pom.xml
@@ -3,7 +3,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-concurrency-simple
- 0.1.0-SNAPSHOT
core-java-concurrency-simple
jar
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/sandbox/SandboxJavaManualTest.java b/core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/sandbox/SandboxJavaManualTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/sandbox/SandboxJavaManualTest.java
rename to core-java-modules/core-java-concurrency-simple/src/test/java/com/baeldung/sandbox/SandboxJavaManualTest.java
diff --git a/core-java-modules/core-java-console/pom.xml b/core-java-modules/core-java-console/pom.xml
index 200e2707dd..4debf9388b 100644
--- a/core-java-modules/core-java-console/pom.xml
+++ b/core-java-modules/core-java-console/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-console
- 0.1.0-SNAPSHOT
core-java-console
jar
diff --git a/core-java-modules/core-java-date-operations-1/pom.xml b/core-java-modules/core-java-date-operations-1/pom.xml
index c5d46723d8..5bfbb5bab0 100644
--- a/core-java-modules/core-java-date-operations-1/pom.xml
+++ b/core-java-modules/core-java-date-operations-1/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-date-operations-1
- ${project.parent.version}
core-java-date-operations-1
jar
diff --git a/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/date/DayOfTheWeek.java b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/date/DayOfTheWeek.java
new file mode 100644
index 0000000000..a5622038ce
--- /dev/null
+++ b/core-java-modules/core-java-date-operations-1/src/main/java/com/baeldung/date/DayOfTheWeek.java
@@ -0,0 +1,41 @@
+package com.baeldung.date;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.temporal.TemporalAdjusters;
+import java.time.temporal.TemporalField;
+import java.time.temporal.WeekFields;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Locale;
+
+public class DayOfTheWeek {
+
+ public LocalDate getDateOfFirstDayOfTheWeek_UsingLocale(LocalDate localDate, Locale locale){
+ TemporalField fieldISO = WeekFields.of(locale).dayOfWeek();
+ return localDate.with(fieldISO, 1);
+ }
+
+ public LocalDate getDateOfFirstDayOfTheWeek_UsingISODayOfWeek(LocalDate localDate){
+ TemporalField dayOfWeek = WeekFields.ISO.dayOfWeek();
+ return localDate.with(dayOfWeek, dayOfWeek.range().getMinimum());
+ }
+
+ public LocalDate getDateOfFirstDayOfTheWeek_UsingDayOfWeek(LocalDate localDate){
+ DayOfWeek weekStart = DayOfWeek.MONDAY;
+ return localDate.with(TemporalAdjusters.previousOrSame(weekStart));
+ }
+
+ public LocalDate getDateOfFirstDayOfTheWeek_UsingCalendar(LocalDate localDate){
+ Calendar calendar = Calendar.getInstance();
+ ZoneId zoneId = ZoneId.systemDefault();
+ Date date = Date.from(localDate.atStartOfDay(zoneId).toInstant());
+ calendar.setTime(date);
+ while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
+ calendar.add(Calendar.DATE, -1);
+ }
+ return LocalDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId()).toLocalDate();
+ }
+}
diff --git a/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/DayOfTheWeekUnitTest.java b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/DayOfTheWeekUnitTest.java
new file mode 100644
index 0000000000..9b29d2cc19
--- /dev/null
+++ b/core-java-modules/core-java-date-operations-1/src/test/java/com/baeldung/date/DayOfTheWeekUnitTest.java
@@ -0,0 +1,68 @@
+package com.baeldung.date;
+
+import java.time.LocalDate;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class DayOfTheWeekUnitTest {
+
+ DayOfTheWeek dayOfTheWeek = new DayOfTheWeek();
+
+ @Test
+ public void whenInputDateIsMonday_ThenFirstDayOfWeekIsSameAsInputDay() {
+ TestData testData = new TestData(LocalDate.of(2023, 2, 20),LocalDate.of(2023,2,20) );
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingISODayOfWeek(testData.inputDate));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingCalendar(testData.inputDate));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingDayOfWeek(testData.inputDate));
+ }
+
+ @Test
+ public void whenInputDateIsSunday_ThenFirstDayOfWeekIsPreviousWeekMonday() {
+ TestData testData = new TestData(LocalDate.of(2023, 2, 19), LocalDate.of(2023,2,13));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingISODayOfWeek(testData.inputDate));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingCalendar(testData.inputDate));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingDayOfWeek(testData.inputDate));
+ }
+
+ @Test
+ void whenInputDateIsNewYearMidWeek_ThenFirstDayOfWeekIsPreviousYearLastMonday() {
+ TestData testData = new TestData(LocalDate.of(2022, 1, 1), LocalDate.of(2021,12,27));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingISODayOfWeek(testData.inputDate));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingCalendar(testData.inputDate));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingDayOfWeek(testData.inputDate));
+ }
+
+ @Test
+ void whenInputDataHasLocale_ThenFirstDayOfWeekIsMondayOrSundayInDifferentLocale() {
+ List testData = Arrays.asList(
+ new TestData(LocalDate.of(2023, 2, 20),Locale.FRANCE,LocalDate.of(2023,2,20)),
+ new TestData(LocalDate.of(2023, 2, 19),Locale.FRANCE,LocalDate.of(2023,2,13)),
+ new TestData(LocalDate.of(2022, 1, 1),Locale.FRANCE,LocalDate.of(2021,12,27)),
+ // day of week starts from sunday in USA
+ new TestData(LocalDate.of(2023, 2, 20),Locale.US,LocalDate.of(2023,2,19)),
+ new TestData(LocalDate.of(2023, 2, 19),Locale.US,LocalDate.of(2023,2,19)),
+ new TestData(LocalDate.of(2022, 1, 1),Locale.US,LocalDate.of(2021,12,26))
+ );
+ testData.forEach(data -> Assertions.assertEquals(data.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingLocale(data.inputDate,data.inputLocale)));
+ }
+
+ private static class TestData{
+ private final LocalDate inputDate;
+ private Locale inputLocale;
+ private final LocalDate expectedOutput;
+
+ private TestData(LocalDate inputDate, LocalDate expectedOutput){
+ this.inputDate = inputDate;
+ this.expectedOutput = expectedOutput;
+ }
+
+ private TestData(LocalDate inputDate, Locale inputLocale, LocalDate expectedOutput){
+ this.inputDate = inputDate;
+ this.inputLocale = inputLocale;
+ this.expectedOutput = expectedOutput;
+ }
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-date-operations-2/pom.xml b/core-java-modules/core-java-date-operations-2/pom.xml
index 461ba70b62..c6a22a4166 100644
--- a/core-java-modules/core-java-date-operations-2/pom.xml
+++ b/core-java-modules/core-java-date-operations-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-date-operations-2
- ${project.parent.version}
core-java-date-operations-2
jar
diff --git a/core-java-modules/core-java-date-operations-3/README.md b/core-java-modules/core-java-date-operations-3/README.md
index 944ab4bd1b..0d36f9c8a2 100644
--- a/core-java-modules/core-java-date-operations-3/README.md
+++ b/core-java-modules/core-java-date-operations-3/README.md
@@ -5,4 +5,5 @@ This module contains articles about date operations in Java.
- [Create Date From Unix Timestamp in Java](https://www.baeldung.com/java-date-unix-timestamp)
- [Convert java.util.Date to java.sql.Date](https://www.baeldung.com/java-convert-util-date-to-sql)
+- [How to Determine Date of the First Day of the Week Using LocalDate in Java](https://www.baeldung.com/java-first-day-of-the-week)
- [[<-- Prev]](/core-java-modules/core-java-date-operations-2)
diff --git a/core-java-modules/core-java-date-operations-3/pom.xml b/core-java-modules/core-java-date-operations-3/pom.xml
index 8713139ba8..89c21a31c1 100644
--- a/core-java-modules/core-java-date-operations-3/pom.xml
+++ b/core-java-modules/core-java-date-operations-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-date-operations-3
- ${project.parent.version}
core-java-date-operations-3
jar
@@ -14,10 +13,4 @@
0.0.1-SNAPSHOT
-
-
-
-
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java-date-operations-3/src/main/java/com/baeldung/date/DayOfTheWeek.java b/core-java-modules/core-java-date-operations-3/src/main/java/com/baeldung/date/DayOfTheWeek.java
new file mode 100644
index 0000000000..a5622038ce
--- /dev/null
+++ b/core-java-modules/core-java-date-operations-3/src/main/java/com/baeldung/date/DayOfTheWeek.java
@@ -0,0 +1,41 @@
+package com.baeldung.date;
+
+import java.time.DayOfWeek;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.temporal.TemporalAdjusters;
+import java.time.temporal.TemporalField;
+import java.time.temporal.WeekFields;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Locale;
+
+public class DayOfTheWeek {
+
+ public LocalDate getDateOfFirstDayOfTheWeek_UsingLocale(LocalDate localDate, Locale locale){
+ TemporalField fieldISO = WeekFields.of(locale).dayOfWeek();
+ return localDate.with(fieldISO, 1);
+ }
+
+ public LocalDate getDateOfFirstDayOfTheWeek_UsingISODayOfWeek(LocalDate localDate){
+ TemporalField dayOfWeek = WeekFields.ISO.dayOfWeek();
+ return localDate.with(dayOfWeek, dayOfWeek.range().getMinimum());
+ }
+
+ public LocalDate getDateOfFirstDayOfTheWeek_UsingDayOfWeek(LocalDate localDate){
+ DayOfWeek weekStart = DayOfWeek.MONDAY;
+ return localDate.with(TemporalAdjusters.previousOrSame(weekStart));
+ }
+
+ public LocalDate getDateOfFirstDayOfTheWeek_UsingCalendar(LocalDate localDate){
+ Calendar calendar = Calendar.getInstance();
+ ZoneId zoneId = ZoneId.systemDefault();
+ Date date = Date.from(localDate.atStartOfDay(zoneId).toInstant());
+ calendar.setTime(date);
+ while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
+ calendar.add(Calendar.DATE, -1);
+ }
+ return LocalDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId()).toLocalDate();
+ }
+}
diff --git a/core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/date/DayOfTheWeekUnitTest.java b/core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/date/DayOfTheWeekUnitTest.java
new file mode 100644
index 0000000000..cdc0eb1d6b
--- /dev/null
+++ b/core-java-modules/core-java-date-operations-3/src/test/java/com/baeldung/date/DayOfTheWeekUnitTest.java
@@ -0,0 +1,68 @@
+package com.baeldung.date;
+
+import java.time.LocalDate;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class DayOfTheWeekUnitTest {
+
+ DayOfTheWeek dayOfTheWeek = new DayOfTheWeek();
+
+ @Test
+ void whenInputDateIsMonday_ThenFirstDayOfWeekIsSameAsInputDay() {
+ TestData testData = new TestData(LocalDate.of(2023, 2, 20),LocalDate.of(2023,2,20) );
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingISODayOfWeek(testData.inputDate));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingCalendar(testData.inputDate));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingDayOfWeek(testData.inputDate));
+ }
+
+ @Test
+ void whenInputDateIsSunday_ThenFirstDayOfWeekIsPreviousWeekMonday() {
+ TestData testData = new TestData(LocalDate.of(2023, 2, 19), LocalDate.of(2023,2,13));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingISODayOfWeek(testData.inputDate));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingCalendar(testData.inputDate));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingDayOfWeek(testData.inputDate));
+ }
+
+ @Test
+ void whenInputDateIsNewYearMidWeek_ThenFirstDayOfWeekIsPreviousYearLastMonday() {
+ TestData testData = new TestData(LocalDate.of(2022, 1, 1), LocalDate.of(2021,12,27));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingISODayOfWeek(testData.inputDate));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingCalendar(testData.inputDate));
+ Assertions.assertEquals(testData.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingDayOfWeek(testData.inputDate));
+ }
+
+ @Test
+ void whenInputDataHasLocale_ThenFirstDayOfWeekIsMondayOrSundayInDifferentLocale() {
+ List testData = Arrays.asList(
+ new TestData(LocalDate.of(2023, 2, 20),Locale.FRANCE,LocalDate.of(2023,2,20)),
+ new TestData(LocalDate.of(2023, 2, 19),Locale.FRANCE,LocalDate.of(2023,2,13)),
+ new TestData(LocalDate.of(2022, 1, 1),Locale.FRANCE,LocalDate.of(2021,12,27)),
+ // day of week starts from sunday in USA
+ new TestData(LocalDate.of(2023, 2, 20),Locale.US,LocalDate.of(2023,2,19)),
+ new TestData(LocalDate.of(2023, 2, 19),Locale.US,LocalDate.of(2023,2,19)),
+ new TestData(LocalDate.of(2022, 1, 1),Locale.US,LocalDate.of(2021,12,26))
+ );
+ testData.forEach(data -> Assertions.assertEquals(data.expectedOutput, dayOfTheWeek.getDateOfFirstDayOfTheWeek_UsingLocale(data.inputDate,data.inputLocale)));
+ }
+
+ private static class TestData{
+ private final LocalDate inputDate;
+ private Locale inputLocale;
+ private final LocalDate expectedOutput;
+
+ private TestData(LocalDate inputDate, LocalDate expectedOutput){
+ this.inputDate = inputDate;
+ this.expectedOutput = expectedOutput;
+ }
+
+ private TestData(LocalDate inputDate, Locale inputLocale, LocalDate expectedOutput){
+ this.inputDate = inputDate;
+ this.inputLocale = inputLocale;
+ this.expectedOutput = expectedOutput;
+ }
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-datetime-string-2/pom.xml b/core-java-modules/core-java-datetime-string-2/pom.xml
index 3ec9ccaac4..458fba25a2 100644
--- a/core-java-modules/core-java-datetime-string-2/pom.xml
+++ b/core-java-modules/core-java-datetime-string-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-datetime-string-2
- ${project.parent.version}
core-java-datetime-string-2
jar
diff --git a/core-java-modules/core-java-datetime-string/pom.xml b/core-java-modules/core-java-datetime-string/pom.xml
index 2b3c2edb02..3efb2fe728 100644
--- a/core-java-modules/core-java-datetime-string/pom.xml
+++ b/core-java-modules/core-java-datetime-string/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-datetime-string
- ${project.parent.version}
core-java-datetime-string
jar
@@ -20,7 +19,6 @@
commons-lang3
${commons-lang3.version}
-
commons-validator
commons-validator
diff --git a/core-java-modules/core-java-documentation/README.md b/core-java-modules/core-java-documentation/README.md
new file mode 100644
index 0000000000..b66b9e8c05
--- /dev/null
+++ b/core-java-modules/core-java-documentation/README.md
@@ -0,0 +1,6 @@
+## Core Java Documentation
+
+### Relevant Articles:
+
+- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
+
diff --git a/core-java-modules/core-java-documentation/pom.xml b/core-java-modules/core-java-documentation/pom.xml
new file mode 100644
index 0000000000..be18af1b10
--- /dev/null
+++ b/core-java-modules/core-java-documentation/pom.xml
@@ -0,0 +1,41 @@
+
+
+ 4.0.0
+ core-java-documentation
+ 0.1.0-SNAPSHOT
+ core-java-documentation
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ ${maven-javadoc-plugin.version}
+
+
+ ${target.version}
+
+
+
+
+
+
+
+ 3.0.0-M1
+ 1.8
+ 1.8
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/javadoc/CodeSnippetFormatting.java b/core-java-modules/core-java-documentation/src/main/java/com/baeldung/javadoc/CodeSnippetFormatting.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/javadoc/CodeSnippetFormatting.java
rename to core-java-modules/core-java-documentation/src/main/java/com/baeldung/javadoc/CodeSnippetFormatting.java
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/javadoc/Person.java b/core-java-modules/core-java-documentation/src/main/java/com/baeldung/javadoc/Person.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/javadoc/Person.java
rename to core-java-modules/core-java-documentation/src/main/java/com/baeldung/javadoc/Person.java
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java b/core-java-modules/core-java-documentation/src/main/java/com/baeldung/javadoc/SuperHero.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java
rename to core-java-modules/core-java-documentation/src/main/java/com/baeldung/javadoc/SuperHero.java
diff --git a/core-java-modules/core-java-exceptions-2/pom.xml b/core-java-modules/core-java-exceptions-2/pom.xml
index 9103672cd4..8bf5605f09 100644
--- a/core-java-modules/core-java-exceptions-2/pom.xml
+++ b/core-java-modules/core-java-exceptions-2/pom.xml
@@ -5,8 +5,6 @@
core-java-exceptions-2
core-java-exceptions-2
jar
-
- http://maven.apache.org
com.baeldung.core-java-modules
diff --git a/core-java-modules/core-java-exceptions-3/pom.xml b/core-java-modules/core-java-exceptions-3/pom.xml
index 7eaa57edf1..6ef979b54a 100644
--- a/core-java-modules/core-java-exceptions-3/pom.xml
+++ b/core-java-modules/core-java-exceptions-3/pom.xml
@@ -3,9 +3,7 @@
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.exceptions
core-java-exceptions-3
- 0.1.0-SNAPSHOT
core-java-exceptions-3
jar
diff --git a/core-java-modules/core-java-exceptions-4/pom.xml b/core-java-modules/core-java-exceptions-4/pom.xml
index e9eb1bf379..c41c782fcc 100644
--- a/core-java-modules/core-java-exceptions-4/pom.xml
+++ b/core-java-modules/core-java-exceptions-4/pom.xml
@@ -3,9 +3,7 @@
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.exceptions
core-java-exceptions-4
- 0.1.0-SNAPSHOT
core-java-exceptions-4
jar
diff --git a/core-java-modules/core-java-exceptions/pom.xml b/core-java-modules/core-java-exceptions/pom.xml
index 866248b416..0bb6e86c76 100644
--- a/core-java-modules/core-java-exceptions/pom.xml
+++ b/core-java-modules/core-java-exceptions/pom.xml
@@ -3,9 +3,7 @@
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.exceptions
core-java-exceptions
- 0.1.0-SNAPSHOT
core-java-exceptions
jar
diff --git a/core-java-modules/core-java-function/pom.xml b/core-java-modules/core-java-function/pom.xml
index ebc34aaf4b..e8b538ad24 100644
--- a/core-java-modules/core-java-function/pom.xml
+++ b/core-java-modules/core-java-function/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-function
- 0.1.0-SNAPSHOT
core-java-function
jar
diff --git a/core-java-modules/core-java-functional/pom.xml b/core-java-modules/core-java-functional/pom.xml
index 9ad47f8133..4b0bf9f730 100644
--- a/core-java-modules/core-java-functional/pom.xml
+++ b/core-java-modules/core-java-functional/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-functional
- 0.1.0-SNAPSHOT
core-java-functional
jar
diff --git a/core-java-modules/core-java-hex/pom.xml b/core-java-modules/core-java-hex/pom.xml
index afac1c4d66..71e6b15b2e 100644
--- a/core-java-modules/core-java-hex/pom.xml
+++ b/core-java-modules/core-java-hex/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-hex
- 0.1.0-SNAPSHOT
core-java-hex
jar
@@ -14,12 +13,4 @@
0.0.1-SNAPSHOT
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java-httpclient/pom.xml b/core-java-modules/core-java-httpclient/pom.xml
index 3df0447ff0..f3730d1b45 100644
--- a/core-java-modules/core-java-httpclient/pom.xml
+++ b/core-java-modules/core-java-httpclient/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-httpclient
- 0.1.0-SNAPSHOT
core-java-httpclient
jar
diff --git a/core-java-modules/core-java-io-2/pom.xml b/core-java-modules/core-java-io-2/pom.xml
index b5f43d5a94..8f4f2518fe 100644
--- a/core-java-modules/core-java-io-2/pom.xml
+++ b/core-java-modules/core-java-io-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io-2
- 0.1.0-SNAPSHOT
core-java-io-2
jar
diff --git a/core-java-modules/core-java-io-3/pom.xml b/core-java-modules/core-java-io-3/pom.xml
index 4901133854..26ea301837 100644
--- a/core-java-modules/core-java-io-3/pom.xml
+++ b/core-java-modules/core-java-io-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io-3
- 0.1.0-SNAPSHOT
core-java-io-3
jar
diff --git a/core-java-modules/core-java-io-4/pom.xml b/core-java-modules/core-java-io-4/pom.xml
index 2cc05698fc..30177e5c09 100644
--- a/core-java-modules/core-java-io-4/pom.xml
+++ b/core-java-modules/core-java-io-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io-4
- 0.1.0-SNAPSHOT
core-java-io-4
jar
diff --git a/core-java-modules/core-java-io-4/src/main/java/com/baeldung/iostreams/DataStream.java b/core-java-modules/core-java-io-4/src/main/java/com/baeldung/iostreams/DataStream.java
index 71c55d31b9..84d6c1ad80 100644
--- a/core-java-modules/core-java-io-4/src/main/java/com/baeldung/iostreams/DataStream.java
+++ b/core-java-modules/core-java-io-4/src/main/java/com/baeldung/iostreams/DataStream.java
@@ -7,12 +7,14 @@ public class DataStream {
PrintStream out = new PrintStream(fileName);
out.print(content);
out.flush();
+ out.close();
}
public static void textDataProcessingCharStream(String fileName, String content) throws IOException {
PrintWriter out = new PrintWriter(fileName);
out.print(content);
out.flush();
+ out.close();
}
public static void nonTextDataProcessing(String fileName, String streamOutputFile, String writerOutputFile) throws IOException {
@@ -33,5 +35,6 @@ public class DataStream {
writer.write(c);
}
writer.close();
+ inputStream.close();
}
}
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-4/src/test/java/com/baeldung/iostreams/DataStreamUnitTest.java b/core-java-modules/core-java-io-4/src/test/java/com/baeldung/iostreams/DataStreamUnitTest.java
index a5a53d5a08..7d697171ce 100644
--- a/core-java-modules/core-java-io-4/src/test/java/com/baeldung/iostreams/DataStreamUnitTest.java
+++ b/core-java-modules/core-java-io-4/src/test/java/com/baeldung/iostreams/DataStreamUnitTest.java
@@ -23,32 +23,29 @@ public class DataStreamUnitTest {
@Test
public void whenUsingByteStream_thenWriteTextToFile() throws IOException {
- DataStream dataStream = new DataStream();
- dataStream.textDataProcessingByteStream(dataProcessingTextFile, textFileContent);
+ DataStream.textDataProcessingByteStream(dataProcessingTextFile, textFileContent);
File file = new File(dataProcessingTextFile);
assertTrue(file.exists());
assertEquals(textFileContent, FileUtils.readFileToString(file, "utf-8"));
- Files.delete(Paths.get(dataProcessingTextFile));
+ Files.deleteIfExists(Paths.get(dataProcessingTextFile));
}
@Test
public void whenUsingCharStream_thenWriteTextToFile() throws IOException {
- DataStream dataStream = new DataStream();
- dataStream.textDataProcessingCharStream(dataProcessingTextFile, textFileContent);
+ DataStream.textDataProcessingCharStream(dataProcessingTextFile, textFileContent);
File file = new File(dataProcessingTextFile);
assertTrue(file.exists());
assertEquals(textFileContent, FileUtils.readFileToString(file, "utf-8"));
- Files.delete(Paths.get(dataProcessingTextFile));
+ Files.deleteIfExists(Paths.get(dataProcessingTextFile));
}
@Test
public void whenUsingStreams_thenWriteNonTextData() throws IOException {
- DataStream dataStream = new DataStream();
- dataStream.nonTextDataProcessing(dataProcessingImageFile, dataProcessingByteStreamFile, dataProcessingCharStreamFile);
+ DataStream.nonTextDataProcessing(dataProcessingImageFile, dataProcessingByteStreamFile, dataProcessingCharStreamFile);
File file = new File(dataProcessingImageFile);
File byteStreamOutputFile = new File(dataProcessingByteStreamFile);
@@ -60,7 +57,7 @@ public class DataStreamUnitTest {
assertTrue(FileUtils.contentEquals(file, byteStreamOutputFile));
assertFalse(FileUtils.contentEquals(file, charStreamOutputFile));
- Files.delete(Paths.get(dataProcessingByteStreamFile));
- Files.delete(Paths.get(dataProcessingCharStreamFile));
+ Files.deleteIfExists(Paths.get(dataProcessingByteStreamFile));
+ Files.deleteIfExists(Paths.get(dataProcessingCharStreamFile));
}
}
diff --git a/core-java-modules/core-java-io-4/src/test/resources/iostreams/TestFile.txt b/core-java-modules/core-java-io-4/src/test/resources/iostreams/TestFile.txt
new file mode 100644
index 0000000000..5dd01c177f
--- /dev/null
+++ b/core-java-modules/core-java-io-4/src/test/resources/iostreams/TestFile.txt
@@ -0,0 +1 @@
+Hello, world!
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-apis-2/README.md b/core-java-modules/core-java-io-apis-2/README.md
index f3d72fe8b5..1633dc4828 100644
--- a/core-java-modules/core-java-io-apis-2/README.md
+++ b/core-java-modules/core-java-io-apis-2/README.md
@@ -5,3 +5,6 @@ This module contains articles about core Java input/output(IO) APIs.
### Relevant Articles:
- [Constructing a Relative Path From Two Absolute Paths in Java](https://www.baeldung.com/java-relative-path-absolute)
- [Java Scanner Taking a Character Input](https://www.baeldung.com/java-scanner-character-input)
+- [Get the Desktop Path in Java](https://www.baeldung.com/java-desktop-path)
+- [Integer.parseInt(scanner.nextLine()) and scanner.nextInt() in Java](https://www.baeldung.com/java-scanner-integer)
+- [Difference Between FileReader and BufferedReader in Java](https://www.baeldung.com/java-filereader-vs-bufferedreader)
diff --git a/core-java-modules/core-java-io-apis-2/pom.xml b/core-java-modules/core-java-io-apis-2/pom.xml
index 70c3a87da2..22c04cdc58 100644
--- a/core-java-modules/core-java-io-apis-2/pom.xml
+++ b/core-java-modules/core-java-io-apis-2/pom.xml
@@ -1,47 +1,115 @@
-
-
- 4.0.0
- core-java-io-apis-2
- 0.1.0-SNAPSHOT
- core-java-io-apis-2
- jar
-
-
- com.baeldung.core-java-modules
- core-java-modules
- 0.0.1-SNAPSHOT
-
-
-
-
-
- log4j
- log4j
- ${log4j.version}
-
-
- org.slf4j
- log4j-over-slf4j
- ${org.slf4j.version}
-
-
- org.projectlombok
- lombok
- ${lombok.version}
- provided
-
-
-
-
- core-java-io-apis-2
-
-
- src/main/resources
- true
-
-
-
-
+
+
+ 4.0.0
+ core-java-io-apis-2
+ core-java-io-apis-2
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+ log4j
+ log4j
+ ${log4j.version}
+
+
+ org.slf4j
+ log4j-over-slf4j
+ ${org.slf4j.version}
+
+
+ org.projectlombok
+ lombok
+ ${lombok.version}
+ provided
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ 5.7.2
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+
+ org.junit.jupiter
+ junit-jupiter-api
+ ${junit-jupiter-version}
+ test
+
+
+
+ org.junit.jupiter
+ junit-jupiter-params
+ ${junit-jupiter-version}
+ test
+
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ ${junit-jupiter-version}
+ test
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+ org.junit.jupiter
+ junit-jupiter
+
+
+ org.testng
+ testng
+ 7.1.0
+ test
+
+
+ org.testng
+ testng
+ 7.5
+ compile
+
+
+
+ 5.2.0
+
+
+ core-java-io-apis-2
+
+
+ src/main/resources
+ true
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/multinput/MultiInputs.java b/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/multinput/MultiInputs.java
new file mode 100644
index 0000000000..df799b2511
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/main/java/com/baeldung/multinput/MultiInputs.java
@@ -0,0 +1,36 @@
+package com.baeldung.multinput;
+
+import java.util.InputMismatchException;
+import java.util.Scanner;
+
+public class MultiInputs {
+ public void UsingSpaceDelimiter(){
+ Scanner scanner = new Scanner(System.in);
+ System.out.print("Enter two numbers: ");
+ int num1 = scanner.nextInt();
+ int num2 = scanner.nextInt();
+ System.out.println("You entered " + num1 + " and " + num2);
+
+ }
+ public void UsingREDelimiter(){
+ Scanner scanner = new Scanner(System.in);
+ scanner.useDelimiter("[\\s,]+");
+ System.out.print("Enter two numbers separated by a space or a comma: ");
+ int num1 = scanner.nextInt();
+ int num2 = scanner.nextInt();
+ System.out.println("You entered " + num1 + " and " + num2);
+
+ }
+ public void UsingCustomDelimiter(){
+ Scanner scanner = new Scanner(System.in);
+ scanner.useDelimiter(";");
+ System.out.print("Enter two numbers separated by a semicolon: ");
+ try { int num1 = scanner.nextInt();
+ int num2 = scanner.nextInt();
+ System.out.println("You entered " + num1 + " and " + num2); }
+ catch (InputMismatchException e)
+ { System.out.println("Invalid input. Please enter two integers separated by a semicolon."); }
+
+ }
+}
+
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/absolutetorelative/AbsoluteToRelativeUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/absolutetorelative/AbsoluteToRelativeUnitTest.java
index 0830b0808a..9b3f424a30 100644
--- a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/absolutetorelative/AbsoluteToRelativeUnitTest.java
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/absolutetorelative/AbsoluteToRelativeUnitTest.java
@@ -1,93 +1,92 @@
-package com.baeldung.absolutetorelative;
-
-import org.assertj.core.api.Assertions;
-import org.junit.jupiter.api.Test;
-
-import java.net.URI;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-
-public class AbsoluteToRelativeUnitTest {
-
- // given - until using Paths, no need to create physical files
- private final Path pathOne = Paths.get("/baeldung/bar/one.txt");
- private final Path pathTwo = Paths.get("/baeldung/bar/two.txt");
- private final Path pathThree = Paths.get("/baeldung/foo/three.txt");
-
- private final URI uriOne = pathOne.toUri();
- private final URI uriTwo = pathTwo.toUri();
- private final URI uriThree = pathThree.toUri();
-
- @Test
- public void givenAbsolutePaths_whenRelativizePathOneToPathTwo_thenRelativeIsReturned() {
- Path result = pathOne.relativize(pathTwo);
-
- Assertions.assertThat(result)
- .isRelative()
- .isEqualTo(Paths.get("../two.txt"));
- }
-
- @Test
- public void givenAbsolutePaths_whenRelativizePathTwoToPathOne_thenRelativeIsReturned() {
- Path result = pathTwo.relativize(pathOne);
-
- Assertions.assertThat(result)
- .isRelative()
- .isEqualTo(Paths.get("../one.txt"));
- }
-
- @Test
- public void givenAbsolutePaths_whenRelativizePathOneParentToPathTwo_thenRelativeIsReturned() {
- Path result = pathOne.getParent().relativize(pathTwo);
-
- Assertions.assertThat(result)
- .isRelative()
- .isEqualTo(Paths.get("two.txt"));
- }
-
- @Test
- public void givenAbsolutePaths_whenRelativizePathOneToPathThree_thenRelativeIsReturned() {
- Path result = pathOne.relativize(pathThree);
-
- Assertions.assertThat(result)
- .isRelative()
- .isEqualTo(Paths.get("../../foo/three.txt"));
- }
-
- @Test
- public void givenAbsolutePaths_whenRelativizePathThreeToPathOne_thenRelativeIsReturned() {
- Path result = pathThree.relativize(pathOne);
-
- Assertions.assertThat(result)
- .isRelative()
- .isEqualTo(Paths.get("../../bar/one.txt"));
- }
-
- @Test
- public void givenAbsoluteURIs_whenRelativizeUriOneToUriTwo_thenAbsoluteIsReturned() {
- URI result = uriOne.relativize(uriTwo);
-
- Assertions.assertThat(result)
- .asString()
- .contains("/baeldung/bar/two.txt");
- }
-
- @Test
- public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriTwo_thenRelativeIsReturned() {
- URI result = pathOne.getParent().toUri().relativize(uriTwo);
-
- Assertions.assertThat(result)
- .asString()
- .contains("two.txt");
- }
-
- @Test
- public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriThree_thenAbsoluteIsReturned() {
- URI result = pathOne.getParent().toUri().relativize(uriThree);
-
- Assertions.assertThat(result)
- .asString()
- .contains("/baeldung/foo/three.txt");
- }
-
-}
+package com.baeldung.absolutetorelative;
+
+import java.net.URI;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class AbsoluteToRelativeUnitTest {
+
+ // given - until using Paths, no need to create physical files
+ private final Path pathOne = Paths.get("/baeldung/bar/one.txt");
+ private final Path pathTwo = Paths.get("/baeldung/bar/two.txt");
+ private final Path pathThree = Paths.get("/baeldung/foo/three.txt");
+
+ private final URI uriOne = pathOne.toUri();
+ private final URI uriTwo = pathTwo.toUri();
+ private final URI uriThree = pathThree.toUri();
+
+ @Test
+ public void givenAbsolutePaths_whenRelativizePathOneToPathTwo_thenRelativeIsReturned() {
+ Path result = pathOne.relativize(pathTwo);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .isRelative()
+ .isEqualTo(Paths.get("../two.txt"));
+ }
+
+ @Test
+ public void givenAbsolutePaths_whenRelativizePathTwoToPathOne_thenRelativeIsReturned() {
+ Path result = pathTwo.relativize(pathOne);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .isRelative()
+ .isEqualTo(Paths.get("../one.txt"));
+ }
+
+ @Test
+ public void givenAbsolutePaths_whenRelativizePathOneParentToPathTwo_thenRelativeIsReturned() {
+ Path result = pathOne.getParent().relativize(pathTwo);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .isRelative()
+ .isEqualTo(Paths.get("two.txt"));
+ }
+
+ @Test
+ public void givenAbsolutePaths_whenRelativizePathOneToPathThree_thenRelativeIsReturned() {
+ Path result = pathOne.relativize(pathThree);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .isRelative()
+ .isEqualTo(Paths.get("../../foo/three.txt"));
+ }
+
+ @Test
+ public void givenAbsolutePaths_whenRelativizePathThreeToPathOne_thenRelativeIsReturned() {
+ Path result = pathThree.relativize(pathOne);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .isRelative()
+ .isEqualTo(Paths.get("../../bar/one.txt"));
+ }
+
+ @Test
+ public void givenAbsoluteURIs_whenRelativizeUriOneToUriTwo_thenAbsoluteIsReturned() {
+ URI result = uriOne.relativize(uriTwo);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .asString()
+ .contains("/baeldung/bar/two.txt");
+ }
+
+ @Test
+ public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriTwo_thenRelativeIsReturned() {
+ URI result = pathOne.getParent().toUri().relativize(uriTwo);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .asString()
+ .contains("two.txt");
+ }
+
+ @Test
+ public void givenAbsoluteURIs_whenRelativizeUriOneParentToUriThree_thenAbsoluteIsReturned() {
+ URI result = pathOne.getParent().toUri().relativize(uriThree);
+
+ org.assertj.core.api.Assertions.assertThat(result)
+ .asString()
+ .contains("/baeldung/foo/three.txt");
+ }
+
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/BufferedReaderUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/BufferedReaderUnitTest.java
new file mode 100644
index 0000000000..06b7d38821
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/BufferedReaderUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.bufferedreadervsfilereader;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+
+import org.junit.jupiter.api.Assertions;
+import org.testng.annotations.Test;
+public class BufferedReaderUnitTest {
+
+ @Test
+ public void whenReadingAFile_thenReadsLineByLine() {
+ StringBuilder result = new StringBuilder();
+
+ try (BufferedReader br = new BufferedReader(new FileReader("src/test/resources/sampleText1.txt"))) {
+ String line;
+
+ while((line = br.readLine()) != null) {
+ result.append(line);
+ result.append('\n');
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ assertEquals("first line\nsecond line\nthird line\n", result.toString());
+ }
+
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/FileReaderUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/FileReaderUnitTest.java
new file mode 100644
index 0000000000..5df870e7b5
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/bufferedreadervsfilereader/FileReaderUnitTest.java
@@ -0,0 +1,30 @@
+package com.baeldung.bufferedreadervsfilereader;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.FileReader;
+import java.io.IOException;
+
+import org.junit.jupiter.api.Test;
+
+public class FileReaderUnitTest {
+
+ @Test
+ public void whenReadingAFile_thenReadsCharByChar() {
+ StringBuilder result = new StringBuilder();
+
+ try (FileReader fr = new FileReader("src/test/resources/sampleText2.txt")) {
+ int i = fr.read();
+
+ while(i != -1) {
+ result.append((char)i);
+
+ i = fr.read();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ assertEquals("qwerty", result.toString());
+ }
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/multinput/TestMultipleInputsUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/multinput/TestMultipleInputsUnitTest.java
new file mode 100644
index 0000000000..317d9e817e
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/multinput/TestMultipleInputsUnitTest.java
@@ -0,0 +1,47 @@
+package com.baeldung.multinput;
+ import java.io.ByteArrayInputStream;
+ import java.io.InputStream;
+ import java.util.InputMismatchException;
+ import org.junit.jupiter.api.Assertions;
+ import org.testng.annotations.Test;
+import com.baeldung.multinput.MultiInputs;
+public class TestMultipleInputsUnitTest {
+ @Test
+ public void givenMultipleInputs_whenUsingSpaceDelimiter_thenExpectPrintingOutputs() {
+ String input = "10 20\n";
+ InputStream in = new ByteArrayInputStream(input.getBytes());
+ System.setIn(in);
+ MultiInputs mi = new MultiInputs();
+ mi.UsingSpaceDelimiter();
+ // You can add assertions here to verify the behavior of the method
+ }
+
+ @Test
+ public void givenMultipleInputs_whenUsingREDelimiter_thenExpectPrintingOutputs() {
+ String input = "30, 40\n";
+ InputStream in = new ByteArrayInputStream(input.getBytes());
+ System.setIn(in);
+ MultiInputs mi = new MultiInputs();
+ mi.UsingREDelimiter();
+ // You can add assertions here to verify the behavior of the method
+ }
+
+ @Test
+ public void givenMultipleInputs_whenUsingCustomDelimiter_thenExpectPrintingOutputs() {
+ String input = "50; 60\n";
+ InputStream in = new ByteArrayInputStream(input.getBytes());
+ System.setIn(in);
+ MultiInputs mi = new MultiInputs();
+ mi.UsingCustomDelimiter();
+ // You can add assertions here to verify the behavior of the method
+ }
+
+ @Test
+ public void givenInvalidInput_whenUsingSpaceDelimiter_thenExpectInputMismatchException() {
+ String input = "abc\n";
+ InputStream in = new ByteArrayInputStream(input.getBytes());
+ System.setIn(in);
+ MultiInputs mi = new MultiInputs();
+ Assertions.assertThrows(InputMismatchException.class, mi::UsingSpaceDelimiter);
+ }
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/path/DesktopPathUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/path/DesktopPathUnitTest.java
new file mode 100644
index 0000000000..1b71512c5c
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/path/DesktopPathUnitTest.java
@@ -0,0 +1,27 @@
+package com.baeldung.path;
+
+import java.io.File;
+
+import javax.swing.filechooser.FileSystemView;
+
+import org.junit.jupiter.api.Test;
+
+public class DesktopPathUnitTest {
+ // Adapt DESKTOP_PATH variable to your own system path
+ // private static final String DESKTOP_PATH = "C:\\Users\\HRAF\\Desktop";
+
+ @Test
+ public void whenUsingGetUserHomeProperty_thenShouldEqualDesktopPath() {
+ String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
+ // assertEquals(DESKTOP_PATH, desktopPath);
+ }
+
+ @Test
+ public void whenUsingFileSystemViewGetHomeDirectory_thenShouldEqualDesktopPath() {
+ FileSystemView view = FileSystemView.getFileSystemView();
+ File file = view.getHomeDirectory();
+ String path = file.getPath();
+ // assertEquals(DESKTOP_PATH, path);
+ }
+
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextLineVsNextIntUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextLineVsNextIntUnitTest.java
new file mode 100644
index 0000000000..3aae0469d0
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/NextLineVsNextIntUnitTest.java
@@ -0,0 +1,85 @@
+package com.baeldung.scanner;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.InputMismatchException;
+import java.util.Scanner;
+
+import org.junit.jupiter.api.Test;
+
+public class NextLineVsNextIntUnitTest {
+
+ @Test
+ void whenInputLineIsNumber_thenNextLineAndNextIntBothWork() {
+ String input = "42\n";
+
+ //nextLine()
+ Scanner sc1 = new Scanner(input);
+ int num1 = Integer.parseInt(sc1.nextLine());
+ assertEquals(42, num1);
+
+ //nextInt()
+ Scanner sc2 = new Scanner(input);
+ int num2 = sc2.nextInt();
+ assertEquals(42, num2);
+
+ }
+
+ @Test
+ void whenInputIsNotValidNumber_thenNextLineAndNextIntThrowDifferentException() {
+ String input = "Nan\n";
+
+ //nextLine() -> NumberFormatException
+ Scanner sc1 = new Scanner(input);
+ assertThrows(NumberFormatException.class, () -> Integer.parseInt(sc1.nextLine()));
+
+ //nextInt() -> InputMismatchException
+ Scanner sc2 = new Scanner(input);
+ assertThrows(InputMismatchException.class, sc2::nextInt);
+ }
+
+ @Test
+ void whenUsingNextInt_thenTheNextTokenAfterItFailsToParseIsNotConsumed() {
+ String input = "42 is a magic number\n";
+
+ //nextInt() to read '42'
+ Scanner sc2 = new Scanner(input);
+ int num2 = sc2.nextInt();
+ assertEquals(42, num2);
+
+ // call nextInt() again on "is"
+ assertThrows(InputMismatchException.class, sc2::nextInt);
+
+ String theNextToken = sc2.next();
+ assertEquals("is", theNextToken);
+
+ theNextToken = sc2.next();
+ assertEquals("a", theNextToken);
+ }
+
+ @Test
+ void whenReadingTwoInputLines_thenNextLineAndNextIntBehaveDifferently() {
+
+ String input = new StringBuilder().append("42\n")
+ .append("It is a magic number.\n")
+ .toString();
+
+ //nextLine()
+ Scanner sc1 = new Scanner(input);
+ int num1 = Integer.parseInt(sc1.nextLine());
+ String nextLineText1 = sc1.nextLine();
+ assertEquals(42, num1);
+ assertEquals("It is a magic number.", nextLineText1);
+
+ //nextInt()
+ Scanner sc2 = new Scanner(input);
+ int num2 = sc2.nextInt();
+ assertEquals(42, num2);
+
+ // nextInt() leaves the newline character (\n) behind
+ String nextLineText2 = sc2.nextLine();
+ assertEquals("", nextLineText2);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScanACharacterUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScanACharacterUnitTest.java
index 1a70c6e3af..340b58bbf6 100644
--- a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScanACharacterUnitTest.java
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScanACharacterUnitTest.java
@@ -1,38 +1,38 @@
-package com.baeldung.scanner;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-
-import java.util.Scanner;
-
-import org.junit.jupiter.api.Test;
-
-public class ScanACharacterUnitTest {
-
- // given - input scanner source, no need to scan from console
- String input = new StringBuilder().append("abc\n")
- .append("mno\n")
- .append("xyz\n")
- .toString();
-
- @Test
- public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
- Scanner sc = new Scanner(input);
- char c = sc.next().charAt(0);
- assertEquals('a', c);
- }
-
- @Test
- public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
- Scanner sc = new Scanner(input);
- char c = sc.findInLine(".").charAt(0);
- assertEquals('a', c);
- }
-
- @Test
- public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() {
- Scanner sc = new Scanner(input);
- char c = sc.useDelimiter("").next().charAt(0);
- assertEquals('a', c);
- }
-
-}
+package com.baeldung.scanner;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Scanner;
+
+import org.junit.jupiter.api.Test;
+
+public class ScanACharacterUnitTest {
+
+ // given - input scanner source, no need to scan from console
+ String input = new StringBuilder().append("abc\n")
+ .append("mno\n")
+ .append("xyz\n")
+ .toString();
+
+ @Test
+ public void givenInputSource_whenScanCharUsingNext_thenOneCharIsRead() {
+ Scanner sc = new Scanner(input);
+ char c = sc.next().charAt(0);
+ assertEquals('a', c);
+ }
+
+ @Test
+ public void givenInputSource_whenScanCharUsingFindInLine_thenOneCharIsRead() {
+ Scanner sc = new Scanner(input);
+ char c = sc.findInLine(".").charAt(0);
+ assertEquals('a', c);
+ }
+
+ @Test
+ public void givenInputSource_whenScanCharUsingUseDelimiter_thenOneCharIsRead() {
+ Scanner sc = new Scanner(input);
+ char c = sc.useDelimiter("").next().charAt(0);
+ assertEquals('a', c);
+ }
+
+}
diff --git a/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScannerToArrayUnitTest.java b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScannerToArrayUnitTest.java
new file mode 100644
index 0000000000..f64bd7b1fc
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/java/com/baeldung/scanner/ScannerToArrayUnitTest.java
@@ -0,0 +1,107 @@
+package com.baeldung.scanner;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Scanner;
+
+import org.junit.jupiter.api.Test;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.ObjectArrays;
+
+public class ScannerToArrayUnitTest {
+
+ @Test
+ void whenMultipleElementsInOneLine_thenGetExpectedArray() {
+ String input = "Java Kotlin Ruby Python Go\n";
+ String[] expected = new String[] { "Java", "Kotlin", "Ruby", "Python", "Go" };
+
+ // scanner.next()
+ Scanner scanner1 = new Scanner(input);
+ String[] result1 = new String[5];
+ int i = 0;
+ while (i < result1.length) {
+ result1[i] = scanner1.next();
+ i++;
+ }
+ assertArrayEquals(expected, result1);
+
+ //split()
+ Scanner scanner2 = new Scanner(input);
+ String[] result2 = scanner2.nextLine()
+ .split("\\s+");
+ assertArrayEquals(expected, result2);
+ }
+
+ @Test
+ void whenOneElementPerLine_thenGetExpectedArray() {
+ String input = new StringBuilder().append("Baeldung Java\n")
+ .append("Baeldung Kotlin\n")
+ .append("Baeldung Linux\n")
+ .toString();
+
+ String[] expected = new String[] { "Baeldung Java", "Baeldung Kotlin", "Baeldung Linux" };
+
+ String[] result = new String[3];
+ Scanner scanner = new Scanner(input);
+ int i = 0;
+ while (i < result.length) {
+ result[i] = scanner.nextLine();
+ i++;
+ }
+ assertArrayEquals(expected, result);
+ }
+
+ @Test
+ void whenOneElementPerLine_thenGetExpectedList() {
+ String input = new StringBuilder().append("Baeldung Java\n")
+ .append("Baeldung Kotlin\n")
+ .append("Baeldung Linux\n")
+ .toString();
+
+ List expected = Lists.newArrayList("Baeldung Java", "Baeldung Kotlin", "Baeldung Linux");
+
+ List result = new ArrayList<>();
+ Scanner scanner = new Scanner(input);
+ while (scanner.hasNextLine()) {
+ result.add(scanner.nextLine());
+ }
+ assertEquals(expected, result);
+ }
+
+ @Test
+ void whenEveryTokenIsAnElement_thenGetExpectedList() {
+ String input = new StringBuilder().append("Linux Windows MacOS\n")
+ .append("Java Kotlin Python Go\n")
+ .toString();
+
+ List expected = Lists.newArrayList("Linux", "Windows", "MacOS", "Java", "Kotlin", "Python", "Go");
+ List result = new ArrayList<>();
+ Scanner scanner = new Scanner(input);
+ while (scanner.hasNext()) {
+ result.add(scanner.next());
+ }
+ assertEquals(expected, result);
+ }
+
+ @Test
+ void whenEveryTokenIsAnElement_thenGetExpectedArray() {
+ String input = new StringBuilder().append("Linux Windows MacOS\n")
+ .append("Java Kotlin Python Go\n")
+ .toString();
+
+ String[] expected = new String[] { "Linux", "Windows", "MacOS", "Java", "Kotlin", "Python", "Go" };
+ String[] result = new String[] {};
+
+ Scanner scanner = new Scanner(input);
+ while (scanner.hasNextLine()) {
+ String[] lineInArray = scanner.nextLine()
+ .split("\\s+");
+ result = ObjectArrays.concat(result, lineInArray, String.class);
+ }
+ assertArrayEquals(expected, result);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-apis-2/src/test/resources/sampleText1.txt b/core-java-modules/core-java-io-apis-2/src/test/resources/sampleText1.txt
new file mode 100644
index 0000000000..ea0584cfe0
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/resources/sampleText1.txt
@@ -0,0 +1,3 @@
+first line
+second line
+third line
diff --git a/core-java-modules/core-java-io-apis-2/src/test/resources/sampleText2.txt b/core-java-modules/core-java-io-apis-2/src/test/resources/sampleText2.txt
new file mode 100644
index 0000000000..f2289097d4
--- /dev/null
+++ b/core-java-modules/core-java-io-apis-2/src/test/resources/sampleText2.txt
@@ -0,0 +1 @@
+qwerty
\ No newline at end of file
diff --git a/core-java-modules/core-java-io-apis/pom.xml b/core-java-modules/core-java-io-apis/pom.xml
index fab2bff959..f9d404cd5b 100644
--- a/core-java-modules/core-java-io-apis/pom.xml
+++ b/core-java-modules/core-java-io-apis/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io-apis
- 0.1.0-SNAPSHOT
core-java-io-apis
jar
diff --git a/core-java-modules/core-java-io-conversions-2/pom.xml b/core-java-modules/core-java-io-conversions-2/pom.xml
index 24708ad967..2c49bbfd81 100644
--- a/core-java-modules/core-java-io-conversions-2/pom.xml
+++ b/core-java-modules/core-java-io-conversions-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io-conversions-2
- 0.1.0-SNAPSHOT
core-java-io-conversions-2
jar
diff --git a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java
index 03f528766b..341a820b01 100644
--- a/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java
+++ b/core-java-modules/core-java-io-conversions-2/src/test/java/com/baeldung/inputstreamtostring/JavaInputStreamToXUnitTest.java
@@ -49,7 +49,7 @@ public class JavaInputStreamToXUnitTest {
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
final StringBuilder textBuilder = new StringBuilder();
- try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) {
+ try (Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
int c;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
@@ -63,7 +63,7 @@ public class JavaInputStreamToXUnitTest {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
- final String text = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))
+ final String text = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
diff --git a/core-java-modules/core-java-io-conversions/pom.xml b/core-java-modules/core-java-io-conversions/pom.xml
index 8d5a47a1ac..a44c352df2 100644
--- a/core-java-modules/core-java-io-conversions/pom.xml
+++ b/core-java-modules/core-java-io-conversions/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io-conversions
- 0.1.0-SNAPSHOT
core-java-io-conversions
jar
diff --git a/core-java-modules/core-java-io/pom.xml b/core-java-modules/core-java-io/pom.xml
index e645534b46..ce072e6875 100644
--- a/core-java-modules/core-java-io/pom.xml
+++ b/core-java-modules/core-java-io/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-io
- 0.1.0-SNAPSHOT
core-java-io
jar
diff --git a/core-java-modules/core-java-jar/pom.xml b/core-java-modules/core-java-jar/pom.xml
index 0ce2414f1e..e4a43bdf1f 100644
--- a/core-java-modules/core-java-jar/pom.xml
+++ b/core-java-modules/core-java-jar/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-jar
- 0.1.0-SNAPSHOT
core-java-jar
jar
diff --git a/core-java-modules/core-java-jndi/pom.xml b/core-java-modules/core-java-jndi/pom.xml
index 23a2fe3bfb..e48bec6622 100644
--- a/core-java-modules/core-java-jndi/pom.xml
+++ b/core-java-modules/core-java-jndi/pom.xml
@@ -3,9 +3,7 @@
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.jndi
core-java-jndi
- 1.0-SNAPSHOT
core-java-jndi
@@ -51,6 +49,18 @@
+
+ maven-surefire-plugin
+ 2.22.2
+
+ 3
+ false
+
+ SpringContextTest
+ **/*UnitTest
+
+
+
org.apache.maven.plugins
maven-compiler-plugin
diff --git a/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java b/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java
index 77f1e52f08..4d202f8f0c 100644
--- a/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java
+++ b/core-java-modules/core-java-jndi/src/test/java/com/baeldung/jndi/exceptions/JndiExceptionsUnitTest.java
@@ -21,7 +21,6 @@ public class JndiExceptionsUnitTest {
@Test
@Order(1)
- @Disabled
void givenNoContext_whenLookupObject_thenThrowNoInitialContext() {
assertThrows(NoInitialContextException.class, () -> {
JndiTemplate jndiTemplate = new JndiTemplate();
diff --git a/core-java-modules/core-java-jpms/pom.xml b/core-java-modules/core-java-jpms/pom.xml
index 62aa49f299..3cfa0e3f45 100644
--- a/core-java-modules/core-java-jpms/pom.xml
+++ b/core-java-modules/core-java-jpms/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-jpms
- 0.0.1-SNAPSHOT
core-java-jpms
pom
@@ -15,8 +14,8 @@
- decoupling-pattern1
- decoupling-pattern2
+ service-provider-factory-pattern
+ service-loader-api-pattern
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/pom.xml b/core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/pom.xml
similarity index 92%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/pom.xml
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/pom.xml
index 13d0b2d201..f928912ffd 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/pom.xml
+++ b/core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/pom.xml
@@ -8,8 +8,8 @@
1.0
- com.baeldung.decoupling-pattern2
- decoupling-pattern2
+ com.baeldung.service-loader-api-pattern
+ service-loader-api-pattern
1.0-SNAPSHOT
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/src/main/java/com/baeldung/consumermodule/Application.java b/core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/src/main/java/com/baeldung/consumermodule/Application.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/src/main/java/com/baeldung/consumermodule/Application.java
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/src/main/java/com/baeldung/consumermodule/Application.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/src/main/java/module-info.java b/core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/src/main/java/module-info.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/consumermodule2/src/main/java/module-info.java
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/consumermodule2/src/main/java/module-info.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml b/core-java-modules/core-java-jpms/service-loader-api-pattern/pom.xml
similarity index 92%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/pom.xml
index 5b2e4cfc82..13a443eab5 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern2/pom.xml
+++ b/core-java-modules/core-java-jpms/service-loader-api-pattern/pom.xml
@@ -3,8 +3,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.baeldung.decoupling-pattern2
- decoupling-pattern2
+ com.baeldung.service-loader-api-pattern
+ service-loader-api-pattern
1.0-SNAPSHOT
pom
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml b/core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/pom.xml
similarity index 91%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/pom.xml
index ddb8aeccd1..bcee01f631 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/pom.xml
+++ b/core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/pom.xml
@@ -8,8 +8,8 @@
1.0
- com.baeldung.decoupling-pattern2
- decoupling-pattern2
+ com.baeldung.service-loader-api-pattern
+ service-loader-api-pattern
1.0-SNAPSHOT
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/src/main/java/com/baeldung/providermodule/LowercaseTextService.java b/core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/src/main/java/com/baeldung/providermodule/LowercaseTextService.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/src/main/java/com/baeldung/providermodule/LowercaseTextService.java
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/src/main/java/com/baeldung/providermodule/LowercaseTextService.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/src/main/java/module-info.java b/core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/src/main/java/module-info.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/providermodule/src/main/java/module-info.java
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/providermodule/src/main/java/module-info.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/pom.xml b/core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/pom.xml
similarity index 88%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/pom.xml
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/pom.xml
index 06ef900092..f40745541b 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/pom.xml
+++ b/core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/pom.xml
@@ -8,8 +8,8 @@
1.0
- com.baeldung.decoupling-pattern2
- decoupling-pattern2
+ com.baeldung.service-loader-api-pattern
+ service-loader-api-pattern
1.0-SNAPSHOT
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/src/main/java/com/baeldung/servicemodule/TextService.java b/core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/src/main/java/com/baeldung/servicemodule/TextService.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/src/main/java/com/baeldung/servicemodule/TextService.java
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/src/main/java/com/baeldung/servicemodule/TextService.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/src/main/java/module-info.java b/core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/src/main/java/module-info.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern2/servicemodule2/src/main/java/module-info.java
rename to core-java-modules/core-java-jpms/service-loader-api-pattern/servicemodule2/src/main/java/module-info.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/pom.xml b/core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/pom.xml
similarity index 89%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/pom.xml
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/pom.xml
index f82e72b85d..ba92733f34 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/pom.xml
+++ b/core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/pom.xml
@@ -8,8 +8,8 @@
jar
- com.baeldung.decoupling-pattern1
- decoupling-pattern1
+ com.baeldung.service-provider-factory-pattern
+ service-provider-factory-pattern
1.0-SNAPSHOT
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/src/main/java/com/baeldung/consumermodule/Application.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/src/main/java/com/baeldung/consumermodule/Application.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/src/main/java/com/baeldung/consumermodule/Application.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/src/main/java/com/baeldung/consumermodule/Application.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/src/main/java/module-info.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/src/main/java/module-info.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/consumermodule1/src/main/java/module-info.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/consumermodule1/src/main/java/module-info.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml b/core-java-modules/core-java-jpms/service-provider-factory-pattern/pom.xml
similarity index 91%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/pom.xml
index 2121b46b82..35a9912312 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern1/pom.xml
+++ b/core-java-modules/core-java-jpms/service-provider-factory-pattern/pom.xml
@@ -3,8 +3,8 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.baeldung.decoupling-pattern1
- decoupling-pattern1
+ com.baeldung.service-provider-factory-pattern
+ service-provider-factory-pattern
1.0-SNAPSHOT
pom
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/pom.xml b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/pom.xml
similarity index 86%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/pom.xml
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/pom.xml
index fc4b5854f9..d6e50ee9ff 100644
--- a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/pom.xml
+++ b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/pom.xml
@@ -9,8 +9,8 @@
jar
- com.baeldung.decoupling-pattern1
- decoupling-pattern1
+ com.baeldung.service-provider-factory-pattern
+ service-provider-factory-pattern
1.0-SNAPSHOT
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextService.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextService.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextService.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextService.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextServiceFactory.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextServiceFactory.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextServiceFactory.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/external/TextServiceFactory.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/LowercaseTextService.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/LowercaseTextService.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/LowercaseTextService.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/LowercaseTextService.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/UppercaseTextService.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/UppercaseTextService.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/UppercaseTextService.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/com/baeldung/servicemodule/internal/UppercaseTextService.java
diff --git a/core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/module-info.java b/core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/module-info.java
similarity index 100%
rename from core-java-modules/core-java-jpms/decoupling-pattern1/servicemodule1/src/main/java/module-info.java
rename to core-java-modules/core-java-jpms/service-provider-factory-pattern/servicemodule1/src/main/java/module-info.java
diff --git a/core-java-modules/core-java-jvm-2/pom.xml b/core-java-modules/core-java-jvm-2/pom.xml
index 01628b0908..2ccc847a6f 100644
--- a/core-java-modules/core-java-jvm-2/pom.xml
+++ b/core-java-modules/core-java-jvm-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-jvm-2
- 0.1.0-SNAPSHOT
core-java-jvm-2
jar
@@ -27,9 +26,28 @@
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ ${maven.compiler.target}
+
+ --add-exports=java.base/jdk.internal.vm.annotation=ALL-UNNAMED
+
+
+
+
+
+
0.10
0.10.2
+ 11
+ 11
\ No newline at end of file
diff --git a/core-java-modules/core-java-jvm-2/src/test/java/com/baeldung/memlayout/MemoryLayoutUnitTest.java b/core-java-modules/core-java-jvm-2/src/test/java/com/baeldung/memlayout/MemoryLayoutUnitTest.java
index 2f226d7657..760115877e 100644
--- a/core-java-modules/core-java-jvm-2/src/test/java/com/baeldung/memlayout/MemoryLayoutUnitTest.java
+++ b/core-java-modules/core-java-jvm-2/src/test/java/com/baeldung/memlayout/MemoryLayoutUnitTest.java
@@ -3,7 +3,8 @@ package com.baeldung.memlayout;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;
-import sun.misc.Contended;
+
+import jdk.internal.vm.annotation.Contended;
public class MemoryLayoutUnitTest {
diff --git a/core-java-modules/core-java-jvm-3/README.md b/core-java-modules/core-java-jvm-3/README.md
index 0c8a325cf2..3ff393a5ad 100644
--- a/core-java-modules/core-java-jvm-3/README.md
+++ b/core-java-modules/core-java-jvm-3/README.md
@@ -6,4 +6,5 @@ This module contains articles about working with the Java Virtual Machine (JVM).
- [Difference Between Class.getResource() and ClassLoader.getResource()](https://www.baeldung.com/java-class-vs-classloader-getresource)
- [Compiling and Executing Code From a String in Java](https://www.baeldung.com/java-string-compile-execute-code)
+- [Difference Between Class.forName() and Class.forName().newInstance()](https://www.baeldung.com/java-class-forname-vs-class-forname-newinstance)
- More articles: [[<-- prev]](/core-java-modules/core-java-jvm-2)
diff --git a/core-java-modules/core-java-jvm-3/pom.xml b/core-java-modules/core-java-jvm-3/pom.xml
index cb2d8b0b85..78f4201c94 100644
--- a/core-java-modules/core-java-jvm-3/pom.xml
+++ b/core-java-modules/core-java-jvm-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-jvm-3
- 0.1.0-SNAPSHOT
core-java-jvm-3
jar
@@ -14,7 +13,4 @@
0.0.1-SNAPSHOT
-
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/loadclass/MyClassForLoad.java b/core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/loadclass/MyClassForLoad.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/loadclass/MyClassForLoad.java
rename to core-java-modules/core-java-jvm-3/src/main/java/com/baeldung/loadclass/MyClassForLoad.java
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/loadclass/LoadClassUnitTest.java b/core-java-modules/core-java-jvm-3/src/test/java/com/baeldung/loadclass/LoadClassUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/loadclass/LoadClassUnitTest.java
rename to core-java-modules/core-java-jvm-3/src/test/java/com/baeldung/loadclass/LoadClassUnitTest.java
diff --git a/core-java-modules/core-java-jvm/pom.xml b/core-java-modules/core-java-jvm/pom.xml
index d26c72323f..52bdf8bc5d 100644
--- a/core-java-modules/core-java-jvm/pom.xml
+++ b/core-java-modules/core-java-jvm/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-jvm
- 0.1.0-SNAPSHOT
core-java-jvm
jar
@@ -30,13 +29,6 @@
esapi
${esapi.version}
-
- com.sun
- tools
- ${sun.tools.version}
- system
- ${java.home}/../lib/tools.jar
-
org.ow2.asm
asm
@@ -176,9 +168,8 @@
3.27.0-GA
- 1.8.0
0.10
- 8.0.1
+ 9.4
6.5.0
diff --git a/core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/PrintClassLoader.java b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/PrintClassLoader.java
index 09ee68bf6e..cd7000b419 100644
--- a/core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/PrintClassLoader.java
+++ b/core-java-modules/core-java-jvm/src/main/java/com/baeldung/classloader/PrintClassLoader.java
@@ -1,13 +1,7 @@
package com.baeldung.classloader;
-import com.sun.javafx.util.Logging;
+import java.sql.DriverManager;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLConnection;
import java.util.ArrayList;
public class PrintClassLoader {
@@ -15,7 +9,7 @@ public class PrintClassLoader {
public void printClassLoaders() throws ClassNotFoundException {
System.out.println("Classloader of this class:" + PrintClassLoader.class.getClassLoader());
- System.out.println("Classloader of Logging:" + Logging.class.getClassLoader());
+ System.out.println("Classloader of DriverManager:" + DriverManager.class.getClassLoader());
System.out.println("Classloader of ArrayList:" + ArrayList.class.getClassLoader());
}
diff --git a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/bytecode/ViewBytecodeUnitTest.java b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/bytecode/ViewBytecodeUnitTest.java
index 5b0fdf26d4..2a7366c322 100644
--- a/core-java-modules/core-java-jvm/src/test/java/com/baeldung/bytecode/ViewBytecodeUnitTest.java
+++ b/core-java-modules/core-java-jvm/src/test/java/com/baeldung/bytecode/ViewBytecodeUnitTest.java
@@ -33,7 +33,7 @@ public class ViewBytecodeUnitTest {
JavaClass objectClazz = Repository.lookupClass("java.lang.Object");
assertEquals(objectClazz.getClassName(), "java.lang.Object");
- assertEquals(objectClazz.getMethods().length, 14);
+ assertEquals(objectClazz.getMethods().length, 12);
assertTrue(objectClazz.toString().contains("public class java.lang.Object"));
}
@@ -43,7 +43,7 @@ public class ViewBytecodeUnitTest {
ClassFile cf = cp.get("java.lang.Object").getClassFile();
assertEquals(cf.getName(), "java.lang.Object");
- assertEquals(cf.getMethods().size(), 14);
+ assertEquals(cf.getMethods().size(), 12);
}
}
diff --git a/core-java-modules/core-java-lambdas/pom.xml b/core-java-modules/core-java-lambdas/pom.xml
index f1e61ab8bf..a7fc5355d7 100644
--- a/core-java-modules/core-java-lambdas/pom.xml
+++ b/core-java-modules/core-java-lambdas/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lambdas
- 0.1.0-SNAPSHOT
core-java-lambdas
jar
diff --git a/core-java-modules/core-java-lang-2/pom.xml b/core-java-modules/core-java-lang-2/pom.xml
index 4a89a22577..22055cf252 100644
--- a/core-java-modules/core-java-lang-2/pom.xml
+++ b/core-java-modules/core-java-lang-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-2
- 0.1.0-SNAPSHOT
core-java-lang-2
jar
diff --git a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/headlessmode/HeadlessModeUnitTest.java b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/headlessmode/HeadlessModeUnitTest.java
index a17c1600f3..d64d8c16da 100644
--- a/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/headlessmode/HeadlessModeUnitTest.java
+++ b/core-java-modules/core-java-lang-2/src/test/java/com/baeldung/headlessmode/HeadlessModeUnitTest.java
@@ -3,13 +3,12 @@ package com.baeldung.headlessmode;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import java.awt.Canvas;
-import java.awt.Font;
-import java.awt.FontMetrics;
-import java.awt.Frame;
-import java.awt.GraphicsEnvironment;
-import java.awt.HeadlessException;
+import java.awt.*;
import java.awt.image.BufferedImage;
+import java.awt.image.ColorModel;
+import java.awt.image.ComponentColorModel;
+import java.awt.image.DataBuffer;
+import java.awt.image.WritableRaster;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -58,7 +57,7 @@ public class HeadlessModeUnitTest {
boolean result = false;
try (InputStream inStream = HeadlessModeUnitTest.class.getResourceAsStream(IN_FILE); FileOutputStream outStream = new FileOutputStream(OUT_FILE)) {
BufferedImage inputImage = ImageIO.read(inStream);
- result = ImageIO.write(inputImage, FORMAT, outStream);
+ result = ImageIO.write(removeAlphaChannel(inputImage), FORMAT, outStream);
}
assertThat(result).isTrue();
@@ -84,4 +83,10 @@ public class HeadlessModeUnitTest {
assertThat(FlexibleApp.iAmFlexible()).isEqualTo(FlexibleApp.HEADED);
}
+ private BufferedImage removeAlphaChannel(BufferedImage inputImage) {
+ final WritableRaster raster = inputImage.getRaster();
+ final WritableRaster newRaster = raster.createWritableChild(0, 0, inputImage.getWidth(), inputImage.getHeight(), 0, 0, new int[]{0, 1, 2});
+ ColorModel newCM = new ComponentColorModel(inputImage.getColorModel().getColorSpace(), false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
+ return new BufferedImage(newCM, newRaster, false, null);
+ }
}
diff --git a/core-java-modules/core-java-lang-3/pom.xml b/core-java-modules/core-java-lang-3/pom.xml
index 331d91dff6..f29fa6494a 100644
--- a/core-java-modules/core-java-lang-3/pom.xml
+++ b/core-java-modules/core-java-lang-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-3
- 0.1.0-SNAPSHOT
core-java-lang-3
jar
diff --git a/core-java-modules/core-java-lang-4/pom.xml b/core-java-modules/core-java-lang-4/pom.xml
index de67ddf55a..6977621a0e 100644
--- a/core-java-modules/core-java-lang-4/pom.xml
+++ b/core-java-modules/core-java-lang-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-4
- 0.1.0-SNAPSHOT
core-java-lang-4
jar
diff --git a/core-java-modules/core-java-lang-5/README.md b/core-java-modules/core-java-lang-5/README.md
index 5ff3e83d2c..b8deff199e 100644
--- a/core-java-modules/core-java-lang-5/README.md
+++ b/core-java-modules/core-java-lang-5/README.md
@@ -14,4 +14,3 @@ This module contains articles about core features in the Java language
- [Convert Between int and char in Java](https://www.baeldung.com/java-convert-int-char)
- [Converting a Number from One Base to Another in Java](https://www.baeldung.com/java-converting-a-number-from-one-base-to-another)
- [Check if Command-Line Arguments Are Null in Java](https://www.baeldung.com/java-check-command-line-args)
-- [Determine if a Class Implements an Interface in Java](https://www.baeldung.com/java-check-class-implements-interface)
diff --git a/core-java-modules/core-java-lang-5/pom.xml b/core-java-modules/core-java-lang-5/pom.xml
index 767ebb6e35..8e95fc4405 100644
--- a/core-java-modules/core-java-lang-5/pom.xml
+++ b/core-java-modules/core-java-lang-5/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-5
- 0.1.0-SNAPSHOT
core-java-lang-5
jar
@@ -13,12 +12,6 @@
core-java-modules
0.0.1-SNAPSHOT
-
-
- 3.12.0
- 0.10.2
-
-
core-java-lang-5
@@ -30,18 +23,9 @@
-
-
- org.apache.commons
- commons-lang3
- ${commons-lang3.version}
-
-
-
- org.reflections
- reflections
- ${reflections.version}
-
-
-
+
+ 3.12.0
+ 0.10.2
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/rawtypes/RawTypesUnitTest.java b/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/rawtypes/RawTypesUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/rawtypes/RawTypesUnitTest.java
rename to core-java-modules/core-java-lang-5/src/test/java/com/baeldung/rawtypes/RawTypesUnitTest.java
diff --git a/core-java-modules/core-java-lang-math-2/pom.xml b/core-java-modules/core-java-lang-math-2/pom.xml
index e6ead53350..223c791d35 100644
--- a/core-java-modules/core-java-lang-math-2/pom.xml
+++ b/core-java-modules/core-java-lang-math-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-math-2
- 0.0.1-SNAPSHOT
core-java-lang-math-2
diff --git a/core-java-modules/core-java-lang-math-3/README.md b/core-java-modules/core-java-lang-math-3/README.md
index 89adc23100..847bd314a7 100644
--- a/core-java-modules/core-java-lang-math-3/README.md
+++ b/core-java-modules/core-java-lang-math-3/README.md
@@ -10,4 +10,5 @@
- [Create a BMI Calculator in Java](https://www.baeldung.com/java-body-mass-index-calculator)
- [Java Program to Calculate the Standard Deviation](https://www.baeldung.com/java-calculate-standard-deviation)
- [Java Program to Print Pascal’s Triangle](https://www.baeldung.com/java-pascal-triangle)
+- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-math-2)
diff --git a/core-java-modules/core-java-lang-math-3/pom.xml b/core-java-modules/core-java-lang-math-3/pom.xml
index 38cb6dfa17..7860f57735 100644
--- a/core-java-modules/core-java-lang-math-3/pom.xml
+++ b/core-java-modules/core-java-lang-math-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-math-3
- 0.0.1-SNAPSHOT
core-java-lang-math-3
@@ -24,11 +23,17 @@
javaluator
${javaluator.version}
+
+ org.javamoney
+ moneta
+ ${javamoney.moneta.version}
+
0.4.8
3.0.3
+ 1.1
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/money/JavaMoney.java b/core-java-modules/core-java-lang-math-3/src/main/java/com/baeldung/money/JavaMoney.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/money/JavaMoney.java
rename to core-java-modules/core-java-lang-math-3/src/main/java/com/baeldung/money/JavaMoney.java
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java b/core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
rename to core-java-modules/core-java-lang-math-3/src/test/java/com/baeldung/money/JavaMoneyUnitManualTest.java
diff --git a/core-java-modules/core-java-lang-math/pom.xml b/core-java-modules/core-java-lang-math/pom.xml
index 37550b67d8..551e5db1d5 100644
--- a/core-java-modules/core-java-lang-math/pom.xml
+++ b/core-java-modules/core-java-lang-math/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-math
- 0.1.0-SNAPSHOT
core-java-lang-math
jar
diff --git a/core-java-modules/core-java-lang-oop-constructors-2/README.md b/core-java-modules/core-java-lang-oop-constructors-2/README.md
new file mode 100644
index 0000000000..d9b162c7a6
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors-2/README.md
@@ -0,0 +1,7 @@
+## Core Java Lang OOP - Constructors - Part 2
+
+This module contains article about constructors in Java
+
+### Relevant Articles:
+- [Different Ways to Create an Object in Java](https://www.baeldung.com/java-different-ways-to-create-objects)
+- More articles: [[<-- Prev]](/core-java-modules/core-java-lang-oop-constructors)
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-constructors-2/pom.xml b/core-java-modules/core-java-lang-oop-constructors-2/pom.xml
new file mode 100644
index 0000000000..c6d9d84774
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors-2/pom.xml
@@ -0,0 +1,16 @@
+
+
+ 4.0.0
+ core-java-lang-oop-constructors-2
+ core-java-lang-oop-constructors-2
+ jar
+
+
+ core-java-modules
+ com.baeldung.core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/ClonableRabbit.java b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/ClonableRabbit.java
new file mode 100644
index 0000000000..0d97e010fb
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/ClonableRabbit.java
@@ -0,0 +1,18 @@
+package com.baeldung.objectcreation.objects;
+
+public class ClonableRabbit implements Cloneable {
+
+ String name = "";
+
+ public ClonableRabbit(String name) {
+ this.name = name;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public Object clone() throws CloneNotSupportedException {
+ return super.clone();
+ }
+}
diff --git a/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/Rabbit.java b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/Rabbit.java
new file mode 100644
index 0000000000..c8a8159544
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/Rabbit.java
@@ -0,0 +1,17 @@
+package com.baeldung.objectcreation.objects;
+
+public class Rabbit {
+
+ String name = "";
+
+ public Rabbit() {
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/RabbitType.java b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/RabbitType.java
new file mode 100644
index 0000000000..b7afe5fe2f
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/RabbitType.java
@@ -0,0 +1,7 @@
+package com.baeldung.objectcreation.objects;
+
+public enum RabbitType {
+ PET,
+ TAME,
+ WILD
+}
diff --git a/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/SerializableRabbit.java b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/SerializableRabbit.java
new file mode 100644
index 0000000000..cb5f2d0b71
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/objects/SerializableRabbit.java
@@ -0,0 +1,21 @@
+package com.baeldung.objectcreation.objects;
+
+import java.io.Serializable;
+
+public class SerializableRabbit implements Serializable {
+
+ private static final long serialVersionUID = 2589844379773087465L;
+
+ String name = "";
+
+ public SerializableRabbit() {
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/utils/CreateRabbits.java b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/utils/CreateRabbits.java
new file mode 100644
index 0000000000..8b3c84e89c
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors-2/src/main/java/com/baeldung/objectcreation/utils/CreateRabbits.java
@@ -0,0 +1,71 @@
+package com.baeldung.objectcreation.utils;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.util.function.Supplier;
+
+import com.baeldung.objectcreation.objects.ClonableRabbit;
+import com.baeldung.objectcreation.objects.Rabbit;
+import com.baeldung.objectcreation.objects.RabbitType;
+import com.baeldung.objectcreation.objects.SerializableRabbit;
+
+public final class CreateRabbits {
+
+ public static Rabbit createRabbitUsingNewOperator() {
+ Rabbit rabbit = new Rabbit();
+
+ return rabbit;
+ }
+
+ public static Rabbit createRabbitUsingClassForName() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
+ Rabbit rabbit = (Rabbit) Class.forName("com.baeldung.objectcreation.objects.Rabbit").newInstance();
+
+ return rabbit;
+ }
+
+ public static Rabbit createRabbitUsingClassNewInstance() throws InstantiationException, IllegalAccessException {
+ Rabbit rabbit = Rabbit.class.newInstance();
+
+ return rabbit;
+ }
+
+ public static Rabbit createRabbitUsingConstructorNewInstance() throws InstantiationException, IllegalAccessException, IllegalArgumentException,
+ InvocationTargetException, NoSuchMethodException, SecurityException {
+ Rabbit rabbit = Rabbit.class.getConstructor().newInstance();
+
+ return rabbit;
+ }
+
+ public static ClonableRabbit createRabbitUsingClone(ClonableRabbit originalRabbit) throws CloneNotSupportedException {
+ ClonableRabbit clonedRabbit = (ClonableRabbit) originalRabbit.clone();
+
+ return clonedRabbit;
+ }
+
+ public static SerializableRabbit createRabbitUsingDeserialization(File file) throws IOException, ClassNotFoundException {
+ try (FileInputStream fis = new FileInputStream(file);
+ ObjectInputStream ois = new ObjectInputStream(fis);) {
+ return (SerializableRabbit) ois.readObject();
+ }
+ }
+
+ public static Rabbit createRabbitUsingSupplier() {
+ Supplier rabbitSupplier = Rabbit::new;
+ Rabbit rabbit = rabbitSupplier.get();
+
+ return rabbit;
+ }
+
+ public static Rabbit[] createRabbitArray() {
+ Rabbit[] rabbitArray = new Rabbit[10];
+
+ return rabbitArray;
+ }
+
+ public static RabbitType createRabbitTypeEnum() {
+ return RabbitType.PET; //any RabbitType could be returned here, PET is just an example.
+ }
+}
diff --git a/core-java-modules/core-java-lang-oop-constructors-2/src/test/java/com/baeldung/objectcreation/CreateRabbitsUnitTest.java b/core-java-modules/core-java-lang-oop-constructors-2/src/test/java/com/baeldung/objectcreation/CreateRabbitsUnitTest.java
new file mode 100644
index 0000000000..653beba096
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-constructors-2/src/test/java/com/baeldung/objectcreation/CreateRabbitsUnitTest.java
@@ -0,0 +1,100 @@
+package com.baeldung.objectcreation;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectOutputStream;
+import java.lang.reflect.InvocationTargetException;
+
+import org.junit.Test;
+
+import com.baeldung.objectcreation.objects.ClonableRabbit;
+import com.baeldung.objectcreation.objects.Rabbit;
+import com.baeldung.objectcreation.objects.RabbitType;
+import com.baeldung.objectcreation.objects.SerializableRabbit;
+import com.baeldung.objectcreation.utils.CreateRabbits;
+
+public class CreateRabbitsUnitTest {
+
+ @Test
+ public void whenUsingNewOperator_thenRabbitIsReturned() {
+ assertTrue(CreateRabbits.createRabbitUsingNewOperator() instanceof Rabbit);
+ }
+
+ @Test
+ public void whenUsingClassForName_thenRabbitIsReturned() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
+ assertTrue(CreateRabbits.createRabbitUsingClassForName() instanceof Rabbit);
+ }
+
+ @Test
+ public void whenUsingClassNewInstance_thenRabbitIsReturned() throws InstantiationException, IllegalAccessException {
+ assertTrue(CreateRabbits.createRabbitUsingClassNewInstance() instanceof Rabbit);
+ }
+
+ @Test
+ public void whenUsingConstructorNewInstance_thenRabbitIsReturned() throws InstantiationException, IllegalAccessException, IllegalArgumentException,
+ InvocationTargetException, NoSuchMethodException, SecurityException {
+ assertTrue(CreateRabbits.createRabbitUsingConstructorNewInstance() instanceof Rabbit);
+ }
+
+ @Test
+ public void givenClonableRabbit_whenUsingCloneMethod_thenClonedRabbitIsReturned() throws CloneNotSupportedException {
+ //given
+ ClonableRabbit originalRabbit = new ClonableRabbit("Peter");
+
+ //when
+ ClonableRabbit clonedRabbit = CreateRabbits.createRabbitUsingClone(originalRabbit);
+
+ //then
+ assertTrue(clonedRabbit instanceof ClonableRabbit);
+ assertNotEquals(originalRabbit, clonedRabbit);
+ assertEquals("Peter", clonedRabbit.getName());
+ }
+
+ @Test
+ public void givenSerializedRabbit_whenDeserializing_thenNewRabbitIsReturned() throws IOException, ClassNotFoundException {
+ //given
+ SerializableRabbit originalRabbit = new SerializableRabbit();
+ originalRabbit.setName("Peter");
+
+ File resourcesFolder = new File("src/test/resources");
+ resourcesFolder.mkdirs(); //creates the directory in case it doesn't exist
+
+ File file = new File(resourcesFolder, "rabbit.ser");
+
+ try (FileOutputStream fileOutputStream = new FileOutputStream(file);
+ ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);) {
+ objectOutputStream.writeObject(originalRabbit);
+ }
+
+ //when
+ SerializableRabbit newRabbit = CreateRabbits.createRabbitUsingDeserialization(file);
+
+ //then
+ assertTrue(newRabbit instanceof SerializableRabbit);
+ assertNotEquals(originalRabbit, newRabbit);
+ assertEquals("Peter", newRabbit.getName());
+
+ //clean up
+ file.delete();
+ }
+
+ @Test
+ public void whenUsingSupplier_thenRabbitIsReturned() {
+ assertTrue(CreateRabbits.createRabbitUsingSupplier() instanceof Rabbit);
+ }
+
+ @Test
+ public void whenUsingArrays_thenRabbitArrayIsReturned() {
+ assertTrue(CreateRabbits.createRabbitArray() instanceof Rabbit[]);
+ }
+
+ @Test
+ public void whenUsingEnums_thenRabbitTypeIsReturned() {
+ assertTrue(CreateRabbits.createRabbitTypeEnum() instanceof RabbitType);
+ }
+}
diff --git a/core-java-modules/core-java-lang-oop-constructors/README.md b/core-java-modules/core-java-lang-oop-constructors/README.md
index a552a79721..c35cb836a5 100644
--- a/core-java-modules/core-java-lang-oop-constructors/README.md
+++ b/core-java-modules/core-java-lang-oop-constructors/README.md
@@ -12,3 +12,5 @@ This module contains article about constructors in Java
- [Java Implicit Super Constructor is Undefined Error](https://www.baeldung.com/java-implicit-super-constructor-is-undefined-error)
- [Constructor Specification in Java](https://www.baeldung.com/java-constructor-specification)
- [Static vs. Instance Initializer Block in Java](https://www.baeldung.com/java-static-instance-initializer-blocks)
+- [Accessing Private Constructor in Java](https://www.baeldung.com/java-private-constructor-access)
+- More articles: [[next -->]](/core-java-modules/core-java-lang-oop-constructors-2)
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-methods/README.md b/core-java-modules/core-java-lang-oop-methods/README.md
index f34606f26a..053cafac3e 100644
--- a/core-java-modules/core-java-lang-oop-methods/README.md
+++ b/core-java-modules/core-java-lang-oop-methods/README.md
@@ -11,3 +11,4 @@ This module contains articles about methods in Java
- [The Covariant Return Type in Java](https://www.baeldung.com/java-covariant-return-type)
- [Does a Method’s Signature Include the Return Type in Java?](https://www.baeldung.com/java-method-signature-return-type)
- [Solving the Hide Utility Class Public Constructor Sonar Warning](https://www.baeldung.com/java-sonar-hide-implicit-constructor)
+- [Best Practices for Passing Many Arguments to a Method in Java](https://www.baeldung.com/java-best-practices-many-parameters-method)
diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Car.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Car.java
new file mode 100644
index 0000000000..a72d7dd0f1
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Car.java
@@ -0,0 +1,98 @@
+package com.baeldung.methods;
+
+public class Car {
+
+ private final String make;
+ private final String model;
+ private final int year;
+ private final String color;
+ private final boolean automatic;
+ private final int numDoors;
+ private final String features;
+
+ private Car(CarBuilder carBuilder) {
+ this.make = carBuilder.make;
+ this.model = carBuilder.model;
+ this.year = carBuilder.year;
+ this.color = carBuilder.color;
+ this.automatic = carBuilder.automatic;
+ this.numDoors = carBuilder.numDoors;
+ this.features = carBuilder.features;
+ }
+
+ public String getMake() {
+ return make;
+ }
+
+ public String getModel() {
+ return model;
+ }
+
+ public int getYear() {
+ return year;
+ }
+
+ public String getColor() {
+ return color;
+ }
+
+ public boolean isAutomatic() {
+ return automatic;
+ }
+
+ public int getNumDoors() {
+ return numDoors;
+ }
+
+ public String getFeatures() {
+ return features;
+ }
+
+ public static class CarBuilder {
+
+ private final String make;
+ private final String model;
+ private final int year;
+
+ private String color = "unknown";
+ private boolean automatic = false;
+ private int numDoors = 4;
+ private String features = "";
+
+ public CarBuilder(String make, String model, int year) {
+ this.make = make;
+ this.model = model;
+ this.year = year;
+ }
+
+ public CarBuilder color(String color) {
+ this.color = color;
+ return this;
+ }
+
+ public CarBuilder automatic(boolean automatic) {
+ this.automatic = automatic;
+ return this;
+ }
+
+ public CarBuilder numDoors(int numDoors) {
+ this.numDoors = numDoors;
+ return this;
+ }
+
+ public CarBuilder features(String features) {
+ this.features = features;
+ return this;
+ }
+
+ public Car build() {
+ return new Car(this);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "Car [make=" + make + ", model=" + model + ", year=" + year + ", color=" + color + ", automatic=" + automatic + ", numDoors=" + numDoors + ", features=" + features + "]";
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Motorcycle.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Motorcycle.java
new file mode 100644
index 0000000000..8a1fce4a5d
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Motorcycle.java
@@ -0,0 +1,52 @@
+package com.baeldung.methods;
+
+import java.io.Serializable;
+
+public class Motorcycle extends Vehicle implements Serializable {
+
+ private static final long serialVersionUID = 5973661295933599929L;
+
+ private int year;
+ private String features = "";
+
+ public Motorcycle() {
+ super();
+ }
+
+ public Motorcycle(String make, String model, String color, int weight, boolean statusNew, int year) {
+ super(make, model, color, weight, statusNew);
+ this.year = year;
+ }
+
+ public Motorcycle(Vehicle vehicle, int year) {
+ super(vehicle);
+ this.year = year;
+ }
+
+ public int getYear() {
+ return year;
+ }
+
+ public void setYear(int year) {
+ this.year = year;
+ }
+
+ public void setFeatures(String features) {
+ this.features = features;
+ }
+
+ public String getFeatures() {
+ return features;
+ }
+
+ public void addMotorcycleFeatures(String... features) {
+ StringBuilder str = new StringBuilder(this.getFeatures());
+ for (String feature : features) {
+ if (!str.toString().isEmpty())
+ str.append(", ");
+ str.append(feature);
+ }
+ this.setFeatures(str.toString());
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Vehicle.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Vehicle.java
new file mode 100644
index 0000000000..0c6964d255
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/Vehicle.java
@@ -0,0 +1,33 @@
+package com.baeldung.methods;
+
+public class Vehicle {
+
+ static String defaultValue = "DEFAULT";
+ private String make = defaultValue;
+ private String model = defaultValue;
+ private String color = defaultValue;
+ private int weight = 0;
+ private boolean statusNew = true;
+
+ public Vehicle() {
+ super();
+ }
+
+ public Vehicle(String make, String model, String color, int weight, boolean statusNew) {
+ this.make = make;
+ this.model = model;
+ this.color = color;
+ this.weight = weight;
+ this.statusNew = statusNew;
+ }
+
+ public Vehicle(Vehicle vehicle) {
+ this(vehicle.make, vehicle.model, vehicle.color, vehicle.weight, vehicle.statusNew);
+ }
+
+ @Override
+ public String toString() {
+ return "Vehicle [make=" + make + ", model=" + model + ", color=" + color + ", weight=" + weight + ", statusNew=" + statusNew + "]";
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/VehicleProcessor.java b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/VehicleProcessor.java
new file mode 100644
index 0000000000..a7d5975813
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-methods/src/main/java/com/baeldung/methods/VehicleProcessor.java
@@ -0,0 +1,20 @@
+package com.baeldung.methods;
+
+public class VehicleProcessor {
+
+ Vehicle processVehicle(String make, String model, String color, int weight, boolean status) {
+ return new Vehicle(make, model, color, weight, status);
+ }
+
+ Vehicle processVehicle(Vehicle vehicle) {
+ return new Vehicle(vehicle);
+ }
+
+ Car processCar(Car car) {
+ return new Car.CarBuilder(car.getMake(), car.getModel(), car.getYear()).color(car.getColor())
+ .automatic(car.isAutomatic())
+ .features(car.getFeatures())
+ .build();
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/methods/VehicleProcessorUnitTest.java b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/methods/VehicleProcessorUnitTest.java
new file mode 100644
index 0000000000..928fbcb426
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-methods/src/test/java/com/baeldung/methods/VehicleProcessorUnitTest.java
@@ -0,0 +1,58 @@
+package com.baeldung.methods;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+class VehicleProcessorUnitTest {
+
+ VehicleProcessor vehicleProcessor = new VehicleProcessor();
+ Vehicle vehicle = new Vehicle("Ford", "Focus", "red", 2200, true);
+
+ @Test
+ void givenAllArguments_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
+ Vehicle veh = vehicleProcessor.processVehicle("Ford", "Focus", "red", 2200, true);
+ assertThat(veh.toString()).hasToString(vehicle.toString());
+ }
+
+ @Test
+ void givenParameterObject_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
+ Vehicle veh = vehicleProcessor.processVehicle(vehicle);
+ assertThat(veh.toString()).hasToString(vehicle.toString());
+ }
+
+ @Test
+ void givenJavaBeanPattern_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
+ Motorcycle motorcycle = new Motorcycle("Ducati", "Monster", "yellow", 235, true, 2023);
+ motorcycle.setFeatures("GPS");
+
+ vehicleProcessor.processVehicle(motorcycle);
+ assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("GPS");
+ }
+
+ @Test
+ void givenJavaVarargs_whenMethodCall_thenAssertTheReturnedConcatenatedString() {
+ Motorcycle motorcycle = new Motorcycle("Ducati", "Monster", "red", 350, true, 2023);
+ motorcycle.addMotorcycleFeatures("abs");
+ assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs");
+
+ motorcycle.addMotorcycleFeatures("navi", "charger");
+ assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs, navi, charger");
+
+ motorcycle.addMotorcycleFeatures("wifi", "phone", "satellite");
+ assertThat(motorcycle.getFeatures()).isEqualToIgnoringCase("abs, navi, charger, wifi, phone, satellite");
+ }
+
+ @Test
+ void givenJavaBuilderPattern_whenMethodCall_thenVerifyCallIsDoneCorrectly() {
+ Car car = new Car.CarBuilder("Ford", "Focus", 2023).color("blue")
+ .automatic(true)
+ .features("abs, navi, charger, wifi, phone, satellite")
+ .build();
+
+ Car result = vehicleProcessor.processCar(car);
+
+ assertThat(result.toString()).hasToString(car.toString());
+ }
+
+}
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/staticclass/Pizza.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticclass/Pizza.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/staticclass/Pizza.java
rename to core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticclass/Pizza.java
diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Car.java b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Car.java
index 950f008dcd..1158851fbd 100644
--- a/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Car.java
+++ b/core-java-modules/core-java-lang-oop-modifiers/src/main/java/com/baeldung/staticmodifier/Car.java
@@ -42,6 +42,10 @@ public class Car {
this.engine = engine;
}
+ public static String getCarsInformation(Car car) {
+ return car.getName() + "-" + car.getEngine();
+ }
+
public static void setNumberOfCars(int numberOfCars) {
Car.numberOfCars = numberOfCars;
}
diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmethod/CallNonStaticMethodUnitTest.java b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmethod/CallNonStaticMethodUnitTest.java
new file mode 100644
index 0000000000..1171cb2e7a
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmethod/CallNonStaticMethodUnitTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.staticmethod;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.AfterClass;
+import org.junit.Test;
+
+import com.baeldung.staticmodifier.Car;
+
+public class CallNonStaticMethodUnitTest {
+ @AfterClass
+ public static void setUpCarInstance() {
+ Car.setNumberOfCars(0);
+ }
+ @Test
+ public void whenCallingNonStaticMethodInStaticMethodWithInstanceClass_thenSuccess() {
+ Car car = new Car("Jaguar", "V8");
+ assertEquals("Jaguar-V8", Car.getCarsInformation(car));
+ }
+
+}
diff --git a/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/CarUnitTest.java b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/CarUnitTest.java
index f55955caa8..68bbe8f0a2 100644
--- a/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/CarUnitTest.java
+++ b/core-java-modules/core-java-lang-oop-modifiers/src/test/java/com/baeldung/staticmodifier/CarUnitTest.java
@@ -2,9 +2,16 @@ package com.baeldung.staticmodifier;
import static org.junit.Assert.*;
+import org.junit.AfterClass;
import org.junit.Test;
public class CarUnitTest {
+
+ @AfterClass
+ public static void setUpCarInstance() {
+ Car.setNumberOfCars(0);
+ }
+
@Test
public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() {
new Car("Jaguar", "V8");
diff --git a/core-java-modules/core-java-lang-oop-types-2/README.md b/core-java-modules/core-java-lang-oop-types-2/README.md
index ca8742d6c0..f46a1a3306 100644
--- a/core-java-modules/core-java-lang-oop-types-2/README.md
+++ b/core-java-modules/core-java-lang-oop-types-2/README.md
@@ -9,3 +9,4 @@ This module contains articles about types in Java
- [Generate a Random Value From an Enum](https://www.baeldung.com/java-enum-random-value)
- [Filling a List With All Enum Values in Java](https://www.baeldung.com/java-enum-values-to-list)
- [Comparing a String to an Enum Value in Java](https://www.baeldung.com/java-comparing-string-to-enum)
+- [Implementing toString() on enums in Java](https://www.baeldung.com/java-enums-tostring)
diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enumtostring/FastFood1.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enumtostring/FastFood1.java
new file mode 100644
index 0000000000..26338fe46c
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enumtostring/FastFood1.java
@@ -0,0 +1,25 @@
+package com.baeldung.enumtostring;
+
+public enum FastFood1 {
+ PIZZA,
+ BURGER,
+ TACO,
+ CHICKEN,
+ ;
+
+ @Override
+ public String toString() {
+ switch (this) {
+ case PIZZA:
+ return "Pizza Pie";
+ case BURGER:
+ return "Cheese Burger";
+ case TACO:
+ return "Crunchy Taco";
+ case CHICKEN:
+ return "Fried Chicken";
+ default:
+ return "";
+ }
+ }
+}
diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enumtostring/FastFood2.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enumtostring/FastFood2.java
new file mode 100644
index 0000000000..8ca7166dec
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enumtostring/FastFood2.java
@@ -0,0 +1,28 @@
+package com.baeldung.enumtostring;
+
+public enum FastFood2 {
+ PIZZA {
+ @Override
+ public String toString() {
+ return "Pizza Pie";
+ }
+ },
+ BURGER {
+ @Override
+ public String toString() {
+ return "Cheese Burger";
+ }
+ },
+ TACO {
+ @Override
+ public String toString() {
+ return "Crunchy Taco";
+ }
+ },
+ CHICKEN {
+ @Override
+ public String toString() {
+ return "Fried Chicken";
+ }
+ }
+}
diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enumtostring/FastFood3.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enumtostring/FastFood3.java
new file mode 100644
index 0000000000..f6db8f4095
--- /dev/null
+++ b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enumtostring/FastFood3.java
@@ -0,0 +1,29 @@
+package com.baeldung.enumtostring;
+
+public enum FastFood3 {
+ PIZZA("Pizza Pie"),
+ BURGER("Cheese Burger"),
+ TACO("Crunchy Taco"),
+ CHICKEN("Fried Chicken"),
+ ;
+
+ private final String prettyName;
+
+ FastFood3(String prettyName) {
+ this.prettyName = prettyName;
+ }
+
+ FastFood3 fromString(String prettyName) {
+ for (FastFood3 f : values()) {
+ if (f.prettyName.equals(prettyName)) {
+ return f;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public String toString() {
+ return prettyName;
+ }
+}
diff --git a/core-java-modules/core-java-lang-operators-2/pom.xml b/core-java-modules/core-java-lang-operators-2/pom.xml
index 9d925c553a..4170f9f6a0 100644
--- a/core-java-modules/core-java-lang-operators-2/pom.xml
+++ b/core-java-modules/core-java-lang-operators-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-operators-2
- 0.1.0-SNAPSHOT
core-java-lang-operators-2
jar
diff --git a/core-java-modules/core-java-lang-operators/pom.xml b/core-java-modules/core-java-lang-operators/pom.xml
index c61fb81354..1815d01dcc 100644
--- a/core-java-modules/core-java-lang-operators/pom.xml
+++ b/core-java-modules/core-java-lang-operators/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-operators
- 0.1.0-SNAPSHOT
core-java-lang-operators
jar
diff --git a/core-java-modules/core-java-lang-syntax-2/pom.xml b/core-java-modules/core-java-lang-syntax-2/pom.xml
index fdb0503174..bae5f0b6bd 100644
--- a/core-java-modules/core-java-lang-syntax-2/pom.xml
+++ b/core-java-modules/core-java-lang-syntax-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-syntax-2
- 0.1.0-SNAPSHOT
core-java-lang-syntax-2
jar
diff --git a/core-java-modules/core-java-lang-syntax/pom.xml b/core-java-modules/core-java-lang-syntax/pom.xml
index 7cdbc40fbc..005bdc73cc 100644
--- a/core-java-modules/core-java-lang-syntax/pom.xml
+++ b/core-java-modules/core-java-lang-syntax/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang-syntax
- 0.1.0-SNAPSHOT
core-java-lang-syntax
jar
diff --git a/core-java-modules/core-java-lang/pom.xml b/core-java-modules/core-java-lang/pom.xml
index 4989c6a5a7..27cf0ac276 100644
--- a/core-java-modules/core-java-lang/pom.xml
+++ b/core-java-modules/core-java-lang/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-lang
- 0.1.0-SNAPSHOT
core-java-lang
jar
diff --git a/core-java-modules/core-java-locale/README.md b/core-java-modules/core-java-locale/README.md
new file mode 100644
index 0000000000..744b5e760f
--- /dev/null
+++ b/core-java-modules/core-java-locale/README.md
@@ -0,0 +1,6 @@
+ Core Java Locale
+
+### Relevant Articles:
+
+- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
+
diff --git a/core-java-modules/core-java-locale/pom.xml b/core-java-modules/core-java-locale/pom.xml
new file mode 100644
index 0000000000..f493d572a1
--- /dev/null
+++ b/core-java-modules/core-java-locale/pom.xml
@@ -0,0 +1,20 @@
+
+
+ 4.0.0
+ core-java-locale
+ 0.1.0-SNAPSHOT
+ core-java-locale
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleControl.java b/core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleControl.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleControl.java
rename to core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleControl.java
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleResource.java b/core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleResource.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleResource.java
rename to core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleResource.java
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl.java b/core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl.java
rename to core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl.java
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl_PL.java b/core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl_PL.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl_PL.java
rename to core-java-modules/core-java-locale/src/main/java/com/baeldung/resourcebundle/ExampleResource_pl_PL.java
diff --git a/core-java-modules/core-java/src/main/resources/resourcebundle/resource.properties b/core-java-modules/core-java-locale/src/main/resources/resourcebundle/resource.properties
similarity index 100%
rename from core-java-modules/core-java/src/main/resources/resourcebundle/resource.properties
rename to core-java-modules/core-java-locale/src/main/resources/resourcebundle/resource.properties
diff --git a/core-java-modules/core-java/src/main/resources/resourcebundle/resource_en.properties b/core-java-modules/core-java-locale/src/main/resources/resourcebundle/resource_en.properties
similarity index 100%
rename from core-java-modules/core-java/src/main/resources/resourcebundle/resource_en.properties
rename to core-java-modules/core-java-locale/src/main/resources/resourcebundle/resource_en.properties
diff --git a/core-java-modules/core-java/src/main/resources/resourcebundle/resource_pl_PL.properties b/core-java-modules/core-java-locale/src/main/resources/resourcebundle/resource_pl_PL.properties
similarity index 100%
rename from core-java-modules/core-java/src/main/resources/resourcebundle/resource_pl_PL.properties
rename to core-java-modules/core-java-locale/src/main/resources/resourcebundle/resource_pl_PL.properties
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/resourcebundle/ExampleResourceUnitTest.java b/core-java-modules/core-java-locale/src/test/java/com/baeldung/resourcebundle/ExampleResourceUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/resourcebundle/ExampleResourceUnitTest.java
rename to core-java-modules/core-java-locale/src/test/java/com/baeldung/resourcebundle/ExampleResourceUnitTest.java
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/resourcebundle/PropertyResourceUnitTest.java b/core-java-modules/core-java-locale/src/test/java/com/baeldung/resourcebundle/PropertyResourceUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/resourcebundle/PropertyResourceUnitTest.java
rename to core-java-modules/core-java-locale/src/test/java/com/baeldung/resourcebundle/PropertyResourceUnitTest.java
diff --git a/core-java-modules/core-java-networking-2/pom.xml b/core-java-modules/core-java-networking-2/pom.xml
index 982f4fa346..34f16a9938 100644
--- a/core-java-modules/core-java-networking-2/pom.xml
+++ b/core-java-modules/core-java-networking-2/pom.xml
@@ -15,9 +15,9 @@
- org.apache.httpcomponents
- httpclient
- ${httpclient.version}
+ commons-codec
+ commons-codec
+ ${commons-codec.version}
org.apache.commons
@@ -52,11 +52,11 @@
- 4.5.9
2.0.1
2.4.5
2.3.3
2.0.0-alpha-3
+ 1.15
\ No newline at end of file
diff --git a/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/auth/HttpClient.java b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/auth/HttpClient.java
index 779f8aa898..f9d747a133 100644
--- a/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/auth/HttpClient.java
+++ b/core-java-modules/core-java-networking-2/src/main/java/com/baeldung/url/auth/HttpClient.java
@@ -21,7 +21,7 @@ public class HttpClient {
this.password = password;
}
- public int sendRquestWithAuthHeader(String url) throws IOException {
+ public int sendRequestWithAuthHeader(String url) throws IOException {
HttpURLConnection connection = null;
try {
connection = createConnection(url);
@@ -34,7 +34,7 @@ public class HttpClient {
}
}
- public int sendRquestWithAuthenticator(String url) throws IOException {
+ public int sendRequestWithAuthenticator(String url) throws IOException {
setAuthenticator();
HttpURLConnection connection = null;
diff --git a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/auth/HttpClientLiveTest.java b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/auth/HttpClientLiveTest.java
index 01d580bc65..387b228953 100644
--- a/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/auth/HttpClientLiveTest.java
+++ b/core-java-modules/core-java-networking-2/src/test/java/com/baeldung/url/auth/HttpClientLiveTest.java
@@ -7,28 +7,28 @@ import org.junit.Test;
public class HttpClientLiveTest {
@Test
- public void sendRquestWithAuthHeader() throws Exception {
+ public void sendRequestWithAuthHeader() throws Exception {
HttpClient httpClient = new HttpClient("user1", "pass1");
- int status = httpClient.sendRquestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
+ int status = httpClient.sendRequestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
assertTrue(isSuccess(status));
}
@Test
- public void sendRquestWithAuthHeader_whenIncorrectCredentials_thenNotSuccessful() throws Exception {
+ public void sendRequestWithAuthHeader_whenIncorrectCredentials_thenNotSuccessful() throws Exception {
HttpClient httpClient = new HttpClient("John", "Smith");
- int status = httpClient.sendRquestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
+ int status = httpClient.sendRequestWithAuthHeader("https://httpbin.org/basic-auth/user1/pass1");
assertTrue(isUnauthorized(status));
}
@Test
- public void sendRquestWithAuthenticator() throws Exception {
+ public void sendRequestWithAuthenticator() throws Exception {
HttpClient httpClient = new HttpClient("user2", "pass2");
- int status = httpClient.sendRquestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
+ int status = httpClient.sendRequestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
assertTrue(isSuccess(status));
}
@@ -37,7 +37,7 @@ public class HttpClientLiveTest {
public void sendRquestWithAuthenticator_whenIncorrectCredentials_thenNotSuccessful() throws Exception {
HttpClient httpClient = new HttpClient("John", "Smith");
- int status = httpClient.sendRquestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
+ int status = httpClient.sendRequestWithAuthenticator("https://httpbin.org/basic-auth/user2/pass2");
assertTrue(isUnauthorized(status));
}
diff --git a/core-java-modules/core-java-networking-4/README.md b/core-java-modules/core-java-networking-4/README.md
index daec647ebe..10ca7caf41 100644
--- a/core-java-modules/core-java-networking-4/README.md
+++ b/core-java-modules/core-java-networking-4/README.md
@@ -2,3 +2,5 @@
- [Difference Between URI.create() and new URI()](https://www.baeldung.com/java-uri-create-and-new-uri)
- [Validating URL in Java](https://www.baeldung.com/java-validate-url)
- [Validating IPv4 Address in Java](https://www.baeldung.com/java-validate-ipv4-address)
+- [Download a Webpage in Java](https://www.baeldung.com/java-download-webpage)
+- [URL Query Manipulation in Java](https://www.baeldung.com/java-url-query-manipulation)
diff --git a/core-java-modules/core-java-networking-4/pom.xml b/core-java-modules/core-java-networking-4/pom.xml
index 29531a5767..cbe6356d0f 100644
--- a/core-java-modules/core-java-networking-4/pom.xml
+++ b/core-java-modules/core-java-networking-4/pom.xml
@@ -14,12 +14,40 @@
-
commons-validator
commons-validator
${apache.commons-validator.version}
+
+ org.jsoup
+ jsoup
+ ${jsoup.version}
+
+
+
+ org.apache.httpcomponents
+ httpclient
+ 4.5.2
+
+
+
+ javax.ws.rs
+ javax.ws.rs-api
+ 2.1.1
+
+
+ org.glassfish.jersey.core
+ jersey-common
+ 2.22.2
+ test
+
+
+
+ org.springframework
+ spring-web
+ 6.0.6
+
@@ -28,6 +56,7 @@
1.7
+ 1.15.4
\ No newline at end of file
diff --git a/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/downloadwebpage/DownloadWebpageUnitTest.java b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/downloadwebpage/DownloadWebpageUnitTest.java
new file mode 100644
index 0000000000..23b8928ecb
--- /dev/null
+++ b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/downloadwebpage/DownloadWebpageUnitTest.java
@@ -0,0 +1,48 @@
+package com.baeldung.downloadwebpage;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import org.jsoup.Jsoup;
+import org.jsoup.nodes.Document;
+import org.junit.jupiter.api.Test;
+
+class DownloadWebpageUnitTest {
+
+ @Test
+ public void givenURLConnection_whenRetrieveWebpage_thenWebpageIsNotNullAndContainsHtmlTag() throws IOException {
+ URL url = new URL("https://example.com");
+ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+ connection.setRequestMethod("GET");
+
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
+ StringBuilder responseBuilder = new StringBuilder();
+ String line;
+ while ((line = reader.readLine()) != null) {
+ responseBuilder.append(line);
+ }
+
+ assertNotNull(responseBuilder);
+ assertTrue(responseBuilder.toString()
+ .contains(""));
+ }
+
+ }
+
+ @Test
+ public void givenJsoup_whenRetrievingWebpage_thenWebpageDocumentIsNotNullAndContainsHtmlTag() throws IOException {
+
+ Document document = Jsoup.connect("https://example.com")
+ .get();
+ String webpage = document.html();
+
+ assertNotNull(webpage);
+ assertTrue(webpage.contains(""));
+
+ }
+
+}
diff --git a/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/urlquerymanipulation/UrlQueryManipulationUnitTest.java b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/urlquerymanipulation/UrlQueryManipulationUnitTest.java
new file mode 100644
index 0000000000..cc53a3e3a8
--- /dev/null
+++ b/core-java-modules/core-java-networking-4/src/test/java/com/baeldung/urlquerymanipulation/UrlQueryManipulationUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.urlquerymanipulation;
+
+import static junit.framework.TestCase.assertEquals;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import javax.ws.rs.core.UriBuilder;
+
+import org.apache.http.client.utils.URIBuilder;
+
+import org.junit.Test;
+import org.springframework.web.util.UriComponentsBuilder;
+
+public class UrlQueryManipulationUnitTest {
+
+ @Test
+ public void whenUsingApacheUriBuilder_thenParametersAreCorrectlyAdded() throws URISyntaxException {
+ String url = "baeldung.com";
+ String key = "article";
+ String value = "alpha";
+ URI uri = new URIBuilder(url).addParameter(key, value)
+ .build();
+
+ assertEquals("baeldung.com?article=alpha", uri.toString());
+ }
+
+ @Test
+ public void whenUsingJavaUriBuilder_thenParametersAreCorrectlyAdded() {
+ String url = "baeldung.com";
+ String key = "article";
+ String value = "beta";
+ URI uri = UriBuilder.fromUri(url)
+ .queryParam(key, value)
+ .build();
+
+ assertEquals("baeldung.com?article=beta", uri.toString());
+ }
+
+ @Test
+ public void whenUsingSpringUriComponentsBuilder_thenParametersAreCorrectlyAdded() {
+ String url = "baeldung.com";
+ String key = "article";
+ String value = "charlie";
+ URI uri = UriComponentsBuilder.fromUriString(url)
+ .queryParam(key, value)
+ .build()
+ .toUri();
+
+ assertEquals("baeldung.com?article=charlie", uri.toString());
+ }
+
+}
diff --git a/core-java-modules/core-java-networking/pom.xml b/core-java-modules/core-java-networking/pom.xml
index 9974134eae..59aadbd1ed 100644
--- a/core-java-modules/core-java-networking/pom.xml
+++ b/core-java-modules/core-java-networking/pom.xml
@@ -1,10 +1,9 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-networking
- 0.1.0-SNAPSHOT
core-java-networking
jar
@@ -20,6 +19,11 @@
spring-web
${springframework.spring-web.version}
+
+ org.apache.httpcomponents
+ httpclient
+ ${apache.httpclient.version}
+
@@ -28,6 +32,7 @@
4.3.4.RELEASE
+ 4.5.14
\ No newline at end of file
diff --git a/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java b/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java
index 112f2cf53f..87d9d7a620 100644
--- a/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java
+++ b/core-java-modules/core-java-networking/src/test/java/com/baeldung/networking/url/UrlUnitTest.java
@@ -1,11 +1,19 @@
package com.baeldung.networking.url;
+import static java.util.stream.Collectors.toList;
import static org.junit.Assert.assertEquals;
import java.net.MalformedURLException;
+import java.net.URISyntaxException;
import java.net.URL;
+import java.util.Map;
+import org.apache.http.client.utils.URIBuilder;
+import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;
+import org.springframework.web.util.UriComponentsBuilder;
+
+import com.google.common.collect.ImmutableMap;
public class UrlUnitTest {
@@ -101,4 +109,44 @@ public class UrlUnitTest {
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
}
-}
+ @Test
+ public void givenUrlParameters_whenBuildUrlWithURIBuilder_thenSuccess() throws URISyntaxException, MalformedURLException {
+ URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles");
+ uriBuilder.setPort(9090);
+ uriBuilder.addParameter("topic", "java");
+ uriBuilder.addParameter("version", "8");
+ URL url = uriBuilder.build().toURL();
+ assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
+ }
+
+ @Test
+ public void givenUrlParametersInMap_whenBuildUrlWithURIBuilder_thenSuccess() throws URISyntaxException, MalformedURLException {
+ Map paramMap = ImmutableMap.of("topic", "java", "version", "8");
+ URIBuilder uriBuilder = new URIBuilder("http://baeldung.com/articles");
+ uriBuilder.setPort(9090);
+ uriBuilder.addParameters(paramMap.entrySet()
+ .stream()
+ .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
+ .collect(toList()));
+
+ URL url = uriBuilder.build().toURL();
+ assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
+ }
+
+ @Test
+ public void givenUrlParameters_whenBuildUrlWithSpringUriComponentsBuilder_thenSuccess() throws MalformedURLException {
+ URL url = UriComponentsBuilder.newInstance()
+ .scheme("http")
+ .host("baeldung.com")
+ .port(9090)
+ .path("articles")
+ .queryParam("topic", "java")
+ .queryParam("version", "8")
+ .build()
+ .toUri()
+ .toURL();
+
+ assertEquals("http://baeldung.com:9090/articles?topic=java&version=8", url.toString());
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-nio-2/pom.xml b/core-java-modules/core-java-nio-2/pom.xml
index eb56c2bf68..e35b70cfc7 100644
--- a/core-java-modules/core-java-nio-2/pom.xml
+++ b/core-java-modules/core-java-nio-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-nio-2
- 0.1.0-SNAPSHOT
core-java-nio-2
jar
diff --git a/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoServer.java b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoServer.java
index 9e9edcd0ba..c8b638dc04 100644
--- a/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoServer.java
+++ b/core-java-modules/core-java-nio-2/src/main/java/com/baeldung/selector/EchoServer.java
@@ -45,8 +45,9 @@ public class EchoServer {
private static void answerWithEcho(ByteBuffer buffer, SelectionKey key) throws IOException {
SocketChannel client = (SocketChannel) key.channel();
- client.read(buffer);
- if (new String(buffer.array()).trim().equals(POISON_PILL)) {
+ int r = client.read(buffer);
+ if (r == -1 || new String(buffer.array()).trim()
+ .equals(POISON_PILL)) {
client.close();
System.out.println("Not accepting client messages anymore");
} else {
diff --git a/core-java-modules/core-java-nio/pom.xml b/core-java-modules/core-java-nio/pom.xml
index 9e1c529a65..35fef82df5 100644
--- a/core-java-modules/core-java-nio/pom.xml
+++ b/core-java-modules/core-java-nio/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-nio
- 0.1.0-SNAPSHOT
core-java-nio
jar
diff --git a/core-java-modules/core-java-nio/src/main/java/com/baeldung/lines/NumberOfLineFinder.java b/core-java-modules/core-java-nio/src/main/java/com/baeldung/lines/NumberOfLineFinder.java
index b355295dab..f5d5fb2b4f 100644
--- a/core-java-modules/core-java-nio/src/main/java/com/baeldung/lines/NumberOfLineFinder.java
+++ b/core-java-modules/core-java-nio/src/main/java/com/baeldung/lines/NumberOfLineFinder.java
@@ -37,7 +37,7 @@ public class NumberOfLineFinder {
int lines = 0;
try (LineNumberReader reader = new LineNumberReader(new FileReader(fileName))) {
reader.skip(Integer.MAX_VALUE);
- lines = reader.getLineNumber() + 1;
+ lines = reader.getLineNumber();
} catch (IOException ioe) {
ioe.printStackTrace();
}
diff --git a/core-java-modules/core-java-nio/src/test/java/com/baeldung/creationdate/CreationDateResolverUnitTest.java b/core-java-modules/core-java-nio/src/test/java/com/baeldung/creationdate/CreationDateResolverUnitTest.java
index 5402852c74..5e7929859d 100644
--- a/core-java-modules/core-java-nio/src/test/java/com/baeldung/creationdate/CreationDateResolverUnitTest.java
+++ b/core-java-modules/core-java-nio/src/test/java/com/baeldung/creationdate/CreationDateResolverUnitTest.java
@@ -21,9 +21,11 @@ public class CreationDateResolverUnitTest {
final Instant response = creationDateResolver.resolveCreationTimeWithBasicAttributes(path);
- assertTrue(Instant
- .now()
- .isAfter(response));
+ Optional.of(response).ifPresent((value) -> {
+ assertTrue(Instant
+ .now()
+ .isAfter(value));
+ });
}
diff --git a/core-java-modules/core-java-numbers-2/pom.xml b/core-java-modules/core-java-numbers-2/pom.xml
index ac3843607e..46e0fa47b4 100644
--- a/core-java-modules/core-java-numbers-2/pom.xml
+++ b/core-java-modules/core-java-numbers-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-numbers-2
- 0.1.0-SNAPSHOT
core-java-numbers-2
jar
diff --git a/core-java-modules/core-java-numbers-3/src/test/java/com/baeldung/formatNumber/FormatNumberUnitTest.java b/core-java-modules/core-java-numbers-3/src/test/java/com/baeldung/formatNumber/FormatNumberUnitTest.java
index 4f0358c6a2..6d78426a56 100644
--- a/core-java-modules/core-java-numbers-3/src/test/java/com/baeldung/formatNumber/FormatNumberUnitTest.java
+++ b/core-java-modules/core-java-numbers-3/src/test/java/com/baeldung/formatNumber/FormatNumberUnitTest.java
@@ -75,8 +75,8 @@ public class FormatNumberUnitTest {
public void givenCurrency_whenFormatNumberCurrencyWithChosenLocalisation_thenGetExpectedResult() {
double value = 23_500;
assertThat(currencyWithChosenLocalisation(value, new Locale("en", "US"))).isEqualTo("$23,500.00");
- assertThat(currencyWithChosenLocalisation(value, new Locale("zh", "CN"))).isEqualTo("¥23,500.00");
- assertThat(currencyWithChosenLocalisation(value, new Locale("pl", "PL"))).isEqualTo("23 500 zł");
+ assertThat(currencyWithChosenLocalisation(value, new Locale("zh", "CN"))).isEqualTo("¥23,500.00");
+ assertThat(currencyWithChosenLocalisation(value, new Locale("pl", "PL"))).isEqualTo("23 500,00 zł");
}
}
diff --git a/core-java-modules/core-java-numbers-6/README.md b/core-java-modules/core-java-numbers-6/README.md
new file mode 100644
index 0000000000..97e4e2ca28
--- /dev/null
+++ b/core-java-modules/core-java-numbers-6/README.md
@@ -0,0 +1,4 @@
+### Relevant Articles:
+- [Java Program to Calculate Pi](https://www.baeldung.com/java-monte-carlo-compute-pi)
+- [Convert Integer to Hexadecimal in Java](https://www.baeldung.com/java-convert-int-to-hex)
+- More articles: [[<-- prev]](../core-java-numbers-5)
diff --git a/core-java-modules/core-java-numbers-6/pom.xml b/core-java-modules/core-java-numbers-6/pom.xml
new file mode 100644
index 0000000000..531f1293d1
--- /dev/null
+++ b/core-java-modules/core-java-numbers-6/pom.xml
@@ -0,0 +1,43 @@
+
+ 4.0.0
+ core-java-numbers-6
+ core-java-numbers-6
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ org.junit.jupiter
+ junit-jupiter-engine
+ ${junit-jupiter.version}
+ test
+
+
+ commons-codec
+ commons-codec
+ ${commons-codec}
+ test
+
+
+
+
+ core-java-numbers-6
+
+
+ src/main/resources
+ true
+
+
+
+
+
+ 1.15
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-numbers-6/src/main/java/com/baeldung/integertohex/IntegerToHex.java b/core-java-modules/core-java-numbers-6/src/main/java/com/baeldung/integertohex/IntegerToHex.java
new file mode 100644
index 0000000000..9f75b9a145
--- /dev/null
+++ b/core-java-modules/core-java-numbers-6/src/main/java/com/baeldung/integertohex/IntegerToHex.java
@@ -0,0 +1,16 @@
+package com.baeldung.integertohex;
+
+class IntegerToHex {
+ static final String digits = "0123456789ABCDEF";
+ static String integerToHex(int input) {
+ if (input <= 0)
+ return "0";
+ StringBuilder hex = new StringBuilder();
+ while (input > 0) {
+ int digit = input % 16;
+ hex.insert(0, digits.charAt(digit));
+ input = input / 16;
+ }
+ return hex.toString();
+ }
+}
diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integertohex/IntegerToHexUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integertohex/IntegerToHexUnitTest.java
new file mode 100644
index 0000000000..6073c2d347
--- /dev/null
+++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/integertohex/IntegerToHexUnitTest.java
@@ -0,0 +1,75 @@
+package com.baeldung.integertohex;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.apache.commons.codec.binary.Hex;
+import org.junit.jupiter.api.Test;
+
+class IntegerToHexUnitTest {
+
+ @Test
+ void givenIntegerValue_whenUseRawMethod_thenWillGetHexValue() {
+ String result = IntegerToHex.integerToHex(1055);
+ assertEquals("41F", result);
+ }
+
+ @Test
+ void givenIntegerNegativeValue_whenUseRawMethod_thenZeroValue() {
+ String result = IntegerToHex.integerToHex(-1055);
+ assertEquals("0", result);
+ }
+
+ @Test
+ void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValue() {
+ String result = String.format("%02x", 255);
+ assertEquals("ff", result);
+ }
+
+ @Test
+ void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValueWithLeftZeros() {
+ String result = String.format("%04x", 255);
+ assertEquals("00ff", result);
+ }
+
+ @Test
+ void givenIntegerPositiveValue_whenUseStringFormat_thenWillGetHexValueWithLeftZerosAndUpperLetter() {
+ String result = String.format("%04X", 255);
+ assertEquals("00FF", result);
+ }
+
+ @Test
+ void givenIntegerValue_whenUseIntegerToHexString_thenWillGetHexValue() {
+ String result = Integer.toHexString(1000);
+ assertEquals("3e8", result);
+ }
+
+ @Test
+ void givenIntegerValue_whenUseLongToHexString_thenWillGetHexValue() {
+ String result = Long.toHexString(255L);
+ assertEquals("ff", result);
+ }
+
+ @Test
+ public void givenNegativeIntegerValue_whenUseIntegerToString_thenWillGetHexValue() {
+ String result = Integer.toString(-1458, 16);
+ assertEquals("-5b2", result);
+ }
+
+ @Test
+ public void givenIntegerValue_whenUseIntegerToString_thenWillGetHexValue() {
+ String result = Integer.toString(1458, 16);
+ assertEquals("5b2", result);
+ }
+
+ @Test
+ public void givenLongValue_whenUseLongToString_thenWillGetHexValue() {
+ String result = Long.toString(158, 16);
+ assertEquals("9e", result);
+ }
+
+ @Test
+ public void givenIntegerValue_whenUseApacheCommons_thenWillGetHexSignedValue() {
+ String result = Hex.encodeHexString(new byte[] { (byte) 254 });
+ assertEquals("fe", result);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/pi/PiProgramUnitTest.java b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/pi/PiProgramUnitTest.java
new file mode 100644
index 0000000000..d47942a517
--- /dev/null
+++ b/core-java-modules/core-java-numbers-6/src/test/java/com/baeldung/pi/PiProgramUnitTest.java
@@ -0,0 +1,31 @@
+package com.baeldung.pi;
+
+import static org.junit.Assert.*;
+
+import java.util.Random;
+import org.junit.Test;
+
+public class PiProgramUnitTest {
+
+ @Test
+ public void givenPiCalculator_whenCalculatePiWithOneMillionPoints_thenEstimatedPiIsWithinTolerance() {
+ int totalPoints = 1000000;
+ int insideCircle = 0;
+
+ Random random = new Random();
+
+ for (long i = 0; i < totalPoints; i++) {
+ double x = random.nextDouble() * 2 - 1;
+ double y = random.nextDouble() * 2 - 1;
+
+ if (x * x + y * y <= 1) {
+ insideCircle++;
+ }
+
+ }
+ double pi = 4.0 * insideCircle / totalPoints;
+
+ assertEquals(Math.PI, pi, 0.01);
+ }
+
+}
diff --git a/core-java-modules/core-java-numbers-conversions/README.md b/core-java-modules/core-java-numbers-conversions/README.md
new file mode 100644
index 0000000000..21810834bd
--- /dev/null
+++ b/core-java-modules/core-java-numbers-conversions/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Convert a Number to a Letter in Java](https://www.baeldung.com/java-convert-number-to-letter)
diff --git a/core-java-modules/core-java-numbers-conversions/pom.xml b/core-java-modules/core-java-numbers-conversions/pom.xml
new file mode 100644
index 0000000000..55df86d5c7
--- /dev/null
+++ b/core-java-modules/core-java-numbers-conversions/pom.xml
@@ -0,0 +1,25 @@
+
+ 4.0.0
+ core-java-numbers-conversions
+ core-java-numbers-conversions
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+ core-java-numbers-conversions
+
+
+ src/main/resources
+ true
+
+
+
+
+
diff --git a/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/numtoletter/ConvertNumberToLetterUnitTest.java b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/numtoletter/ConvertNumberToLetterUnitTest.java
new file mode 100644
index 0000000000..5652969761
--- /dev/null
+++ b/core-java-modules/core-java-numbers-conversions/src/test/java/com/baeldung/numtoletter/ConvertNumberToLetterUnitTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.numtoletter;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+
+public class ConvertNumberToLetterUnitTest {
+
+ static char numToLetterBySubstr(int i) {
+ String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+ if (i > 0 && i <= 25) {
+ return LETTERS.substring(i, i + 1).charAt(0);
+ } else {
+ return '?';
+ }
+ }
+
+ static char numToLetterByAsciiCode(int i) {
+ if (i > 0 && i <= 25) {
+ return (char) ('A' + i);
+ } else {
+ return '?';
+ }
+ }
+
+ @Test
+ void givenANumber_whenConvertToLetterUsingSubstring_shouldGetExpectedResult() {
+ char negativeInputResult = numToLetterBySubstr(-7);
+ assertEquals('?', negativeInputResult);
+
+ char tooLargeInputResult = numToLetterBySubstr(42);
+ assertEquals('?', tooLargeInputResult);
+
+ char result = numToLetterBySubstr(10);
+ assertEquals('K', result);
+ }
+
+ @Test
+ void givenANumber_whenConvertToLetterUsingAscii_shouldGetExpectedResult() {
+ char negativeInputResult = numToLetterByAsciiCode(-7);
+ assertEquals('?', negativeInputResult);
+
+ char tooLargeInputResult = numToLetterByAsciiCode(42);
+ assertEquals('?', tooLargeInputResult);
+
+ char charResult = numToLetterByAsciiCode(10);
+ assertEquals('K', charResult);
+
+ assertEquals("K", String.valueOf(charResult));
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-numbers/pom.xml b/core-java-modules/core-java-numbers/pom.xml
index 4b2cae8ee9..38def238e8 100644
--- a/core-java-modules/core-java-numbers/pom.xml
+++ b/core-java-modules/core-java-numbers/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-numbers
- 0.1.0-SNAPSHOT
core-java-numbers
jar
diff --git a/core-java-modules/core-java-optional/pom.xml b/core-java-modules/core-java-optional/pom.xml
index 08441f6cee..eeefed867e 100644
--- a/core-java-modules/core-java-optional/pom.xml
+++ b/core-java-modules/core-java-optional/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-optional
- 0.1.0-SNAPSHOT
core-java-optional
jar
diff --git a/core-java-modules/core-java-os/pom.xml b/core-java-modules/core-java-os/pom.xml
index ef29e435a5..d4ee34b8b7 100644
--- a/core-java-modules/core-java-os/pom.xml
+++ b/core-java-modules/core-java-os/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-os
- 0.1.0-SNAPSHOT
core-java-os
jar
diff --git a/core-java-modules/core-java-perf-2/README.md b/core-java-modules/core-java-perf-2/README.md
new file mode 100644
index 0000000000..5616cce48b
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/README.md
@@ -0,0 +1 @@
+## Relevant Articles
diff --git a/core-java-modules/core-java-perf-2/pom.xml b/core-java-modules/core-java-perf-2/pom.xml
new file mode 100644
index 0000000000..a9408ca385
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/pom.xml
@@ -0,0 +1,16 @@
+
+
+ 4.0.0
+ core-java-perf-2
+ core-java-perf-2
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/highcpu/Application.java b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/highcpu/Application.java
new file mode 100644
index 0000000000..82162406b3
--- /dev/null
+++ b/core-java-modules/core-java-perf-2/src/main/java/com/baeldung/highcpu/Application.java
@@ -0,0 +1,20 @@
+package com.baeldung.highcpu;
+
+import java.util.LinkedList;
+import java.util.List;
+import java.util.function.IntUnaryOperator;
+import java.util.stream.IntStream;
+
+public class Application {
+
+ static List generateList() {
+ return IntStream.range(0, 10000000).parallel().map(IntUnaryOperator.identity()).collect(LinkedList::new, List::add, List::addAll);
+ }
+
+ public static void main(String[] args) {
+ List list = generateList();
+ long start = System.nanoTime();
+ int value = list.get(9500000);
+ System.out.printf("Found value %d in %d nanos\n", value, (System.nanoTime() - start));
+ }
+}
diff --git a/core-java-modules/core-java-perf/README.md b/core-java-modules/core-java-perf/README.md
index c018ec9927..c400f1d196 100644
--- a/core-java-modules/core-java-perf/README.md
+++ b/core-java-modules/core-java-perf/README.md
@@ -13,3 +13,5 @@ This module contains articles about performance of Java applications
- [Capturing a Java Thread Dump](https://www.baeldung.com/java-thread-dump)
- [JMX Ports](https://www.baeldung.com/jmx-ports)
- [Calling JMX MBean Method From a Shell Script](https://www.baeldung.com/jmx-mbean-shell-access)
+- [External Debugging With JMXTerm](https://www.baeldung.com/java-jmxterm-external-debugging)
+- [Create and Detect Memory Leaks in Java](https://www.baeldung.com/java-create-detect-memory-leaks)
diff --git a/core-java-modules/core-java-perf/pom.xml b/core-java-modules/core-java-perf/pom.xml
index f6f3ef795c..c21fc94ec1 100644
--- a/core-java-modules/core-java-perf/pom.xml
+++ b/core-java-modules/core-java-perf/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-perf
- 0.1.0-SNAPSHOT
core-java-perf
jar
diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/AbstractPlayerMBean.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/AbstractPlayerMBean.java
new file mode 100644
index 0000000000..698d107c51
--- /dev/null
+++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/AbstractPlayerMBean.java
@@ -0,0 +1,16 @@
+package com.baeldung.jmxterm;
+
+import java.util.UUID;
+
+public abstract class AbstractPlayerMBean implements PlayerMBean{
+
+ private final UUID id;
+
+ protected AbstractPlayerMBean() {
+ this.id = UUID.randomUUID();
+ }
+
+ String getId() {
+ return getName() + id.toString();
+ }
+}
diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/BroadcastingGuessGame.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/BroadcastingGuessGame.java
new file mode 100644
index 0000000000..921d87c4d7
--- /dev/null
+++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/BroadcastingGuessGame.java
@@ -0,0 +1,42 @@
+package com.baeldung.jmxterm;
+
+import javax.management.ListenerNotFoundException;
+import javax.management.MBeanNotificationInfo;
+import javax.management.Notification;
+import javax.management.NotificationBroadcaster;
+import javax.management.NotificationBroadcasterSupport;
+import javax.management.NotificationFilter;
+import javax.management.NotificationListener;
+
+public abstract class BroadcastingGuessGame implements NotificationBroadcaster, GuessGameMBean {
+ private final NotificationBroadcasterSupport broadcaster =
+ new NotificationBroadcasterSupport();
+
+ private long notificationSequence = 0;
+
+ private final MBeanNotificationInfo[] notificationInfo;
+
+ protected BroadcastingGuessGame() {
+ this.notificationInfo = new MBeanNotificationInfo[]{
+ new MBeanNotificationInfo(new String[]{"game"}, Notification.class.getName(), "Game notification")
+ };
+ }
+
+ protected void notifyAboutWinner(Player winner) {
+ String message = "Winner is " + winner.getName() + " with score " + winner.getScore();
+ Notification notification = new Notification("game.winner", this, notificationSequence++, message);
+ broadcaster.sendNotification(notification);
+ }
+
+ public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) {
+ broadcaster.addNotificationListener(listener, filter, handback);
+ }
+
+ public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
+ broadcaster.removeNotificationListener(listener);
+ }
+
+ public MBeanNotificationInfo[] getNotificationInfo() {
+ return notificationInfo;
+ }
+}
diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/GameRunner.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/GameRunner.java
new file mode 100644
index 0000000000..3955d37504
--- /dev/null
+++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/GameRunner.java
@@ -0,0 +1,19 @@
+package com.baeldung.jmxterm;
+
+import java.util.Arrays;
+import java.util.List;
+
+public class GameRunner {
+
+ public static void main(String[] args) {
+ MBeanGameServer mBeanGameServer = new MBeanGameServer();
+ Player bob = new Player("Bob");
+ Player alice = new Player("Alice");
+ Player john = new Player("John");
+ List players = Arrays.asList(bob, alice, john);
+ GuessGame guessGame = new GuessGame(players);
+ mBeanGameServer.registerGame(guessGame);
+ guessGame.start();
+ }
+
+}
diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/GuessGame.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/GuessGame.java
new file mode 100644
index 0000000000..c9d680880f
--- /dev/null
+++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/GuessGame.java
@@ -0,0 +1,80 @@
+package com.baeldung.jmxterm;
+
+import static com.baeldung.jmxterm.RandomNumbergenerator.generateRandomNumber;
+
+import java.util.List;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class GuessGame extends BroadcastingGuessGame {
+
+
+ public static final int SECOND = 1000;
+ private static final Logger log = Logger.getLogger(GuessGame.class.getCanonicalName());
+ private final List players;
+ private volatile boolean isFinished = false;
+ private volatile boolean isPaused = false;
+
+
+ public GuessGame(List players) {
+ this.players = players;
+ log.setLevel(Level.WARNING);
+ }
+
+ public void start() {
+ int randomNumber = generateRandomNumber();
+ while (!isFinished) {
+ waitASecond();
+ while (!isPaused && !isFinished) {
+ log.info("Current random number is " + randomNumber);
+ waitASecond();
+ for (Player player : players) {
+ int guess = player.guessNumber();
+ if (guess == randomNumber) {
+ log.info("Players " + player.getName() + " " + guess + " is correct");
+ player.incrementScore();
+ notifyAboutWinner(player);
+ randomNumber = generateRandomNumber();
+ break;
+ }
+ log.info("Player " + player.getName() + " guessed incorrectly with " + guess);
+ }
+ log.info("\n");
+ }
+ if (isPaused) {
+ log.info("Game is paused");
+ }
+ if (isFinished) {
+ log.info("Game is finished");
+ }
+ }
+ }
+
+ @Override
+ public void finishGame() {
+ isFinished = true;
+ }
+
+ @Override
+ public void pauseGame() {
+ isPaused = true;
+ }
+
+ @Override
+ public void unpauseGame() {
+ isPaused = false;
+ }
+
+ public List getPlayers() {
+ return players;
+ }
+
+ private void waitASecond() {
+ try {
+ Thread.sleep(SECOND);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/GuessGameMBean.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/GuessGameMBean.java
new file mode 100644
index 0000000000..fdf8149f71
--- /dev/null
+++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/GuessGameMBean.java
@@ -0,0 +1,8 @@
+package com.baeldung.jmxterm;
+
+public interface GuessGameMBean {
+
+ void finishGame();
+ void pauseGame();
+ void unpauseGame();
+}
diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/MBeanGameServer.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/MBeanGameServer.java
new file mode 100644
index 0000000000..922a0baf76
--- /dev/null
+++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/MBeanGameServer.java
@@ -0,0 +1,37 @@
+package com.baeldung.jmxterm;
+
+import java.lang.management.ManagementFactory;
+import javax.management.InstanceAlreadyExistsException;
+import javax.management.MBeanRegistrationException;
+import javax.management.MBeanServer;
+import javax.management.MalformedObjectNameException;
+import javax.management.NotCompliantMBeanException;
+import javax.management.ObjectName;
+
+public class MBeanGameServer {
+
+ public static final String ID_FORMAT = "com.baeldung.jmxterm:type=%s,id=%s";
+ private final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
+
+ public void registerPlayer(AbstractPlayerMBean player) {
+ registerBean(player, "player", player.getId());
+ }
+
+ public void registerGame(GuessGame guessGame) {
+ registerBean(guessGame, "game", "singlegame");
+ guessGame.getPlayers().forEach(this::registerPlayer);
+ }
+
+ private void registerBean(Object bean, String type, String id) {
+ try {
+ ObjectName name = new ObjectName(String.format(ID_FORMAT, type, id));
+ server.registerMBean(bean, name);
+ } catch (InstanceAlreadyExistsException |
+ MBeanRegistrationException |
+ NotCompliantMBeanException |
+ MalformedObjectNameException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+}
diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/Player.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/Player.java
new file mode 100644
index 0000000000..b24e313902
--- /dev/null
+++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/Player.java
@@ -0,0 +1,33 @@
+package com.baeldung.jmxterm;
+
+import static com.baeldung.jmxterm.RandomNumbergenerator.*;
+
+public class Player extends AbstractPlayerMBean {
+ private final String name;
+ private int score = 0;
+
+ public Player(String name) {
+ super();
+ this.name = name;
+ }
+
+ @Override
+ public int guessNumber() {
+ return generateRandomNumber();
+ }
+
+ public void incrementScore() {
+ score++;
+ }
+
+ @Override
+ public int getScore() {
+ return score;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+}
diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/PlayerMBean.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/PlayerMBean.java
new file mode 100644
index 0000000000..78b73ff578
--- /dev/null
+++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/PlayerMBean.java
@@ -0,0 +1,10 @@
+package com.baeldung.jmxterm;
+
+public interface PlayerMBean {
+
+ int guessNumber();
+
+ int getScore();
+
+ String getName();
+}
diff --git a/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/RandomNumbergenerator.java b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/RandomNumbergenerator.java
new file mode 100644
index 0000000000..1418f502c6
--- /dev/null
+++ b/core-java-modules/core-java-perf/src/main/java/com/baeldung/jmxterm/RandomNumbergenerator.java
@@ -0,0 +1,18 @@
+package com.baeldung.jmxterm;
+
+import java.util.concurrent.ThreadLocalRandom;
+
+public class RandomNumbergenerator {
+
+ private static final int MIN = 0;
+ private static final int MAX = 10;
+
+ private static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();
+
+ private RandomNumbergenerator() {
+ }
+ public static int generateRandomNumber() {
+ return RANDOM.nextInt(MIN, MAX + 1);
+ }
+
+}
diff --git a/core-java-modules/core-java-perf/src/test/java/com/baeldung/jmxterm/PlayerUnitTest.java b/core-java-modules/core-java-perf/src/test/java/com/baeldung/jmxterm/PlayerUnitTest.java
new file mode 100644
index 0000000000..a0f31b1995
--- /dev/null
+++ b/core-java-modules/core-java-perf/src/test/java/com/baeldung/jmxterm/PlayerUnitTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.jmxterm;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+class PlayerUnitTest {
+
+ @Test
+ void givenNewPlayer_thenScoreIsZero() {
+ Player player = new Player("John");
+ assertEquals(0, player.getScore());
+ }
+
+ @Test
+ void givenNewPlayer_whenIncrementScore_thenScoreIsOne() {
+ Player player = new Player("John");
+ player.incrementScore();
+ assertEquals(1, player.getScore());
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-properties/README.md b/core-java-modules/core-java-properties/README.md
new file mode 100644
index 0000000000..73991634df
--- /dev/null
+++ b/core-java-modules/core-java-properties/README.md
@@ -0,0 +1,6 @@
+## Core Java Properties
+
+### Relevant Articles:
+
+- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
+- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
diff --git a/core-java-modules/core-java-properties/pom.xml b/core-java-modules/core-java-properties/pom.xml
new file mode 100644
index 0000000000..9beacabdd5
--- /dev/null
+++ b/core-java-modules/core-java-properties/pom.xml
@@ -0,0 +1,23 @@
+
+
+ 4.0.0
+ core-java-properties
+ 0.1.0-SNAPSHOT
+ core-java-properties
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/util/PropertiesLoader.java b/core-java-modules/core-java-properties/src/main/java/com/baeldung/util/PropertiesLoader.java
similarity index 100%
rename from core-java-modules/core-java/src/main/java/com/baeldung/util/PropertiesLoader.java
rename to core-java-modules/core-java-properties/src/main/java/com/baeldung/util/PropertiesLoader.java
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java b/core-java-modules/core-java-properties/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java
rename to core-java-modules/core-java-properties/src/test/java/com/baeldung/java/properties/PropertiesUnitTest.java
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/properties/MergePropertiesUnitTest.java b/core-java-modules/core-java-properties/src/test/java/com/baeldung/properties/MergePropertiesUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/properties/MergePropertiesUnitTest.java
rename to core-java-modules/core-java-properties/src/test/java/com/baeldung/properties/MergePropertiesUnitTest.java
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java b/core-java-modules/core-java-properties/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java
similarity index 100%
rename from core-java-modules/core-java/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java
rename to core-java-modules/core-java-properties/src/test/java/com/baeldung/util/PropertiesLoaderUnitTest.java
diff --git a/core-java-modules/core-java/src/test/resources/app.properties b/core-java-modules/core-java-properties/src/test/resources/app.properties
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/app.properties
rename to core-java-modules/core-java-properties/src/test/resources/app.properties
diff --git a/core-java-modules/core-java/src/test/resources/catalog b/core-java-modules/core-java-properties/src/test/resources/catalog
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/catalog
rename to core-java-modules/core-java-properties/src/test/resources/catalog
diff --git a/core-java-modules/core-java/src/test/resources/configuration.properties b/core-java-modules/core-java-properties/src/test/resources/configuration.properties
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/configuration.properties
rename to core-java-modules/core-java-properties/src/test/resources/configuration.properties
diff --git a/core-java-modules/core-java/src/test/resources/default.properties b/core-java-modules/core-java-properties/src/test/resources/default.properties
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/default.properties
rename to core-java-modules/core-java-properties/src/test/resources/default.properties
diff --git a/core-java-modules/core-java/src/test/resources/icons.xml b/core-java-modules/core-java-properties/src/test/resources/icons.xml
similarity index 100%
rename from core-java-modules/core-java/src/test/resources/icons.xml
rename to core-java-modules/core-java-properties/src/test/resources/icons.xml
diff --git a/core-java-modules/core-java-records/README.md b/core-java-modules/core-java-records/README.md
new file mode 100644
index 0000000000..2e7ad00cd3
--- /dev/null
+++ b/core-java-modules/core-java-records/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Overridding hashCode() And equals() For Records](https://www.baeldung.com/java-override-hashcode-equals-records)
diff --git a/core-java-modules/core-java-records/pom.xml b/core-java-modules/core-java-records/pom.xml
new file mode 100644
index 0000000000..ed9a36fc14
--- /dev/null
+++ b/core-java-modules/core-java-records/pom.xml
@@ -0,0 +1,32 @@
+
+
+
+ core-java-modules
+ com.baeldung.core-java-modules
+ 0.0.1-SNAPSHOT
+
+ 4.0.0
+
+ core-java-records
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ 16
+
+
+
+
+
+
+ 19
+ 19
+ UTF-8
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Movie.java b/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Movie.java
new file mode 100644
index 0000000000..e94638e8b5
--- /dev/null
+++ b/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Movie.java
@@ -0,0 +1,26 @@
+package com.baeldung.equalshashcoderecords;
+
+import java.util.Objects;
+
+record Movie(String name, Integer yearOfRelease, String distributor) {
+
+@Override
+public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (other == null) {
+ return false;
+ }
+ Movie movie = (Movie) other;
+ if (movie.name.equals(this.name) && movie.yearOfRelease.equals(this.yearOfRelease)) {
+ return true;
+ }
+ return false;
+}
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, yearOfRelease);
+ }
+}
diff --git a/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Person.java b/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Person.java
new file mode 100644
index 0000000000..7bfd8ae741
--- /dev/null
+++ b/core-java-modules/core-java-records/src/main/java/com/baeldung/equalshashcoderecords/Person.java
@@ -0,0 +1,5 @@
+package com.baeldung.equalshashcoderecords;
+
+public record Person(String firstName, String lastName, String SSN, String dateOfBirth) {
+};
+
diff --git a/core-java-modules/core-java-records/src/test/java/com/baeldung/equalshashcoderecords/CustomRecordEqualsHashCode.java b/core-java-modules/core-java-records/src/test/java/com/baeldung/equalshashcoderecords/CustomRecordEqualsHashCode.java
new file mode 100644
index 0000000000..074886304f
--- /dev/null
+++ b/core-java-modules/core-java-records/src/test/java/com/baeldung/equalshashcoderecords/CustomRecordEqualsHashCode.java
@@ -0,0 +1,30 @@
+package com.baeldung.equalshashcoderecords;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+import org.junit.Test;
+
+public class CustomRecordEqualsHashCode {
+ @Test
+ public void givenTwoRecords_whenDefaultEquals_thenCompareEquality() {
+ Person robert = new Person("Robert", "Frost", "HDHDB223", "2000-01-02");
+ Person mike = new Person("Mike", "Adams", "ABJDJ2883", "2001-01-02");
+ assertNotEquals(robert, mike);
+ }
+
+ @Test
+ public void givenTwoRecords_hashCodesShouldBeSame() {
+ Person robert = new Person("Robert", "Frost", "HDHDB223", "2000-01-02");
+ Person robertCopy = new Person("Robert", "Frost", "HDHDB223", "2000-01-02");
+ assertEquals(robert.hashCode(), robertCopy.hashCode());
+ }
+
+ @Test
+ public void givenTwoRecords_whenCustomImplementation_thenCompareEquality() {
+ Movie movie1 = new Movie("The Batman", 2022, "WB");
+ Movie movie2 = new Movie("The Batman", 2022, "Dreamworks");
+ assertEquals(movie1, movie2);
+ assertEquals(movie1.hashCode(), movie2.hashCode());
+ }
+}
diff --git a/core-java-modules/core-java-reflection-2/pom.xml b/core-java-modules/core-java-reflection-2/pom.xml
index ee3eeee734..c7a4981533 100644
--- a/core-java-modules/core-java-reflection-2/pom.xml
+++ b/core-java-modules/core-java-reflection-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-reflection-2
- 0.1.0-SNAPSHOT
core-java-reflection-2
jar
diff --git a/core-java-modules/core-java-reflection-private-constructor/README.md b/core-java-modules/core-java-reflection-private-constructor/README.md
new file mode 100644
index 0000000000..a3c9d00b0a
--- /dev/null
+++ b/core-java-modules/core-java-reflection-private-constructor/README.md
@@ -0,0 +1,10 @@
+### Relevant Articles:
+
+- [Reading the Value of ‘private’ Fields from a Different Class in Java](https://www.baeldung.com/java-reflection-read-private-field-value)
+- [Set Field Value With Reflection](https://www.baeldung.com/java-set-private-field-value)
+- [Checking If a Method is Static Using Reflection in Java](https://www.baeldung.com/java-check-method-is-static)
+- [Checking if a Java Class is ‘abstract’ Using Reflection](https://www.baeldung.com/java-reflection-is-class-abstract)
+- [Invoking a Private Method in Java](https://www.baeldung.com/java-call-private-method)
+- [Finding All Classes in a Java Package](https://www.baeldung.com/java-find-all-classes-in-package)
+- [Invoke a Static Method Using Java Reflection API](https://www.baeldung.com/java-invoke-static-method-reflection)
+- [What Is the JDK com.sun.proxy.$Proxy Class?](https://www.baeldung.com/jdk-com-sun-proxy)
diff --git a/core-java-modules/core-java-reflection-private-constructor/pom.xml b/core-java-modules/core-java-reflection-private-constructor/pom.xml
new file mode 100644
index 0000000000..aee7815e23
--- /dev/null
+++ b/core-java-modules/core-java-reflection-private-constructor/pom.xml
@@ -0,0 +1,59 @@
+
+
+ 4.0.0
+ core-java-reflection-private-constructor
+ core-java-reflection-private-constructor
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ org.springframework
+ spring-test
+ ${spring.version}
+ test
+
+
+ org.reflections
+ reflections
+ ${reflections.version}
+
+
+
+
+ core-java-reflection-private-constructor
+
+
+ src/main/resources
+ true
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ ${target.version}
+ -parameters
+
+
+
+
+
+
+ 0.9.12
+ 1.8
+ 1.8
+ 5.3.4
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-reflection-private-constructor/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java b/core-java-modules/core-java-reflection-private-constructor/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java
new file mode 100644
index 0000000000..24e7d435c7
--- /dev/null
+++ b/core-java-modules/core-java-reflection-private-constructor/src/main/java/com/baeldung/reflection/PrivateConstructorClass.java
@@ -0,0 +1,8 @@
+package com.baeldung.reflection;
+
+public class PrivateConstructorClass {
+
+ private PrivateConstructorClass() {
+ System.out.println("Used the private constructor!");
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-reflection-private-constructor/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java b/core-java-modules/core-java-reflection-private-constructor/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java
new file mode 100644
index 0000000000..cd1f48d720
--- /dev/null
+++ b/core-java-modules/core-java-reflection-private-constructor/src/test/java/com/baeldung/reflection/PrivateConstructorUnitTest.java
@@ -0,0 +1,17 @@
+package com.baeldung.reflection;
+
+import java.lang.reflect.Constructor;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class PrivateConstructorUnitTest {
+
+ @Test
+ public void whenConstructorIsPrivate_thenInstanceSuccess() throws Exception {
+ Constructor pcc = PrivateConstructorClass.class.getDeclaredConstructor();
+ pcc.setAccessible(true);
+ PrivateConstructorClass privateConstructorInstance = pcc.newInstance();
+ Assertions.assertTrue(privateConstructorInstance instanceof PrivateConstructorClass);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-reflection/README.md b/core-java-modules/core-java-reflection/README.md
index f68362611e..b823f43606 100644
--- a/core-java-modules/core-java-reflection/README.md
+++ b/core-java-modules/core-java-reflection/README.md
@@ -8,3 +8,4 @@
- [What Causes java.lang.reflect.InvocationTargetException?](https://www.baeldung.com/java-lang-reflect-invocationtargetexception)
- [How to Get a Name of a Method Being Executed?](http://www.baeldung.com/java-name-of-executing-method)
- [Getting Class Type From a String in Java](https://www.baeldung.com/java-get-class-object-from-string)
+- [Determine if a Class Implements an Interface in Java](https://www.baeldung.com/java-check-class-implements-interface)
diff --git a/core-java-modules/core-java-reflection/pom.xml b/core-java-modules/core-java-reflection/pom.xml
index 1706bf3c45..a836ee4a22 100644
--- a/core-java-modules/core-java-reflection/pom.xml
+++ b/core-java-modules/core-java-reflection/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-reflection
- 0.1.0-SNAPSHOT
core-java-reflection
jar
@@ -14,6 +13,19 @@
0.0.1-SNAPSHOT
+
+
+ org.reflections
+ reflections
+ ${reflections.version}
+
+
+ org.apache.commons
+ commons-lang3
+ ${commons-lang3.version}
+
+
+
core-java-reflection
@@ -39,6 +51,8 @@
1.8
1.8
+ 0.10.2
+ 3.12.0
\ No newline at end of file
diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/checkinterface/ChildClass1.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/checkinterface/ChildClass1.java
similarity index 100%
rename from core-java-modules/core-java-lang-5/src/main/java/com/baeldung/checkinterface/ChildClass1.java
rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/checkinterface/ChildClass1.java
diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/checkinterface/ChildClass2.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/checkinterface/ChildClass2.java
similarity index 100%
rename from core-java-modules/core-java-lang-5/src/main/java/com/baeldung/checkinterface/ChildClass2.java
rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/checkinterface/ChildClass2.java
diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/checkinterface/ChildInterface1.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/checkinterface/ChildInterface1.java
similarity index 100%
rename from core-java-modules/core-java-lang-5/src/main/java/com/baeldung/checkinterface/ChildInterface1.java
rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/checkinterface/ChildInterface1.java
diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/checkinterface/ChildInterface2.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/checkinterface/ChildInterface2.java
similarity index 100%
rename from core-java-modules/core-java-lang-5/src/main/java/com/baeldung/checkinterface/ChildInterface2.java
rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/checkinterface/ChildInterface2.java
diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/checkinterface/MasterClass.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/checkinterface/MasterClass.java
similarity index 100%
rename from core-java-modules/core-java-lang-5/src/main/java/com/baeldung/checkinterface/MasterClass.java
rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/checkinterface/MasterClass.java
diff --git a/core-java-modules/core-java-lang-5/src/main/java/com/baeldung/checkinterface/MasterInterface.java b/core-java-modules/core-java-reflection/src/main/java/com/baeldung/checkinterface/MasterInterface.java
similarity index 100%
rename from core-java-modules/core-java-lang-5/src/main/java/com/baeldung/checkinterface/MasterInterface.java
rename to core-java-modules/core-java-reflection/src/main/java/com/baeldung/checkinterface/MasterInterface.java
diff --git a/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/checkinterface/CheckInterfaceUnitTest.java b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/checkinterface/CheckInterfaceUnitTest.java
similarity index 97%
rename from core-java-modules/core-java-lang-5/src/test/java/com/baeldung/checkinterface/CheckInterfaceUnitTest.java
rename to core-java-modules/core-java-reflection/src/test/java/com/baeldung/checkinterface/CheckInterfaceUnitTest.java
index dcbbb7eb05..3a72cdf0db 100644
--- a/core-java-modules/core-java-lang-5/src/test/java/com/baeldung/checkinterface/CheckInterfaceUnitTest.java
+++ b/core-java-modules/core-java-reflection/src/test/java/com/baeldung/checkinterface/CheckInterfaceUnitTest.java
@@ -1,154 +1,154 @@
-package com.baeldung.checkinterface;
-
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.commons.lang3.ClassUtils;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-import org.reflections.ReflectionUtils;
-import org.reflections.Reflections;
-
-public class CheckInterfaceUnitTest {
-
- protected static Reflections reflections;
-
- @BeforeAll
- public static void initializeReflectionsLibrary() {
-
- reflections = new Reflections("com.baeldung.checkinterface");
- }
-
- @Test
- public void whenUsingReflectionGetInterfaces_thenDirectlyImplementedInterfaceIsFound() {
-
- ChildClass2 childClass2 = new ChildClass2();
- List> interfaces = Arrays.asList(childClass2.getClass().getInterfaces());
-
- assertEquals(1, interfaces.size());
- assertTrue(interfaces.contains(ChildInterface2.class));
- }
-
- @Test
- public void whenUsingReflectionGetInterfaces_thenParentInterfaceIsNotFound() {
-
- ChildClass2 childClass2 = new ChildClass2();
- List> interfaces = Arrays.asList(childClass2.getClass().getInterfaces());
-
- assertFalse(interfaces.contains(MasterInterface.class));
- }
-
- @Test
- public void whenUsingReflectionGetInterfacesRecursively_thenParentInterfaceIsFound() {
-
- Set> interfaces = getAllExtendedOrImplementedInterfacesRecursively(ChildClass2.class);
-
- assertTrue(interfaces.contains(ChildInterface2.class));
- assertTrue(interfaces.contains(MasterInterface.class));
- }
-
- @Test
- public void whenUsingReflectionIsAssignableFrom_thenDirectlyImplementedInterfaceIsFound() {
-
- ChildClass2 childClass2 = new ChildClass2();
-
- assertTrue(ChildInterface2.class.isAssignableFrom(childClass2.getClass()));
- }
-
- @Test
- public void whenUsingReflectionIsAssignableFrom_thenParentInterfaceIsFound() {
-
- ChildClass2 childClass2 = new ChildClass2();
-
- assertTrue(MasterInterface.class.isAssignableFrom(childClass2.getClass()));
- }
-
- @Test
- public void whenUsingReflectionIsInstance_thenDirectlyImplementedInterfaceIsFound() {
-
- ChildClass2 childClass2 = new ChildClass2();
-
- assertTrue(ChildInterface2.class.isInstance(childClass2));
- }
-
- @Test
- public void whenUsingReflectionIsInstance_thenParentInterfaceIsFound() {
-
- ChildClass2 childClass2 = new ChildClass2();
-
- assertTrue(MasterInterface.class.isInstance(childClass2));
- }
-
- @Test
- public void whenUsingReflectionInstanceOf_thenDirectlyImplementedInterfaceIsFound() {
-
- ChildClass2 childClass2 = new ChildClass2();
-
- assertTrue(childClass2 instanceof ChildInterface2);
- }
-
- @Test
- public void whenUsingReflectionInstanceOf_thenParentInterfaceIsFound() {
-
- ChildClass2 childClass2 = new ChildClass2();
-
- assertTrue(childClass2 instanceof MasterInterface);
- }
-
- @Test
- public void whenUsingCommons_thenDirectlyImplementedInterfaceIsFound() {
-
- ChildClass2 childClass2 = new ChildClass2();
- List> interfaces = ClassUtils.getAllInterfaces(childClass2.getClass());
-
- assertTrue(interfaces.contains(ChildInterface2.class));
- }
-
- @Test
- public void whenUsingCommons_thenParentInterfaceIsFound() {
-
- ChildClass2 childClass2 = new ChildClass2();
- List> interfaces = ClassUtils.getAllInterfaces(childClass2.getClass());
-
- assertTrue(interfaces.contains(MasterInterface.class));
- }
-
- @Test
- public void whenUsingReflections_thenDirectlyImplementedInterfaceIsFound() {
-
- ChildClass2 childClass2 = new ChildClass2();
- Set> interfaces = reflections.get(ReflectionUtils.Interfaces.of(childClass2.getClass()));
-
- assertTrue(interfaces.contains(ChildInterface2.class));
- }
-
- @Test
- public void whenUsingReflections_thenParentInterfaceIsFound() {
-
- ChildClass2 childClass2 = new ChildClass2();
- Set> interfaces = reflections.get(ReflectionUtils.Interfaces.of(childClass2.getClass()));
-
- assertTrue(interfaces.contains(MasterInterface.class));
- }
-
- static Set> getAllExtendedOrImplementedInterfacesRecursively(Class> clazz) {
-
- Set> res = new HashSet>();
- Class>[] interfaces = clazz.getInterfaces();
-
- if (interfaces.length > 0) {
- res.addAll(Arrays.asList(interfaces));
- for (Class> interfaze : interfaces) {
- res.addAll(getAllExtendedOrImplementedInterfacesRecursively(interfaze));
- }
- }
-
- return res;
- }
-}
+package com.baeldung.checkinterface;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.lang3.ClassUtils;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.reflections.ReflectionUtils;
+import org.reflections.Reflections;
+
+public class CheckInterfaceUnitTest {
+
+ protected static Reflections reflections;
+
+ @BeforeAll
+ public static void initializeReflectionsLibrary() {
+
+ reflections = new Reflections("com.baeldung.checkinterface");
+ }
+
+ @Test
+ public void whenUsingReflectionGetInterfaces_thenDirectlyImplementedInterfaceIsFound() {
+
+ ChildClass2 childClass2 = new ChildClass2();
+ List> interfaces = Arrays.asList(childClass2.getClass().getInterfaces());
+
+ assertEquals(1, interfaces.size());
+ assertTrue(interfaces.contains(ChildInterface2.class));
+ }
+
+ @Test
+ public void whenUsingReflectionGetInterfaces_thenParentInterfaceIsNotFound() {
+
+ ChildClass2 childClass2 = new ChildClass2();
+ List> interfaces = Arrays.asList(childClass2.getClass().getInterfaces());
+
+ assertFalse(interfaces.contains(MasterInterface.class));
+ }
+
+ @Test
+ public void whenUsingReflectionGetInterfacesRecursively_thenParentInterfaceIsFound() {
+
+ Set> interfaces = getAllExtendedOrImplementedInterfacesRecursively(ChildClass2.class);
+
+ assertTrue(interfaces.contains(ChildInterface2.class));
+ assertTrue(interfaces.contains(MasterInterface.class));
+ }
+
+ @Test
+ public void whenUsingReflectionIsAssignableFrom_thenDirectlyImplementedInterfaceIsFound() {
+
+ ChildClass2 childClass2 = new ChildClass2();
+
+ assertTrue(ChildInterface2.class.isAssignableFrom(childClass2.getClass()));
+ }
+
+ @Test
+ public void whenUsingReflectionIsAssignableFrom_thenParentInterfaceIsFound() {
+
+ ChildClass2 childClass2 = new ChildClass2();
+
+ assertTrue(MasterInterface.class.isAssignableFrom(childClass2.getClass()));
+ }
+
+ @Test
+ public void whenUsingReflectionIsInstance_thenDirectlyImplementedInterfaceIsFound() {
+
+ ChildClass2 childClass2 = new ChildClass2();
+
+ assertTrue(ChildInterface2.class.isInstance(childClass2));
+ }
+
+ @Test
+ public void whenUsingReflectionIsInstance_thenParentInterfaceIsFound() {
+
+ ChildClass2 childClass2 = new ChildClass2();
+
+ assertTrue(MasterInterface.class.isInstance(childClass2));
+ }
+
+ @Test
+ public void whenUsingReflectionInstanceOf_thenDirectlyImplementedInterfaceIsFound() {
+
+ ChildClass2 childClass2 = new ChildClass2();
+
+ assertTrue(childClass2 instanceof ChildInterface2);
+ }
+
+ @Test
+ public void whenUsingReflectionInstanceOf_thenParentInterfaceIsFound() {
+
+ ChildClass2 childClass2 = new ChildClass2();
+
+ assertTrue(childClass2 instanceof MasterInterface);
+ }
+
+ @Test
+ public void whenUsingCommons_thenDirectlyImplementedInterfaceIsFound() {
+
+ ChildClass2 childClass2 = new ChildClass2();
+ List> interfaces = ClassUtils.getAllInterfaces(childClass2.getClass());
+
+ assertTrue(interfaces.contains(ChildInterface2.class));
+ }
+
+ @Test
+ public void whenUsingCommons_thenParentInterfaceIsFound() {
+
+ ChildClass2 childClass2 = new ChildClass2();
+ List> interfaces = ClassUtils.getAllInterfaces(childClass2.getClass());
+
+ assertTrue(interfaces.contains(MasterInterface.class));
+ }
+
+ @Test
+ public void whenUsingReflections_thenDirectlyImplementedInterfaceIsFound() {
+
+ ChildClass2 childClass2 = new ChildClass2();
+ Set> interfaces = reflections.get(ReflectionUtils.Interfaces.of(childClass2.getClass()));
+
+ assertTrue(interfaces.contains(ChildInterface2.class));
+ }
+
+ @Test
+ public void whenUsingReflections_thenParentInterfaceIsFound() {
+
+ ChildClass2 childClass2 = new ChildClass2();
+ Set> interfaces = reflections.get(ReflectionUtils.Interfaces.of(childClass2.getClass()));
+
+ assertTrue(interfaces.contains(MasterInterface.class));
+ }
+
+ static Set> getAllExtendedOrImplementedInterfacesRecursively(Class> clazz) {
+
+ Set> res = new HashSet>();
+ Class>[] interfaces = clazz.getInterfaces();
+
+ if (interfaces.length > 0) {
+ res.addAll(Arrays.asList(interfaces));
+ for (Class> interfaze : interfaces) {
+ res.addAll(getAllExtendedOrImplementedInterfacesRecursively(interfaze));
+ }
+ }
+
+ return res;
+ }
+}
diff --git a/core-java-modules/core-java-regex-2/README.md b/core-java-modules/core-java-regex-2/README.md
index 453e2cc419..f733d7770a 100644
--- a/core-java-modules/core-java-regex-2/README.md
+++ b/core-java-modules/core-java-regex-2/README.md
@@ -5,4 +5,5 @@
- [Converting Camel Case and Title Case to Words in Java](https://www.baeldung.com/java-camel-case-title-case-to-words)
- [How to Use Regular Expressions to Replace Tokens in Strings in Java](https://www.baeldung.com/java-regex-token-replacement)
- [Creating a Java Array from Regular Expression Matches](https://www.baeldung.com/java-array-regex-matches)
+- [Getting the Text That Follows After the Regex Match in Java](https://www.baeldung.com/java-regex-text-after-match)
- More articles: [[<-- prev]](/core-java-modules/core-java-regex)
diff --git a/core-java-modules/core-java-regex-2/pom.xml b/core-java-modules/core-java-regex-2/pom.xml
index ae9385e63c..ddfba35cb2 100644
--- a/core-java-modules/core-java-regex-2/pom.xml
+++ b/core-java-modules/core-java-regex-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-regex-2
- 0.1.0-SNAPSHOT
core-java-regex-2
jar
diff --git a/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/aftermatch/GetTextAfterTheRegexMatchUnitTest.java b/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/aftermatch/GetTextAfterTheRegexMatchUnitTest.java
new file mode 100644
index 0000000000..04650a0c02
--- /dev/null
+++ b/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/aftermatch/GetTextAfterTheRegexMatchUnitTest.java
@@ -0,0 +1,83 @@
+package com.baeldung.regex.aftermatch;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class GetTextAfterTheRegexMatchUnitTest {
+ private static final String INPUT1 = "Some text, targetValue=Regex is cool";
+ private static final String INPUT2 = "Some text. targetValue=Java is cool. some other text";
+
+ @Test
+ void whenUsingSplit_thenGetExpectedString() {
+ String result1 = INPUT1.split("targetValue=")[1];
+ assertEquals("Regex is cool", result1);
+
+ String afterFirstSplit = INPUT2.split("targetValue=")[1];
+ assertEquals("Java is cool. some other text", afterFirstSplit);
+ String result2 = afterFirstSplit.split("[.]")[0];
+ assertEquals("Java is cool", result2);
+
+ // if use the dot as the regex for splitting, the result array is empty
+ String[] splitByDot = INPUT2.split("targetValue=")[1].split(".");
+ assertEquals(0, splitByDot.length);
+ }
+
+ @Test
+ void whenUsingReplaceAll_thenGetExpectedString() {
+ String result1 = INPUT1.replaceAll(".*targetValue=", "");
+ assertEquals("Regex is cool", result1);
+
+ String afterFirstReplace = INPUT2.replaceAll(".*targetValue=", "");
+ assertEquals("Java is cool. some other text", afterFirstReplace);
+ String result2 = afterFirstReplace.replaceAll("[.].*", "");
+ assertEquals("Java is cool", result2);
+
+ }
+
+ @Test
+ void whenUsingRegexGrouping_thenGetExpectedString() {
+ Pattern p1 = Pattern.compile("targetValue=(.*)");
+ Matcher m1 = p1.matcher(INPUT1);
+ assertTrue(m1.find());
+ String result1 = m1.group(1);
+ assertEquals("Regex is cool", result1);
+
+ Pattern p2 = Pattern.compile("targetValue=([^.]*)");
+ Matcher m2 = p2.matcher(INPUT2);
+ assertTrue(m2.find());
+ String result2 = m2.group(1);
+ assertEquals("Java is cool", result2);
+
+ Pattern p3 = Pattern.compile("targetValue=(.*?)[.]");
+ Matcher m3 = p3.matcher(INPUT2);
+ assertTrue(m3.find());
+ String result3 = m3.group(1);
+ assertEquals("Java is cool", result3);
+ }
+
+ @Test
+ void whenUsingLookaround_thenGetExpectedString() {
+ Pattern p1 = Pattern.compile("(?<=targetValue=).*");
+ Matcher m1 = p1.matcher(INPUT1);
+ assertTrue(m1.find());
+ String result1 = m1.group();
+ assertEquals("Regex is cool", result1);
+
+ Pattern p2 = Pattern.compile("(?<=targetValue=)[^.]*");
+ Matcher m2 = p2.matcher(INPUT2);
+ assertTrue(m2.find());
+ String result2 = m2.group();
+ assertEquals("Java is cool", result2);
+
+ Pattern p3 = Pattern.compile("(?<=targetValue=).*(?=[.])");
+ Matcher m3 = p3.matcher(INPUT2);
+ assertTrue(m3.find());
+ String result3 = m3.group();
+ assertEquals("Java is cool", result3);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/z_regexp/ZRegularExpressionUnitTest.java b/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/z_regexp/ZRegularExpressionUnitTest.java
new file mode 100644
index 0000000000..90bbbb6540
--- /dev/null
+++ b/core-java-modules/core-java-regex-2/src/test/java/com/baeldung/regex/z_regexp/ZRegularExpressionUnitTest.java
@@ -0,0 +1,35 @@
+package com.baeldung.regex.z_regexp;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class ZRegularExpressionUnitTest {
+ @Test
+ public void givenCreditCardNumber_thenReturnIfMatched() {
+ String creditCardNumber = "1234567890123456";
+ String pattern = "\\d{16}\\z";
+ Assertions.assertTrue(creditCardNumber.matches(pattern));
+ }
+
+ @Test
+ public void givenLogOutput_thenReturnIfMatched() {
+ String logLine = "2022-05-01 14:30:00,123 INFO Some log message";
+ String pattern = ".*message\\z";
+ Assertions.assertTrue(logLine.matches(pattern));
+ }
+
+ @Test
+ public void givenEmailMessage_thenReturnIfMatched() {
+ String myMessage = "Hello HR, I hope i can write to Baeldung\n";
+ String pattern = ".*Baeldung\\s*\\Z";
+ Assertions.assertTrue(myMessage.matches(pattern));
+ }
+
+ @Test
+ public void givenFileExtension_thenReturnIfMatched() {
+ String fileName = "image.jpeg";
+ String pattern = ".*\\.jpeg\\Z";
+ Assertions.assertTrue(fileName.matches(pattern));
+ }
+
+}
diff --git a/core-java-modules/core-java-regex/pom.xml b/core-java-modules/core-java-regex/pom.xml
index 93f3ae3cdb..00b8107c57 100644
--- a/core-java-modules/core-java-regex/pom.xml
+++ b/core-java-modules/core-java-regex/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-regex
- 0.1.0-SNAPSHOT
core-java-regex
jar
diff --git a/core-java-modules/core-java-security-2/pom.xml b/core-java-modules/core-java-security-2/pom.xml
index 7a354ee9e2..0fc121c070 100644
--- a/core-java-modules/core-java-security-2/pom.xml
+++ b/core-java-modules/core-java-security-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-security-2
- 0.1.0-SNAPSHOT
core-java-security-2
jar
diff --git a/core-java-modules/core-java-security-3/pom.xml b/core-java-modules/core-java-security-3/pom.xml
index 3cd546e697..fef8b53289 100644
--- a/core-java-modules/core-java-security-3/pom.xml
+++ b/core-java-modules/core-java-security-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-security-3
- 0.1.0-SNAPSHOT
core-java-security-3
jar
diff --git a/core-java-modules/core-java/src/main/resources/META-INF/BenchmarkList b/core-java-modules/core-java-security-algorithms/classpath
similarity index 100%
rename from core-java-modules/core-java/src/main/resources/META-INF/BenchmarkList
rename to core-java-modules/core-java-security-algorithms/classpath
diff --git a/core-java-modules/core-java-security-algorithms/pom.xml b/core-java-modules/core-java-security-algorithms/pom.xml
index 967ddc103e..0dde9f861a 100644
--- a/core-java-modules/core-java-security-algorithms/pom.xml
+++ b/core-java-modules/core-java-security-algorithms/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-security-algorithms
- 0.1.0-SNAPSHOT
core-java-security-algorithms
jar
@@ -25,7 +24,6 @@
bcprov-jdk15on
${bouncycastle.version}
-
javax.xml.bind
jaxb-api
diff --git a/core-java-modules/core-java-security/pom.xml b/core-java-modules/core-java-security/pom.xml
index b36de5ac4c..921017b080 100644
--- a/core-java-modules/core-java-security/pom.xml
+++ b/core-java-modules/core-java-security/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-security
- 0.1.0-SNAPSHOT
core-java-security
jar
diff --git a/core-java-modules/core-java-serialization/pom.xml b/core-java-modules/core-java-serialization/pom.xml
index c82ae9d1d6..04144fb27f 100644
--- a/core-java-modules/core-java-serialization/pom.xml
+++ b/core-java-modules/core-java-serialization/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-serialization
- 0.1.0-SNAPSHOT
core-java-serialization
jar
diff --git a/core-java-modules/core-java-streams-2/pom.xml b/core-java-modules/core-java-streams-2/pom.xml
index c8fa83c55a..9725497b04 100644
--- a/core-java-modules/core-java-streams-2/pom.xml
+++ b/core-java-modules/core-java-streams-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-streams-2
- 1.0
core-java-streams-2
jar
diff --git a/core-java-modules/core-java-streams-3/pom.xml b/core-java-modules/core-java-streams-3/pom.xml
index 3074a647ff..9c657119b5 100644
--- a/core-java-modules/core-java-streams-3/pom.xml
+++ b/core-java-modules/core-java-streams-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-streams-3
- 0.1.0-SNAPSHOT
core-java-streams-3
jar
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/flatmap/map/Java8MapAndFlatMapUnitTest.java
similarity index 94%
rename from core-java-modules/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java
rename to core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/flatmap/map/Java8MapAndFlatMapUnitTest.java
index a0bd1cf093..1b09ea25c6 100644
--- a/core-java-modules/core-java/src/test/java/com/baeldung/java8/Java8MapAndFlatMap.java
+++ b/core-java-modules/core-java-streams-3/src/test/java/com/baeldung/streams/flatmap/map/Java8MapAndFlatMapUnitTest.java
@@ -1,4 +1,4 @@
-package com.baeldung.java8;
+package com.baeldung.streams.flatmap.map;
import org.junit.Test;
@@ -12,7 +12,7 @@ import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
-public class Java8MapAndFlatMap {
+public class Java8MapAndFlatMapUnitTest {
@Test
public void givenStream_whenCalledMap_thenProduceList() {
diff --git a/core-java-modules/core-java-streams-4/README.md b/core-java-modules/core-java-streams-4/README.md
index 67b16ac153..c6717ec5fe 100644
--- a/core-java-modules/core-java-streams-4/README.md
+++ b/core-java-modules/core-java-streams-4/README.md
@@ -9,3 +9,4 @@
- [Stream to Iterable in Java](https://www.baeldung.com/java-stream-to-iterable)
- [Understanding the Difference Between Stream.of() and IntStream.range()](https://www.baeldung.com/java-stream-of-and-intstream-range)
- [Check if Object Is an Array in Java](https://www.baeldung.com/java-check-if-object-is-an-array)
+- [Mapping an Array of Integers to Strings Using Java Streams](https://www.baeldung.com/java-stream-integer-array-to-strings)
diff --git a/core-java-modules/core-java-streams-4/pom.xml b/core-java-modules/core-java-streams-4/pom.xml
index 46c0f3f7e1..fe791ebd42 100644
--- a/core-java-modules/core-java-streams-4/pom.xml
+++ b/core-java-modules/core-java-streams-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-streams-4
- 0.1.0-SNAPSHOT
core-java-streams-4
jar
diff --git a/core-java-modules/core-java-streams-5/README.md b/core-java-modules/core-java-streams-5/README.md
new file mode 100644
index 0000000000..4f367799f2
--- /dev/null
+++ b/core-java-modules/core-java-streams-5/README.md
@@ -0,0 +1 @@
+- [Difference Between parallelStream() and stream().parallel() in Java](https://www.baeldung.com/java-parallelstream-vs-stream-parallel)
diff --git a/core-java-modules/core-java-streams-5/pom.xml b/core-java-modules/core-java-streams-5/pom.xml
new file mode 100644
index 0000000000..d1f8af6461
--- /dev/null
+++ b/core-java-modules/core-java-streams-5/pom.xml
@@ -0,0 +1,72 @@
+
+
+ 4.0.0
+ core-java-streams-5
+ core-java-streams-5
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ log4j
+ log4j
+ ${log4j.version}
+
+
+ org.junit
+ junit-bom
+ ${junit-jupiter.version}
+ pom
+ import
+
+
+ org.assertj
+ assertj-core
+ 3.23.1
+ test
+
+
+ org.apache.commons
+ commons-lang3
+ 3.12.0
+ test
+
+
+
+
+ core-java-streams-4
+
+
+ ../core-java-streams-4/src/main
+ true
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ ${maven.compiler.target}
+ -parameters
+
+
+
+
+
+
+
+ 3.1
+ 12
+ 12
+
+
+
\ No newline at end of file
diff --git a/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/Book.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/Book.java
new file mode 100644
index 0000000000..d52a31aac9
--- /dev/null
+++ b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/Book.java
@@ -0,0 +1,37 @@
+package com.baeldung.streams.parallelstream;
+
+public class Book {
+ private String name;
+ private String author;
+ private int yearPublished;
+
+ public Book(String name, String author, int yearPublished) {
+ this.name = name;
+ this.author = author;
+ this.yearPublished = yearPublished;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getAuthor() {
+ return author;
+ }
+
+ public void setAuthor(String author) {
+ this.author = author;
+ }
+
+ public int getYearPublished() {
+ return yearPublished;
+ }
+
+ public void setYearPublished(int yearPublished) {
+ this.yearPublished = yearPublished;
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/BookSpliterator.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/BookSpliterator.java
new file mode 100644
index 0000000000..7460e1372b
--- /dev/null
+++ b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/BookSpliterator.java
@@ -0,0 +1,40 @@
+package com.baeldung.streams.parallelstream;
+
+import java.util.Spliterator;
+import java.util.function.Consumer;
+
+public class BookSpliterator implements Spliterator {
+ private final Object[] books;
+ private int startIndex;
+ public BookSpliterator(Object[] books, int startIndex) {
+ this.books = books;
+ this.startIndex = startIndex;
+ }
+
+ @Override
+ public Spliterator trySplit() {
+ // Always Assuming that the source is too small to split, returning null
+ return null;
+ }
+
+ // Other overridden methods such as tryAdvance(), estimateSize() etc
+
+ @Override
+ public boolean tryAdvance(Consumer super T> action) {
+ if (startIndex < books.length) {
+ startIndex += 2;
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public long estimateSize() {
+ return books.length - startIndex;
+ }
+
+ @Override
+ public int characteristics() {
+ return CONCURRENT;
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/MyBookContainer.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/MyBookContainer.java
new file mode 100644
index 0000000000..d7e3adc5f1
--- /dev/null
+++ b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/MyBookContainer.java
@@ -0,0 +1,93 @@
+package com.baeldung.streams.parallelstream;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Spliterator;
+import java.util.stream.Stream;
+import java.util.stream.StreamSupport;
+
+public class MyBookContainer implements Collection {
+ private static final long serialVersionUID = 1L;
+ private T[] elements;
+
+ public MyBookContainer(T[] elements) {
+ this.elements = elements;
+ }
+
+ @Override
+ public Spliterator spliterator() {
+ return new BookSpliterator(elements, 0);
+ }
+
+ @Override
+ public Stream parallelStream() {
+ return StreamSupport.stream(spliterator(), false);
+ }
+
+ // standard overridden methods of Collection Interface
+
+ @Override
+ public int size() {
+ return elements.length;
+ }
+
+ @Override
+ public boolean isEmpty() {
+ return elements.length == 0;
+ }
+
+ @Override
+ public boolean contains(Object o) {
+ return false;
+ }
+
+ @Override
+ public Iterator iterator() {
+ return null;
+ }
+
+ @Override
+ public Object[] toArray() {
+ return new Object[0];
+ }
+
+ @Override
+ public T1[] toArray(T1[] a) {
+ return null;
+ }
+
+ @Override
+ public boolean add(T t) {
+ return false;
+ }
+
+ @Override
+ public boolean remove(Object o) {
+ return false;
+ }
+
+ @Override
+ public boolean containsAll(Collection> c) {
+ return false;
+ }
+
+ @Override
+ public boolean addAll(Collection extends T> c) {
+ return false;
+ }
+
+ @Override
+ public boolean removeAll(Collection> c) {
+ return false;
+ }
+
+ @Override
+ public boolean retainAll(Collection> c) {
+ return false;
+ }
+
+ @Override
+ public void clear() {
+
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/ParallelStreamApplication.java b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/ParallelStreamApplication.java
new file mode 100644
index 0000000000..4297bdd3ed
--- /dev/null
+++ b/core-java-modules/core-java-streams-5/src/main/java/com/baeldung/streams/parallelstream/ParallelStreamApplication.java
@@ -0,0 +1,41 @@
+package com.baeldung.streams.parallelstream;
+
+import java.util.Collection;
+import java.util.concurrent.atomic.AtomicLong;
+
+public class ParallelStreamApplication {
+
+ public long usingCollectionsParallel(Collection listOfbooks, int year) {
+ AtomicLong countOfBooks = new AtomicLong();
+ listOfbooks.parallelStream()
+ .forEach(book -> {
+ if (book.getYearPublished() == year) {
+ countOfBooks.getAndIncrement();
+ }
+ });
+ return countOfBooks.get();
+ }
+
+ public long usingStreamParallel(Collection listOfBooks, int year) {
+ AtomicLong countOfBooks = new AtomicLong();
+ listOfBooks.stream()
+ .parallel()
+ .forEach(book -> {
+ if (book.getYearPublished() == year) {
+ countOfBooks.getAndIncrement();
+ }
+ });
+ return countOfBooks.get();
+ }
+
+ public long usingWithCustomSpliterator(MyBookContainer listOfBooks, int year) {
+ AtomicLong countOfBooks = new AtomicLong();
+ listOfBooks.parallelStream()
+ .forEach(book -> {
+ if (book.getYearPublished() == year) {
+ countOfBooks.getAndIncrement();
+ }
+ });
+ return countOfBooks.get();
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/parallelstream/ParallelStreamUnitTest.java b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/parallelstream/ParallelStreamUnitTest.java
new file mode 100644
index 0000000000..af8172a10d
--- /dev/null
+++ b/core-java-modules/core-java-streams-5/src/test/java/com/baeldung/parallelstream/ParallelStreamUnitTest.java
@@ -0,0 +1,46 @@
+package com.baeldung.parallelstream;
+
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.baeldung.streams.parallelstream.Book;
+import com.baeldung.streams.parallelstream.MyBookContainer;
+import com.baeldung.streams.parallelstream.ParallelStreamApplication;
+
+public class ParallelStreamUnitTest {
+
+ @Test
+ public void givenCollectionWhenCollectionsParallelIsUsedThenReturnCount() {
+ ParallelStreamApplication parallelStreamApplication = new ParallelStreamApplication();
+ Assert.assertEquals(parallelStreamApplication.usingCollectionsParallel(generateListOfBooks(), 1974), 2);
+ }
+
+ @Test
+ public void givenCollectionWhenStreamParallelIsUsedThenReturnCount() {
+ ParallelStreamApplication parallelStreamApplication = new ParallelStreamApplication();
+ Assert.assertEquals(parallelStreamApplication.usingStreamParallel(generateListOfBooks(), 1974), 2);
+ }
+
+ @Test
+ public void givenBookContainerWhenParallelStreamIsUsedThenReturnIncorrectCount() {
+ ParallelStreamApplication parallelStreamApplication = new ParallelStreamApplication();
+ Assert.assertNotEquals(parallelStreamApplication.usingWithCustomSpliterator(getBookContainer(), 1974), 2);
+ }
+
+ private List generateListOfBooks() {
+ Book book1 = new Book("The Blue Umbrella", "Ruskin Bond", 1974);
+ Book book2 = new Book("Carrie", "Stephen King", 1974);
+ Book book3 = new Book("The Psychology of money", "Morgan Housel", 2020);
+ List books = List.of(book1, book2, book3);
+ return books;
+ }
+
+ private MyBookContainer getBookContainer() {
+ MyBookContainer listOfBooks = new MyBookContainer<>(new Book[] { new Book("The Blue Umbrella", "Ruskin Bond", 1974),
+ new Book("Carrie", "Stephen King", 1974),
+ new Book("The Psychology of money", "Morgan Housel", 2020)});
+ return listOfBooks;
+ }
+}
diff --git a/core-java-modules/core-java-streams-collect/README.md b/core-java-modules/core-java-streams-collect/README.md
new file mode 100644
index 0000000000..b6659a8ef7
--- /dev/null
+++ b/core-java-modules/core-java-streams-collect/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles:
+- [Can Stream.collect() Return the null Value?](https://www.baeldung.com/stream-collect-returning-null)
diff --git a/core-java-modules/core-java-streams-collect/pom.xml b/core-java-modules/core-java-streams-collect/pom.xml
new file mode 100644
index 0000000000..e81598017c
--- /dev/null
+++ b/core-java-modules/core-java-streams-collect/pom.xml
@@ -0,0 +1,41 @@
+
+
+ 4.0.0
+ core-java-streams-4
+ core-java-streams-collect
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ log4j
+ log4j
+ ${log4j.version}
+
+
+ org.junit
+ junit-bom
+ ${junit-jupiter.version}
+ pom
+ import
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+
+
+ 3.23.1
+
+
+
diff --git a/core-java-modules/core-java-streams-collect/src/test/java/com/baeldung/collect/nullable/CanCollectReturnNullUnitTest.java b/core-java-modules/core-java-streams-collect/src/test/java/com/baeldung/collect/nullable/CanCollectReturnNullUnitTest.java
new file mode 100644
index 0000000000..cf02f1d5ea
--- /dev/null
+++ b/core-java-modules/core-java-streams-collect/src/test/java/com/baeldung/collect/nullable/CanCollectReturnNullUnitTest.java
@@ -0,0 +1,92 @@
+package com.baeldung.collect.nullable;
+
+import static java.util.stream.Collectors.collectingAndThen;
+import static java.util.stream.Collectors.groupingBy;
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.Collectors.toMap;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Collector;
+
+import org.junit.jupiter.api.Test;
+
+public class CanCollectReturnNullUnitTest {
+ private final List LANGUAGES = Arrays.asList("Kotlin", null, null, "Java", "Python", "Rust");
+
+ @Test
+ void givenAStreamWithNullElements_whenCollect_shouldReturnNotNull() {
+ List result = LANGUAGES.stream()
+ .filter(Objects::isNull)
+ .collect(toList());
+ assertNotNull(result);
+ assertEquals(Arrays.asList(null, null), result);
+ }
+
+ @Test
+ void givenAStreamWithNullElements_whenCollectEmptyStream_shouldReturnNotNull() {
+ List result = LANGUAGES.stream()
+ .filter(s -> s != null && s.length() == 1)
+ .collect(toList());
+ assertNotNull(result);
+ assertTrue(result.isEmpty());
+
+ Map result2 = LANGUAGES.stream()
+ .filter(s -> s != null && s.length() == 1)
+ .collect(toMap(s -> s.charAt(0), Function.identity()));
+ assertNotNull(result2);
+ assertTrue(result2.isEmpty());
+
+ Map> result3 = LANGUAGES.stream()
+ .filter(s -> s != null && s.length() == 1)
+ .collect(groupingBy(s -> s.charAt(0)));
+ assertNotNull(result3);
+ assertTrue(result3.isEmpty());
+ }
+
+ @Test
+ void givenAStream_whenCollectByEmptyToNullCollector_shouldReturnExpectedResults() {
+ Collector, ArrayList> emptyListToNullCollector = Collector.of(ArrayList::new, ArrayList::add, (a, b) -> {
+ a.addAll(b);
+ return a;
+ }, a -> a.isEmpty() ? null : a);
+
+ List notNullResult = LANGUAGES.stream()
+ .filter(Objects::isNull)
+ .collect(emptyListToNullCollector);
+ assertNotNull(notNullResult);
+ assertEquals(Arrays.asList(null, null), notNullResult);
+
+ List nullResult = LANGUAGES.stream()
+ .filter(s -> s != null && s.length() == 1)
+ .collect(emptyListToNullCollector);
+ assertNull(nullResult);
+ }
+
+ @Test
+ void givenAStream_whenCollectByCollectingAndThen_shouldReturnExpectedResults() {
+ List notNullResult = LANGUAGES.stream()
+ .filter(Objects::nonNull)
+ .collect(collectingAndThen(toList(), Collections::unmodifiableList));
+ assertNotNull(notNullResult);
+ assertEquals(Arrays.asList("Kotlin", "Java", "Python", "Rust"), notNullResult);
+
+ //the result list becomes immutable
+ assertThrows(UnsupportedOperationException.class, () -> notNullResult.add("Oops"));
+
+ List nullResult = LANGUAGES.stream()
+ .filter(s -> s != null && s.length() == 1)
+ .collect(collectingAndThen(toList(), strings -> strings.isEmpty() ? null : strings));
+ assertNull(nullResult);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-streams-maps/README.md b/core-java-modules/core-java-streams-maps/README.md
new file mode 100644
index 0000000000..f9f7dffad9
--- /dev/null
+++ b/core-java-modules/core-java-streams-maps/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles:
+- [Handle Duplicate Keys When Producing Map Using Java Stream](https://www.baeldung.com/java-duplicate-keys-when-producing-map-using-stream)
diff --git a/core-java-modules/core-java-streams-maps/pom.xml b/core-java-modules/core-java-streams-maps/pom.xml
new file mode 100644
index 0000000000..66e1fedd87
--- /dev/null
+++ b/core-java-modules/core-java-streams-maps/pom.xml
@@ -0,0 +1,66 @@
+
+
+ 4.0.0
+ core-java-streams-maps
+ core-java-streams-maps
+ jar
+
+
+ com.baeldung.core-java-modules
+ core-java-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ log4j
+ log4j
+ ${log4j.version}
+
+
+ org.junit
+ junit-bom
+ ${junit-jupiter.version}
+ pom
+ import
+
+
+ org.assertj
+ assertj-core
+ 3.23.1
+ test
+
+
+
+
+ core-java-streams-maps
+
+
+ src/main
+ true
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ ${maven.compiler.target}
+ -parameters
+
+
+
+
+
+
+
+ 3.1
+ 1.8
+ 1.8
+
+
+
diff --git a/core-java-modules/core-java-streams-maps/src/test/java/com/baeldung/streams/tomap/StreamToMapDuplicatedKeysHandlingUnitTest.java b/core-java-modules/core-java-streams-maps/src/test/java/com/baeldung/streams/tomap/StreamToMapDuplicatedKeysHandlingUnitTest.java
new file mode 100644
index 0000000000..7da8a16062
--- /dev/null
+++ b/core-java-modules/core-java-streams-maps/src/test/java/com/baeldung/streams/tomap/StreamToMapDuplicatedKeysHandlingUnitTest.java
@@ -0,0 +1,97 @@
+package com.baeldung.streams.tomap;
+
+import static java.util.stream.Collectors.groupingBy;
+import static java.util.stream.Collectors.toMap;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.function.Function;
+
+import org.junit.jupiter.api.Test;
+
+class City {
+ private String name;
+ private String locatedIn;
+
+ public City(String name, String locatedIn) {
+ this.name = name;
+ this.locatedIn = locatedIn;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getLocatedIn() {
+ return locatedIn;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (!(o instanceof City))
+ return false;
+
+ City city = (City) o;
+
+ if (!name.equals(city.name))
+ return false;
+ return locatedIn.equals(city.locatedIn);
+ }
+
+ @Override
+ public int hashCode() {
+ int result = name.hashCode();
+ result = 31 * result + locatedIn.hashCode();
+ return result;
+ }
+}
+
+public class StreamToMapDuplicatedKeysHandlingUnitTest {
+ // @formatter:off
+ private final List CITY_INPUT = Arrays.asList(
+ new City("New York City", "USA"),
+ new City("Shanghai", "China"),
+ new City("Hamburg", "Germany"),
+ new City("Paris", "France"),
+ new City("Paris", "Texas, USA"));
+ // @formatter:on
+
+ @Test
+ void givenCityList_whenUsingGroupingBy_shouldContainExpectedCity() {
+ Map> resultMap = CITY_INPUT.stream()
+ .collect(groupingBy(City::getName));
+ assertEquals(4, resultMap.size());
+ // @formatter:off
+ assertEquals(Arrays.asList(
+ new City("Paris", "France"),
+ new City("Paris", "Texas, USA")), resultMap.get("Paris"));
+ // @formatter:on
+
+ }
+
+ @Test
+ void givenCityList_whenContainingDuplicatedNamesUsingToMap_shouldContainExpectedCity() {
+ Map resultMap1 = CITY_INPUT.stream()
+ .collect(toMap(City::getName, Function.identity(), (first, second) -> first));
+ assertEquals(4, resultMap1.size());
+ assertEquals(new City("Paris", "France"), resultMap1.get("Paris"));
+
+ Map resultMap2 = CITY_INPUT.stream()
+ .collect(toMap(City::getName, Function.identity(), (first, second) -> second));
+ assertEquals(4, resultMap2.size());
+ assertEquals(new City("Paris", "Texas, USA"), resultMap2.get("Paris"));
+
+ Map resultMap3 = CITY_INPUT.stream()
+ .collect(toMap(City::getName, Function.identity(), (first, second) -> {
+ String locations = first.getLocatedIn() + " and " + second.getLocatedIn();
+ return new City(first.getName(), locations);
+ }));
+ assertEquals(4, resultMap2.size());
+ assertEquals(new City("Paris", "France and Texas, USA"), resultMap3.get("Paris"));
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-streams/pom.xml b/core-java-modules/core-java-streams/pom.xml
index a6bb827e77..b0794829c2 100644
--- a/core-java-modules/core-java-streams/pom.xml
+++ b/core-java-modules/core-java-streams/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-streams
- 0.1.0-SNAPSHOT
core-java-streams
jar
@@ -15,7 +14,6 @@
-
org.openjdk.jmh
jmh-core
diff --git a/core-java-modules/core-java-string-algorithms-2/pom.xml b/core-java-modules/core-java-string-algorithms-2/pom.xml
index 5af187abc2..3fdb022a4b 100644
--- a/core-java-modules/core-java-string-algorithms-2/pom.xml
+++ b/core-java-modules/core-java-string-algorithms-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-algorithms-2
- 0.1.0-SNAPSHOT
core-java-string-algorithms-2
jar
diff --git a/core-java-modules/core-java-string-algorithms-3/README.md b/core-java-modules/core-java-string-algorithms-3/README.md
index d2863be8e5..c9e7e7d7d4 100644
--- a/core-java-modules/core-java-string-algorithms-3/README.md
+++ b/core-java-modules/core-java-string-algorithms-3/README.md
@@ -10,3 +10,4 @@ This module contains articles about string-related algorithms.
- [Check if the First Letter of a String is Uppercase](https://www.baeldung.com/java-check-first-letter-uppercase)
- [Find the First Non Repeating Character in a String in Java](https://www.baeldung.com/java-find-the-first-non-repeating-character)
- [Find the First Embedded Occurrence of an Integer in a Java String](https://www.baeldung.com/java-string-find-embedded-integer)
+- [Find the Most Frequent Characters in a String](https://www.baeldung.com/java-string-find-most-frequent-characters)
diff --git a/core-java-modules/core-java-string-algorithms-3/pom.xml b/core-java-modules/core-java-string-algorithms-3/pom.xml
index 147ea22375..7d4adeba92 100644
--- a/core-java-modules/core-java-string-algorithms-3/pom.xml
+++ b/core-java-modules/core-java-string-algorithms-3/pom.xml
@@ -3,7 +3,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-algorithms-3
- 0.1.0-SNAPSHOT
core-java-string-algorithms-3
jar
@@ -40,8 +39,8 @@
maven-compiler-plugin
${maven-compiler-plugin.version}
-
- ${java.version}
+
+ ${maven.compiler.target}
-parameters
diff --git a/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/charfreq/CharacterWithHighestFrequency.java b/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/charfreq/CharacterWithHighestFrequency.java
new file mode 100644
index 0000000000..938ad1edf3
--- /dev/null
+++ b/core-java-modules/core-java-string-algorithms-3/src/main/java/com/baeldung/charfreq/CharacterWithHighestFrequency.java
@@ -0,0 +1,58 @@
+package com.baeldung.charfreq;
+
+import static java.util.Map.Entry.comparingByValue;
+import static java.util.stream.Collectors.counting;
+import static java.util.stream.Collectors.groupingBy;
+import static java.util.stream.Collectors.toSet;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+public class CharacterWithHighestFrequency {
+ public static Character byStream(String input) {
+ return input.chars()
+ .mapToObj(x -> (char) x)
+ .collect(groupingBy(x -> x, counting()))
+ .entrySet()
+ .stream()
+ .max(comparingByValue())
+ .get()
+ .getKey();
+ }
+
+ public static Set byMap(String input) {
+ Map map = new HashMap<>();
+ for (char c : input.toCharArray()) {
+ map.compute(c, (character, count) -> count == null ? 1 : ++count);
+ }
+ int maxCount = map.values()
+ .stream()
+ .mapToInt(Integer::intValue)
+ .max()
+ .getAsInt();
+
+ return map.keySet()
+ .stream()
+ .filter(c -> map.get(c) == maxCount)
+ .collect(toSet());
+ }
+
+ public static Set byBucket(String input) {
+ int[] buckets = new int[128];
+
+ int maxCount = 0;
+ for (char c : input.toCharArray()) {
+ buckets[c]++;
+ maxCount = Math.max(buckets[c], maxCount);
+ }
+
+ int finalMaxCount = maxCount;
+ return IntStream.range(0, 128)
+ .filter(c -> buckets[c] == finalMaxCount)
+ .mapToObj(i -> (char) i)
+ .collect(Collectors.toSet());
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/charfreq/CharacterWithHighestFrequencyUnitTest.java b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/charfreq/CharacterWithHighestFrequencyUnitTest.java
new file mode 100644
index 0000000000..978752f3d4
--- /dev/null
+++ b/core-java-modules/core-java-string-algorithms-3/src/test/java/com/baeldung/charfreq/CharacterWithHighestFrequencyUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.charfreq;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Collections;
+import java.util.Set;
+
+import org.junit.jupiter.api.Test;
+
+import com.google.common.collect.ImmutableSet;
+
+class CharacterWithHighestFrequencyUnitTest {
+ private static final String INPUT1 = "aaaaaaaaaa(10) bbbbbbb ccccc dddd eee ff";
+ private static final Set EXPECTED1 = Collections.singleton('a');
+
+ private static final String INPUT2 = "YYYYYYY(7) bbbbb -------(7) dddd eee kkkkkkk(7) ff";
+ private static final Set EXPECTED2 = ImmutableSet.of('Y', '-', 'k');
+
+ @Test
+ void whenGettingSingleCharWithHighestFrequencyByStream_shouldSuccess() {
+ char result1 = CharacterWithHighestFrequency.byStream(INPUT1);
+ assertEquals('a', result1);
+ }
+
+ @Test
+ void whenGettingCharWithHighestFrequencyByMap_shouldSuccess() {
+ Set result1 = CharacterWithHighestFrequency.byMap(INPUT1);
+ assertEquals(EXPECTED1, result1);
+
+ Set result2 = CharacterWithHighestFrequency.byMap(INPUT2);
+ assertEquals(EXPECTED2, result2);
+
+ }
+
+ @Test
+ void whenGettingCharWithHighestFrequencyByBucket_shouldSuccess() {
+ Set result1 = CharacterWithHighestFrequency.byBucket(INPUT1);
+ assertEquals(EXPECTED1, result1);
+
+ Set result2 = CharacterWithHighestFrequency.byBucket(INPUT2);
+ assertEquals(EXPECTED2, result2);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-algorithms/pom.xml b/core-java-modules/core-java-string-algorithms/pom.xml
index 84f3b61f84..10d28feb2f 100644
--- a/core-java-modules/core-java-string-algorithms/pom.xml
+++ b/core-java-modules/core-java-string-algorithms/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-algorithms
- 0.1.0-SNAPSHOT
core-java-string-algorithms
jar
diff --git a/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java
index 5236f14ccd..07663ab7d1 100644
--- a/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java
+++ b/core-java-modules/core-java-string-algorithms/src/main/java/com/baeldung/reverse/ReverseStringExamples.java
@@ -1,5 +1,9 @@
package com.baeldung.reverse;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+
import org.apache.commons.lang3.StringUtils;
public class ReverseStringExamples {
@@ -46,11 +50,43 @@ public class ReverseStringExamples {
}
return output.toString()
- .trim();
+ .trim();
}
public static String reverseTheOrderOfWordsUsingApacheCommons(String sentence) {
return StringUtils.reverseDelimited(sentence, ' ');
}
+ public static String reverseUsingIntStreamRangeMethod(String str) {
+ if (str == null) {
+ return null;
+ }
+
+ char[] charArray = str.toCharArray();
+ return IntStream.range(0, str.length())
+ .mapToObj(i -> charArray[str.length() - i - 1])
+ .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
+ .toString();
+ }
+
+ public static String reverseUsingStreamOfMethod(String str) {
+ if (str == null) {
+ return null;
+ }
+
+ return Stream.of(str)
+ .map(string -> new StringBuilder(string).reverse())
+ .collect(Collectors.joining());
+ }
+
+ public static String reverseUsingCharsMethod(String str) {
+ if (str == null) {
+ return null;
+ }
+
+ return str.chars()
+ .mapToObj(c -> (char) c)
+ .reduce("", (a, b) -> b + a, (a2, b2) -> b2 + a2);
+ }
+
}
diff --git a/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/reverse/ReverseStringExamplesUnitTest.java b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/reverse/ReverseStringExamplesUnitTest.java
index c122163174..b3685a49da 100644
--- a/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/reverse/ReverseStringExamplesUnitTest.java
+++ b/core-java-modules/core-java-string-algorithms/src/test/java/com/baeldung/reverse/ReverseStringExamplesUnitTest.java
@@ -1,10 +1,11 @@
package com.baeldung.reverse;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-
public class ReverseStringExamplesUnitTest {
private static final String STRING_INPUT = "cat";
@@ -19,7 +20,7 @@ public class ReverseStringExamplesUnitTest {
String reversedEmpty = ReverseStringExamples.reverse(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
- assertEquals(null, reversedNull);
+ assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@@ -30,7 +31,7 @@ public class ReverseStringExamplesUnitTest {
String reversedEmpty = ReverseStringExamples.reverseUsingStringBuilder(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
- assertEquals(null, reversedNull);
+ assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@@ -41,7 +42,7 @@ public class ReverseStringExamplesUnitTest {
String reversedEmpty = ReverseStringExamples.reverseUsingApacheCommons(StringUtils.EMPTY);
assertEquals(STRING_INPUT_REVERSED, reversed);
- assertEquals(null, reversedNull);
+ assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@@ -52,7 +53,7 @@ public class ReverseStringExamplesUnitTest {
String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWords(StringUtils.EMPTY);
assertEquals(REVERSED_WORDS_SENTENCE, reversed);
- assertEquals(null, reversedNull);
+ assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
@@ -63,7 +64,40 @@ public class ReverseStringExamplesUnitTest {
String reversedEmpty = ReverseStringExamples.reverseTheOrderOfWordsUsingApacheCommons(StringUtils.EMPTY);
assertEquals(REVERSED_WORDS_SENTENCE, reversed);
- assertEquals(null, reversedNull);
+ assertNull(reversedNull);
+ assertEquals(StringUtils.EMPTY, reversedEmpty);
+ }
+
+ @Test
+ public void whenReverseStringUsingIntStreamRangeMethod_ThenCorrectStringIsReturned() {
+ String reversed = ReverseStringExamples.reverseUsingIntStreamRangeMethod(STRING_INPUT);
+ String reversedNull = ReverseStringExamples.reverseUsingIntStreamRangeMethod(null);
+ String reversedEmpty = ReverseStringExamples.reverseUsingIntStreamRangeMethod(StringUtils.EMPTY);
+
+ assertEquals(STRING_INPUT_REVERSED, reversed);
+ assertNull(reversedNull);
+ assertEquals(StringUtils.EMPTY, reversedEmpty);
+ }
+
+ @Test
+ public void whenReverseStringUsingCharsMethod_ThenCorrectStringIsReturned() {
+ String reversed = ReverseStringExamples.reverseUsingCharsMethod(STRING_INPUT);
+ String reversedNull = ReverseStringExamples.reverseUsingCharsMethod(null);
+ String reversedEmpty = ReverseStringExamples.reverseUsingCharsMethod(StringUtils.EMPTY);
+
+ assertEquals(STRING_INPUT_REVERSED, reversed);
+ assertNull(reversedNull);
+ assertEquals(StringUtils.EMPTY, reversedEmpty);
+ }
+
+ @Test
+ public void whenReverseStringUsingStreamOfMethod_ThenCorrectStringIsReturned() {
+ String reversed = ReverseStringExamples.reverseUsingStreamOfMethod(STRING_INPUT);
+ String reversedNull = ReverseStringExamples.reverseUsingStreamOfMethod(null);
+ String reversedEmpty = ReverseStringExamples.reverseUsingStreamOfMethod(StringUtils.EMPTY);
+
+ assertEquals(STRING_INPUT_REVERSED, reversed);
+ assertNull(reversedNull);
assertEquals(StringUtils.EMPTY, reversedEmpty);
}
diff --git a/core-java-modules/core-java-string-apis-2/pom.xml b/core-java-modules/core-java-string-apis-2/pom.xml
index ba983d7593..db97b85748 100644
--- a/core-java-modules/core-java-string-apis-2/pom.xml
+++ b/core-java-modules/core-java-string-apis-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-apis-2
- 0.0.1-SNAPSHOT
core-java-string-apis-2
jar
diff --git a/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/nullandempty/NullAndEmptyStringUnitTest.java b/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/nullandempty/NullAndEmptyStringUnitTest.java
new file mode 100644
index 0000000000..332a16fd84
--- /dev/null
+++ b/core-java-modules/core-java-string-apis-2/src/test/java/com/baeldung/nullandempty/NullAndEmptyStringUnitTest.java
@@ -0,0 +1,27 @@
+package com.baeldung.nullandempty;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+
+import org.junit.jupiter.api.Test;
+
+public class NullAndEmptyStringUnitTest {
+
+ @Test
+ void givenANullAndEmptyString_whenUsingStringMethods_thenShouldGetExpectedResult() {
+ String nullString = null;
+ String emptyString = "";
+ assertTrue(emptyString.equals(""));
+ assertThrows(NullPointerException.class, () -> nullString.length());
+ }
+
+ @Test
+ void givenANullAndEmptyString_whenCheckingEquality_thenShouldGetExpectedResult() {
+ String nullString = null;
+ String emptyString = "";
+ assertFalse(emptyString.equals(nullString));
+ assertFalse(emptyString == nullString);
+ }
+
+}
diff --git a/core-java-modules/core-java-string-apis/pom.xml b/core-java-modules/core-java-string-apis/pom.xml
index 6a382c3c57..5d7737228c 100644
--- a/core-java-modules/core-java-string-apis/pom.xml
+++ b/core-java-modules/core-java-string-apis/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-apis
- 0.1.0-SNAPSHOT
core-java-string-apis
jar
diff --git a/core-java-modules/core-java-string-conversions-2/pom.xml b/core-java-modules/core-java-string-conversions-2/pom.xml
index e424ef3083..90463271b8 100644
--- a/core-java-modules/core-java-string-conversions-2/pom.xml
+++ b/core-java-modules/core-java-string-conversions-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-conversions-2
- 0.1.0-SNAPSHOT
core-java-string-conversions-2
jar
diff --git a/core-java-modules/core-java-string-conversions/pom.xml b/core-java-modules/core-java-string-conversions/pom.xml
index f10ae401b3..b87431cd0b 100644
--- a/core-java-modules/core-java-string-conversions/pom.xml
+++ b/core-java-modules/core-java-string-conversions/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-conversions
- 0.1.0-SNAPSHOT
core-java-string-conversions
jar
@@ -44,6 +43,7 @@
61.1
+ -Djava.locale.providers=COMPAT
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-conversions/src/main/java/com/baeldung/stringtoint/StringToIntConverter.java b/core-java-modules/core-java-string-conversions/src/main/java/com/baeldung/stringtoint/StringToIntConverter.java
new file mode 100644
index 0000000000..03d77c2aea
--- /dev/null
+++ b/core-java-modules/core-java-string-conversions/src/main/java/com/baeldung/stringtoint/StringToIntConverter.java
@@ -0,0 +1,52 @@
+package com.baeldung.stringtoint;
+
+import java.util.Optional;
+import org.apache.commons.lang3.math.NumberUtils;
+
+public class StringToIntConverter {
+
+ private StringToIntConverter() {
+ }
+
+ public static Integer convertStringToIntUsingIntegerParseInt(String input){
+ try {
+ return Integer.parseInt(input);
+ } catch (NumberFormatException e) {
+ // log or handle the error
+ return Integer.MIN_VALUE;
+ }
+ }
+
+ public static Integer convertStringToIntUsingIntegerValueOf(String input){
+ try {
+ return Integer.valueOf(input);
+ } catch (NumberFormatException e) {
+ // log or handle the error
+ return Integer.MIN_VALUE;
+ }
+ }
+
+ public static Integer convertStringToIntUsingIntegerDecode(String input){
+ try {
+ return Integer.decode(input);
+ } catch (Exception e) {
+ // log or handle the error
+ return Integer.MIN_VALUE;
+ }
+ }
+
+ public static Integer convertStringToIntUsingOptional(String input){
+ Optional parsedInt;
+ try {
+ parsedInt = Optional.of(Integer.parseInt(input));
+ } catch (Exception e) {
+ // log or handle the error
+ parsedInt = Optional.empty();
+ }
+ return parsedInt.orElse(Integer.MIN_VALUE);
+ }
+
+ public static int convertStringToIntUsingNumberUtils(String input){
+ return NumberUtils.toInt(input, Integer.MIN_VALUE);
+ }
+}
diff --git a/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/datetostring/DateToStringFormatterUnitTest.java b/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/datetostring/DateToStringFormatterUnitTest.java
index 221900fb0e..c4fb84713c 100644
--- a/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/datetostring/DateToStringFormatterUnitTest.java
+++ b/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/datetostring/DateToStringFormatterUnitTest.java
@@ -1,7 +1,6 @@
package com.baeldung.datetostring;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
@@ -14,7 +13,8 @@ import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
-import static org.junit.Assert.assertEquals;
+import org.junit.BeforeClass;
+import org.junit.Test;
public class DateToStringFormatterUnitTest {
diff --git a/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/stringtoint/StringToIntConverterUnitTest.java b/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/stringtoint/StringToIntConverterUnitTest.java
new file mode 100644
index 0000000000..2bfb4db161
--- /dev/null
+++ b/core-java-modules/core-java-string-conversions/src/test/java/com/baeldung/stringtoint/StringToIntConverterUnitTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.stringtoint;
+
+import java.util.Arrays;
+import java.util.List;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class StringToIntConverterUnitTest {
+
+ @Test
+ void whenConvertingIntToString_thenInvalidCasesReturnIntegerMinValue() {
+ List testData = Arrays.asList(
+ new TestData("", Integer.MIN_VALUE),
+ new TestData(null, Integer.MIN_VALUE),
+ new TestData("23,56", Integer.MIN_VALUE),
+ new TestData("2147483648", Integer.MIN_VALUE),
+ new TestData("-2147483649", Integer.MIN_VALUE),
+ new TestData("hello", Integer.MIN_VALUE)
+ );
+ testData.forEach(data -> {
+ Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingIntegerParseInt(data.input));
+ Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingIntegerValueOf(data.input));
+ Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingOptional(data.input));
+ Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingIntegerDecode(data.input));
+ Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingNumberUtils(data.input));
+ });
+ }
+
+ @Test
+ void whenConvertingIntToString_thenValidCasesReturnUnboxedInt() {
+ List testData = Arrays.asList(
+ new TestData("23", 23),
+ new TestData("-23", -23)
+ );
+ testData.forEach(data -> {
+ Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingIntegerParseInt(data.input));
+ Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingIntegerValueOf(data.input));
+ Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingOptional(data.input));
+ Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingNumberUtils(data.input));
+ Assertions.assertEquals(data.expectedOutput, StringToIntConverter.convertStringToIntUsingIntegerDecode(data.input));
+ });
+ }
+
+ public static class TestData{
+ String input;
+ Integer expectedOutput;
+
+ TestData(String input, Integer expectedOutput){
+ this.input = input;
+ this.expectedOutput = expectedOutput;
+ }
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-operations-2/pom.xml b/core-java-modules/core-java-string-operations-2/pom.xml
index 92bfa6b2d8..c6debc4f71 100644
--- a/core-java-modules/core-java-string-operations-2/pom.xml
+++ b/core-java-modules/core-java-string-operations-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-operations-2
- 0.1.0-SNAPSHOT
core-java-string-operations-2
jar
diff --git a/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/encoding/CharacterEncodingExamples.java b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/encoding/CharacterEncodingExamples.java
index 1ed5f9e62a..11cda28ffe 100644
--- a/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/encoding/CharacterEncodingExamples.java
+++ b/core-java-modules/core-java-string-operations-2/src/main/java/com/baeldung/encoding/CharacterEncodingExamples.java
@@ -40,6 +40,6 @@ public class CharacterEncodingExamples {
charsetDecoder.onMalformedInput(codingErrorAction);
return new BufferedReader(
new InputStreamReader(
- new ByteArrayInputStream(input.getBytes()), charsetDecoder)).readLine();
+ new ByteArrayInputStream(input.getBytes(charset)), charsetDecoder)).readLine();
}
}
diff --git a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encoding/CharacterEncodingExamplesUnitTest.java b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encoding/CharacterEncodingExamplesUnitTest.java
index 273839de1f..752f2e1e19 100644
--- a/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encoding/CharacterEncodingExamplesUnitTest.java
+++ b/core-java-modules/core-java-string-operations-2/src/test/java/com/baeldung/encoding/CharacterEncodingExamplesUnitTest.java
@@ -75,7 +75,7 @@ public class CharacterEncodingExamplesUnitTest {
@Test
public void givenUTF8String_whenDecodeByUS_ASCII_thenIgnoreMalformedInputSequence() throws IOException {
- Assertions.assertEquals("The faade pattern is a software design pattern.", CharacterEncodingExamples.decodeText("The façade pattern is a software design pattern.", StandardCharsets.US_ASCII, CodingErrorAction.IGNORE));
+ Assertions.assertEquals("The fa?ade pattern is a software design pattern.", CharacterEncodingExamples.decodeText("The façade pattern is a software design pattern.", StandardCharsets.US_ASCII, CodingErrorAction.IGNORE));
}
//@Test
@@ -89,7 +89,8 @@ public class CharacterEncodingExamplesUnitTest {
CodingErrorAction.REPLACE));
}
- @Test
+ //@Test
+ // run this manually as it's dependent on platform encoding
public void givenUTF8String_whenDecodeByUS_ASCII_thenReportMalformedInputSequence() {
Assertions.assertThrows(
MalformedInputException.class,
diff --git a/core-java-modules/core-java-string-operations-3/pom.xml b/core-java-modules/core-java-string-operations-3/pom.xml
index 19b3d57ffd..39167271fa 100644
--- a/core-java-modules/core-java-string-operations-3/pom.xml
+++ b/core-java-modules/core-java-string-operations-3/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-operations-3
- 0.1.0-SNAPSHOT
core-java-string-operations-3
jar
diff --git a/core-java-modules/core-java-string-operations-4/pom.xml b/core-java-modules/core-java-string-operations-4/pom.xml
index 0f1e377d18..cc755cf470 100644
--- a/core-java-modules/core-java-string-operations-4/pom.xml
+++ b/core-java-modules/core-java-string-operations-4/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-operations-4
- 0.1.0-SNAPSHOT
core-java-string-operations-4
jar
diff --git a/core-java-modules/core-java-string-operations-5/README.md b/core-java-modules/core-java-string-operations-5/README.md
index 94fb7e855e..3a09c8a585 100644
--- a/core-java-modules/core-java-string-operations-5/README.md
+++ b/core-java-modules/core-java-string-operations-5/README.md
@@ -8,3 +8,7 @@
- [Convert String to String Array](https://www.baeldung.com/java-convert-string-to-string-array)
- [String Interpolation in Java](https://www.baeldung.com/java-string-interpolation)
- [Guide to Splitting a String by Whitespace in Java](https://www.baeldung.com/java-splitting-a-string-by-whitespace)
+- [Check if the First Letter of a String Is a Number](https://www.baeldung.com/java-check-if-string-starts-with-number)
+- [Print “” Quotes Around a String in Java](https://www.baeldung.com/java-string-print-quotes)
+- [Remove Punctuation From a String in Java](https://www.baeldung.com/java-remove-punctuation-from-string)
+- [Find the Longest Word in a Given String in Java](https://www.baeldung.com/java-longest-word-string)
diff --git a/core-java-modules/core-java-string-operations-5/pom.xml b/core-java-modules/core-java-string-operations-5/pom.xml
index efb32c73b9..2a2a353984 100644
--- a/core-java-modules/core-java-string-operations-5/pom.xml
+++ b/core-java-modules/core-java-string-operations-5/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-operations-5
- 0.1.0-SNAPSHOT
core-java-string-operations-5
jar
diff --git a/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/firstchardigit/FirstCharDigit.java b/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/firstchardigit/FirstCharDigit.java
new file mode 100644
index 0000000000..a43127af1a
--- /dev/null
+++ b/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/firstchardigit/FirstCharDigit.java
@@ -0,0 +1,62 @@
+package com.baeldung.firstchardigit;
+
+import java.util.regex.Pattern;
+
+import com.google.common.base.CharMatcher;
+
+public class FirstCharDigit {
+
+ public static boolean checkUsingCharAtMethod(String str) {
+ if (str == null || str.length() == 0) {
+ return false;
+ }
+
+ char c = str.charAt(0);
+ return c >= '0' && c <= '9';
+ }
+
+ public static boolean checkUsingIsDigitMethod(String str) {
+ if (str == null || str.length() == 0) {
+ return false;
+ }
+
+ return Character.isDigit(str.charAt(0));
+ }
+
+ public static boolean checkUsingPatternClass(String str) {
+ if (str == null || str.length() == 0) {
+ return false;
+ }
+
+ return Pattern.compile("^[0-9].*")
+ .matcher(str)
+ .matches();
+ }
+
+ public static boolean checkUsingMatchesMethod(String str) {
+ if (str == null || str.length() == 0) {
+ return false;
+ }
+
+ return str.matches("^[0-9].*");
+ }
+
+ public static boolean checkUsingCharMatcherInRangeMethod(String str) {
+ if (str == null || str.length() == 0) {
+ return false;
+ }
+
+ return CharMatcher.inRange('0', '9')
+ .matches(str.charAt(0));
+ }
+
+ public static boolean checkUsingCharMatcherForPredicateMethod(String str) {
+ if (str == null || str.length() == 0) {
+ return false;
+ }
+
+ return CharMatcher.forPredicate(Character::isDigit)
+ .matches(str.charAt(0));
+ }
+
+}
diff --git a/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/longestword/LongestWordFinder.java b/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/longestword/LongestWordFinder.java
new file mode 100644
index 0000000000..770984ac29
--- /dev/null
+++ b/core-java-modules/core-java-string-operations-5/src/main/java/com/baeldung/longestword/LongestWordFinder.java
@@ -0,0 +1,36 @@
+package com.baeldung.longestword;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+public class LongestWordFinder {
+
+ public Optional findLongestWord(String sentence) {
+ return Optional.ofNullable(sentence)
+ .filter(string -> !string.trim()
+ .isEmpty())
+ .map(string -> string.split("\\s"))
+ .map(Arrays::asList)
+ .map(list -> Collections.max(list, Comparator.comparingInt(String::length)));
+ }
+
+ public List findLongestWords(String sentence) {
+ if (sentence == null || sentence.trim()
+ .isEmpty()) {
+ return Collections.emptyList();
+ }
+ String[] words = sentence.split("\\s");
+ int maxWordLength = Arrays.stream(words)
+ .mapToInt(String::length)
+ .max()
+ .orElseThrow();
+ return Arrays.stream(words)
+ .filter(word -> word.length() == maxWordLength)
+ .collect(Collectors.toList());
+ }
+
+}
diff --git a/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/delpunctuation/RemovePunctuationUnitTest.java b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/delpunctuation/RemovePunctuationUnitTest.java
new file mode 100644
index 0000000000..751ae0f4bc
--- /dev/null
+++ b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/delpunctuation/RemovePunctuationUnitTest.java
@@ -0,0 +1,43 @@
+package com.baeldung.delpunctuation;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+import org.junit.jupiter.api.Test;
+
+public class RemovePunctuationUnitTest {
+ private static final String INPUT = "Its 1 W o r d (!@#$%^&*{}[];':\")<>,.";
+ private static final String EXPECTED = "Its 1 W o r d ";
+
+ private static final String UNICODE_INPUT = "3 March März 三月 březen маршировать (!@#$%^&*{}[];':\")<>,.";
+ private static final String UNICODE_EXPECTED = "3 March März 三月 březen маршировать ";
+
+ @Test
+ void whenUsingCharClassRange_thenGetExceptedResult() {
+ String result = INPUT.replaceAll("[^\\sa-zA-Z0-9]", "");
+ assertEquals(EXPECTED, result);
+ }
+
+ @Test
+ void whenUsingPunctuationCharClass_thenGetExceptedResult() {
+ String result = INPUT.replaceAll("\\p{Punct}", "");
+ assertEquals(EXPECTED, result);
+ }
+
+ @Test
+ void whenInputContainsUnicodeChars_thenGetExceptedResult() {
+ String result1 = UNICODE_INPUT.replaceAll("[^\\sa-zA-Z0-9]", "");
+ assertNotEquals(UNICODE_EXPECTED, result1);
+
+ String actualResult1 = "3 March Mrz bezen ";
+ assertEquals(actualResult1, result1);
+
+
+ String result2 = UNICODE_INPUT.replaceAll("\\p{Punct}", "");
+ assertEquals(UNICODE_EXPECTED, result2);
+
+ String result3 = UNICODE_INPUT.replaceAll("[^\\s\\p{L}0-9]", "");
+ assertEquals(UNICODE_EXPECTED, result3);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/firstchardigit/FirstCharDigitUnitTest.java b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/firstchardigit/FirstCharDigitUnitTest.java
new file mode 100644
index 0000000000..0095ebcaf3
--- /dev/null
+++ b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/firstchardigit/FirstCharDigitUnitTest.java
@@ -0,0 +1,58 @@
+package com.baeldung.firstchardigit;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+
+class FirstCharDigitUnitTest {
+
+ @Test
+ void givenString_whenUsingCharAtMethod_thenSuccess() {
+ assertTrue(FirstCharDigit.checkUsingCharAtMethod("12 years"));
+ assertFalse(FirstCharDigit.checkUsingCharAtMethod("years"));
+ assertFalse(FirstCharDigit.checkUsingCharAtMethod(""));
+ assertFalse(FirstCharDigit.checkUsingCharAtMethod(null));
+ }
+
+ @Test
+ void givenString_whenUsingIsDigitMethod_thenSuccess() {
+ assertTrue(FirstCharDigit.checkUsingIsDigitMethod("10 cm"));
+ assertFalse(FirstCharDigit.checkUsingIsDigitMethod("cm"));
+ assertFalse(FirstCharDigit.checkUsingIsDigitMethod(""));
+ assertFalse(FirstCharDigit.checkUsingIsDigitMethod(null));
+ }
+
+ @Test
+ void givenString_whenUsingPatternClass_thenSuccess() {
+ assertTrue(FirstCharDigit.checkUsingPatternClass("1 kg"));
+ assertFalse(FirstCharDigit.checkUsingPatternClass("kg"));
+ assertFalse(FirstCharDigit.checkUsingPatternClass(""));
+ assertFalse(FirstCharDigit.checkUsingPatternClass(null));
+ }
+
+ @Test
+ void givenString_whenUsingMatchesMethod_thenSuccess() {
+ assertTrue(FirstCharDigit.checkUsingMatchesMethod("123"));
+ assertFalse(FirstCharDigit.checkUsingMatchesMethod("ABC"));
+ assertFalse(FirstCharDigit.checkUsingMatchesMethod(""));
+ assertFalse(FirstCharDigit.checkUsingMatchesMethod(null));
+ }
+
+ @Test
+ void givenString_whenUsingCharMatcherInRangeMethod_thenSuccess() {
+ assertTrue(FirstCharDigit.checkUsingCharMatcherInRangeMethod("2023"));
+ assertFalse(FirstCharDigit.checkUsingCharMatcherInRangeMethod("abc"));
+ assertFalse(FirstCharDigit.checkUsingCharMatcherInRangeMethod(""));
+ assertFalse(FirstCharDigit.checkUsingCharMatcherInRangeMethod(null));
+ }
+
+ @Test
+ void givenString_whenUsingCharMatcherForPredicateMethod_thenSuccess() {
+ assertTrue(FirstCharDigit.checkUsingCharMatcherForPredicateMethod("100"));
+ assertFalse(FirstCharDigit.checkUsingCharMatcherForPredicateMethod("abdo"));
+ assertFalse(FirstCharDigit.checkUsingCharMatcherForPredicateMethod(""));
+ assertFalse(FirstCharDigit.checkUsingCharMatcherForPredicateMethod(null));
+ }
+
+}
diff --git a/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/longestword/LongestWordFinderUnitTest.java b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/longestword/LongestWordFinderUnitTest.java
new file mode 100644
index 0000000000..9d5f82d493
--- /dev/null
+++ b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/longestword/LongestWordFinderUnitTest.java
@@ -0,0 +1,62 @@
+package com.baeldung.longestword;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+class LongestWordFinderUnitTest {
+
+ LongestWordFinder longestWordFinder = new LongestWordFinder();
+
+ @Test
+ void givenNull_whenFindLongestWord_thenEmpty() {
+ assertThat(longestWordFinder.findLongestWord(null)).isEmpty();
+ }
+
+ @Test
+ void givenEmptyString_whenFindLongestWord_thenEmpty() {
+ assertThat(longestWordFinder.findLongestWord("")).isEmpty();
+ }
+
+ @Test
+ void givenStringWithOnlySpaces_whenFindLongestWord_thenEmpty() {
+ assertThat(longestWordFinder.findLongestWord(" ")).isEmpty();
+ }
+
+ @Test
+ void givenAPhraseWithALongestWord_whenFindLongestWord_thenLongestWordOfThePhrase() {
+ assertThat(longestWordFinder.findLongestWord("This is a phrase with words")).hasValue("phrase");
+ }
+
+ @Test
+ void givenAPhraseWithVariousWordsOfMaxLength_whenFindLongestWord_thenAnyOfTheLongestsWordsOfThePhrase() {
+ assertThat(longestWordFinder.findLongestWord("Baeldung is another word of size eight in this sentence")
+ .get()).isIn("Baeldung", "sentence");
+ }
+
+ @Test
+ void givenNull_whenFindLongestWords_thenEmpty() {
+ assertThat(longestWordFinder.findLongestWords(null)).isEmpty();
+ }
+
+ @Test
+ void givenEmptyString_whenFindLongestWords_thenEmpty() {
+ assertThat(longestWordFinder.findLongestWords("")).isEmpty();
+ }
+
+ @Test
+ void givenStringWithOnlySpaces_whenFindLongestWords_thenEmpty() {
+ assertThat(longestWordFinder.findLongestWords(" ")).isEmpty();
+ }
+
+ @Test
+ void givenAPhraseWithALongestWord_whenFindLongestWords_thenLongestWordOfThePhrase() {
+ assertThat(longestWordFinder.findLongestWords("This is a phrase with words")).containsExactly("phrase");
+ }
+
+ @Test
+ void givenAPhraseWithVariousWordsOfMaxLength_whenFindLongestWords_thenAllLongestsWords() {
+ assertThat(longestWordFinder.findLongestWords("Baeldung is another word of size eight in this sentence")).containsExactly("Baeldung", "sentence");
+ }
+
+}
diff --git a/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/stringwithquotes/PrintQuotesAroundAStringUnitTest.java b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/stringwithquotes/PrintQuotesAroundAStringUnitTest.java
new file mode 100644
index 0000000000..fd4ade1ef3
--- /dev/null
+++ b/core-java-modules/core-java-string-operations-5/src/test/java/com/baeldung/stringwithquotes/PrintQuotesAroundAStringUnitTest.java
@@ -0,0 +1,60 @@
+package com.baeldung.stringwithquotes;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class PrintQuotesAroundAStringUnitTest {
+ private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
+ private final PrintStream originalOut = System.out;
+
+ @BeforeEach
+ void replaceOut() {
+ System.setOut(new PrintStream(outContent));
+ }
+
+ @AfterEach
+ void restoreOut() {
+ System.setOut(originalOut);
+ }
+
+ @Test
+ void whenWrappingAStringWithEscapedQuote_thenGetExpectedResult() {
+ String theySay = "All Java programmers are cute!";
+ String quoted = "\"" + theySay + "\"";
+
+ System.out.println(quoted);
+
+ //assertion
+ String expected = "\"All Java programmers are cute!\"\n";
+ assertEquals(expected, outContent.toString());
+ }
+
+ @Test
+ void whenCallingReplaceAll_thenGetExpectedResult() {
+ String theySay = "Can you write Java code?";
+ String quoted = theySay.replaceAll("^|$", "\"");
+
+ System.out.println(quoted);
+
+ //assertion
+ String expected = "\"Can you write Java code?\"\n";
+ assertEquals(expected, outContent.toString());
+ }
+
+ @Test
+ void whenWrappingAStringWithQuoteChar_thenGetExpectedResult() {
+ String weSay = "Yes, we can write beautiful Java codes!";
+ String quoted = '"' + weSay + '"';
+ System.out.println(quoted);
+
+ //assertion
+ String expected = "\"Yes, we can write beautiful Java codes!\"\n";
+ assertEquals(expected, outContent.toString());
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java-string-operations/pom.xml b/core-java-modules/core-java-string-operations/pom.xml
index 20e4df3ba3..577736a324 100644
--- a/core-java-modules/core-java-string-operations/pom.xml
+++ b/core-java-modules/core-java-string-operations/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-string-operations
- 0.1.0-SNAPSHOT
core-java-string-operations
jar
@@ -15,6 +14,11 @@
+
+ javax.xml.bind
+ jaxb-api
+ 2.4.0-b180725.0427
+
org.apache.commons
commons-lang3
diff --git a/core-java-modules/core-java-strings/README.md b/core-java-modules/core-java-strings/README.md
index 835e9ec582..84cf31e8bd 100644
--- a/core-java-modules/core-java-strings/README.md
+++ b/core-java-modules/core-java-strings/README.md
@@ -13,3 +13,4 @@ This module contains articles about strings in Java.
- [Java Multi-line String](https://www.baeldung.com/java-multiline-string)
- [Guide to Java String Pool](https://www.baeldung.com/java-string-pool)
- [Fixing “constant string too long” Build Error](https://www.baeldung.com/java-constant-string-too-long-error)
+- [Reuse StringBuilder for Efficiency](https://www.baeldung.com/java-reuse-stringbuilder-for-efficiency)
diff --git a/core-java-modules/core-java-strings/pom.xml b/core-java-modules/core-java-strings/pom.xml
index 2cc35dad5f..e3cdb3c666 100644
--- a/core-java-modules/core-java-strings/pom.xml
+++ b/core-java-modules/core-java-strings/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-strings
- 0.1.0-SNAPSHOT
core-java-strings
jar
diff --git a/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuilder/ReuseStringBuilderPerformance.java b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuilder/ReuseStringBuilderPerformance.java
new file mode 100644
index 0000000000..b403f859bc
--- /dev/null
+++ b/core-java-modules/core-java-strings/src/main/java/com/baeldung/stringbuilder/ReuseStringBuilderPerformance.java
@@ -0,0 +1,55 @@
+package com.baeldung.stringbuilder;
+
+import org.openjdk.jmh.annotations.*;
+import org.openjdk.jmh.runner.Runner;
+import org.openjdk.jmh.runner.options.Options;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+import java.util.concurrent.TimeUnit;
+
+@BenchmarkMode(Mode.SingleShotTime)
+@OutputTimeUnit(TimeUnit.MILLISECONDS)
+@Measurement(batchSize = 100000, iterations = 10)
+@Warmup(batchSize = 100000, iterations = 10)
+@State(Scope.Thread)
+public class ReuseStringBuilderPerformance {
+
+ @Benchmark
+ public void benchmarkStringBuilder() {
+ for (int i = 0; i < 100; i++) {
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.append("baeldung");
+ stringBuilder.toString();
+ }
+ }
+
+ @Benchmark
+ public void benchmarkStringBuilderReuseWithSetLength() {
+ StringBuilder stringBuilder = new StringBuilder();
+ for (int i = 0; i < 100; i++) {
+ stringBuilder.append("baeldung");
+ stringBuilder.toString();
+ stringBuilder.setLength(0);
+ }
+ }
+
+ @Benchmark()
+ public void benchmarkStringBuilderReuseWithDelete() {
+ StringBuilder stringBuilder = new StringBuilder();
+ for (int i = 0; i < 100; i++) {
+ stringBuilder.append("baeldung");
+ stringBuilder.toString();
+ stringBuilder.delete(0, stringBuilder.length());
+ }
+ }
+
+ public static void main(String[] args) throws Exception {
+ Options options = new OptionsBuilder()
+ .include(ReuseStringBuilderPerformance.class.getSimpleName()).threads(1)
+ .forks(1).shouldFailOnError(true)
+ .shouldDoGC(true)
+ .jvmArgs("-server").build();
+ new Runner(options).run();
+ }
+
+}
diff --git a/core-java-modules/core-java-sun/pom.xml b/core-java-modules/core-java-sun/pom.xml
index e959932235..c9427f66a3 100644
--- a/core-java-modules/core-java-sun/pom.xml
+++ b/core-java-modules/core-java-sun/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-sun
- 0.1.0-SNAPSHOT
core-java-sun
jar
diff --git a/core-java-modules/core-java-time-measurements/pom.xml b/core-java-modules/core-java-time-measurements/pom.xml
index ac5fb3a5e6..7b2bc31ebb 100644
--- a/core-java-modules/core-java-time-measurements/pom.xml
+++ b/core-java-modules/core-java-time-measurements/pom.xml
@@ -3,9 +3,7 @@
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.exception.numberformat
core-java-time-measurements
- 0.0.1-SNAPSHOT
core-java-time-measurements
jar
diff --git a/core-java-modules/core-java-uuid/README.md b/core-java-modules/core-java-uuid/README.md
index 0a77c36acd..bd7bd9d9da 100644
--- a/core-java-modules/core-java-uuid/README.md
+++ b/core-java-modules/core-java-uuid/README.md
@@ -4,3 +4,5 @@
- [Generating Alphanumeric UUID String in Java](https://www.baeldung.com/java-generate-alphanumeric-uuid)
- [Guide to UUID in Java](http://www.baeldung.com/java-uuid)
- [Validate UUID String in Java](https://www.baeldung.com/java-validate-uuid-string)
+- [Generate the Same UUID From a String in Java](https://www.baeldung.com/java-generate-same-uuid-from-string)
+- [Generating Time Based UUIDs](https://www.baeldung.com/java-generating-time-based-uuids)
diff --git a/core-java-modules/core-java-uuid/pom.xml b/core-java-modules/core-java-uuid/pom.xml
index 442a266dab..c0e93c1d32 100644
--- a/core-java-modules/core-java-uuid/pom.xml
+++ b/core-java-modules/core-java-uuid/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-uuid
- 0.1.0-SNAPSHOT
core-java-uuid
jar
diff --git a/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDFromStringUnitTest.java b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDFromStringUnitTest.java
new file mode 100644
index 0000000000..381d8715d5
--- /dev/null
+++ b/core-java-modules/core-java-uuid/src/test/java/com/baeldung/uuid/UUIDFromStringUnitTest.java
@@ -0,0 +1,62 @@
+package com.baeldung.uuid;
+
+import org.junit.jupiter.api.Test;
+
+import java.util.UUID;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+public class UUIDFromStringUnitTest {
+ @Test
+ void whenStringInUUIDFormat_thenFromStringWorks() {
+ String inputStr = "bbcc4621-d88f-4a94-ae2f-b38072bf5087";
+
+ UUID uuid = UUID.fromString(inputStr);
+ UUID uuid2 = UUID.fromString(inputStr);
+ UUID uuid3 = UUID.fromString(inputStr);
+
+ assertEquals(inputStr, uuid.toString());
+
+ assertEquals(uuid, uuid2);
+ assertEquals(uuid, uuid3);
+
+ }
+
+ @Test
+ void whenStringNotInUUIDFormat_thenFromStringRaisesException() {
+ String inputStr = "I am not a standard UUID representation.";
+ assertThrows(IllegalArgumentException.class, () -> UUID.fromString(inputStr));
+ }
+
+ @Test
+ void whenStringInFreeFormat_thenNameUUIDFromBytesWorks() {
+ String inputStr = "I am not a standard UUID representation.";
+
+ UUID uuid = UUID.nameUUIDFromBytes(inputStr.getBytes());
+ UUID uuid2 = UUID.nameUUIDFromBytes(inputStr.getBytes());
+ UUID uuid3 = UUID.nameUUIDFromBytes(inputStr.getBytes());
+
+ assertTrue(uuid != null);
+
+ assertEquals(uuid, uuid2);
+ assertEquals(uuid, uuid3);
+
+ assertEquals(3, uuid.version());
+ }
+
+ @Test
+ void whenStringInFreeFormat_thenGenerateVer5UUIDWorks() {
+ String inputStr = "I am not a standard UUID representation.";
+
+ UUID uuid = UUIDGenerator.generateType5UUID(inputStr);
+ UUID uuid2 = UUIDGenerator.generateType5UUID(inputStr);
+ UUID uuid3 = UUIDGenerator.generateType5UUID(inputStr);
+
+ assertEquals(5, uuid.version());
+
+ assertTrue(uuid != null);
+
+ assertEquals(uuid, uuid2);
+ assertEquals(uuid, uuid3);
+ }
+}
\ No newline at end of file
diff --git a/core-java-modules/core-java/.gitignore b/core-java-modules/core-java/.gitignore
deleted file mode 100644
index 374c8bf907..0000000000
--- a/core-java-modules/core-java/.gitignore
+++ /dev/null
@@ -1,25 +0,0 @@
-*.class
-
-0.*
-
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-.resourceCache
-
-# Packaged files #
-*.jar
-*.war
-*.ear
-
-# Files generated by integration tests
-backup-pom.xml
-/bin/
-/temp
-
-#IntelliJ specific
-.idea/
-*.iml
\ No newline at end of file
diff --git a/core-java-modules/core-java/README.md b/core-java-modules/core-java/README.md
deleted file mode 100644
index 6d9bbe03c2..0000000000
--- a/core-java-modules/core-java/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
-## Core Java Cookbooks and Examples
-
-### Relevant Articles:
-
-- [Getting Started with Java Properties](http://www.baeldung.com/java-properties)
-- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
-- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
-- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
-- [A Guide to the ResourceBundle](http://www.baeldung.com/java-resourcebundle)
-- [Merging java.util.Properties Objects](https://www.baeldung.com/java-merging-properties)
-- [Illegal Character Compilation Error](https://www.baeldung.com/java-illegal-character-error)
-- [Lambda Expression vs. Anonymous Inner Class](https://www.baeldung.com/java-lambdas-vs-anonymous-class)
-- [Difference Between Class.forName() and Class.forName().newInstance()](https://www.baeldung.com/java-class-forname-vs-class-forname-newinstance)
diff --git a/core-java-modules/core-java/customers.xml b/core-java-modules/core-java/customers.xml
deleted file mode 100644
index b52dc27633..0000000000
--- a/core-java-modules/core-java/customers.xml
+++ /dev/null
@@ -1,95 +0,0 @@
-
-
-
- SELECT * FROM customers
- 1008
-
- true
- 1000
- 0
- 2
-
-
-
- 0
- 0
- 0
- true
- ResultSet.TYPE_SCROLL_INSENSITIVE
- false
- customers
- jdbc:h2:mem:testdb
-
- com.sun.rowset.providers.RIOptimisticProvider
- Oracle Corporation
- 1.0
- 2
- 1
-
-
-
- 2
-
- 1
- false
- true
- false
- 0
- true
- true
- 11
- ID
- ID
- PUBLIC
- 10
- 0
- CUSTOMERS
- TESTDB
- 4
- INTEGER
-
-
- 2
- false
- true
- false
- 0
- true
- true
- 50
- NAME
- NAME
- PUBLIC
- 50
- 0
- CUSTOMERS
- TESTDB
- 12
- VARCHAR
-
-
-
-
- 1
- Customer1
-
-
- 2
- Customer2
-
-
- 3
- Customer3
-
-
- 4
- Customer4
-
-
- 5
- Customer5
-
-
-
diff --git a/core-java-modules/core-java/externalizable.txt b/core-java-modules/core-java/externalizable.txt
deleted file mode 100644
index ddd3e143a8..0000000000
Binary files a/core-java-modules/core-java/externalizable.txt and /dev/null differ
diff --git a/core-java-modules/core-java/pom.xml b/core-java-modules/core-java/pom.xml
deleted file mode 100644
index 87abe6c007..0000000000
--- a/core-java-modules/core-java/pom.xml
+++ /dev/null
@@ -1,199 +0,0 @@
-
-
- 4.0.0
- core-java
- 0.1.0-SNAPSHOT
- core-java
- jar
-
-
- com.baeldung.core-java-modules
- core-java-modules
- 0.0.1-SNAPSHOT
-
-
-
-
- org.unix4j
- unix4j-command
- ${unix4j.version}
-
-
- com.googlecode.grep4j
- grep4j
- ${grep4j.version}
-
-
-
-
- com.fasterxml.jackson.core
- jackson-databind
- ${jackson.version}
-
-
-
- log4j
- log4j
- ${log4j.version}
-
-
- org.slf4j
- log4j-over-slf4j
- ${org.slf4j.version}
-
-
- org.projectlombok
- lombok
- ${lombok.version}
- provided
-
-
- org.javamoney
- moneta
- ${javamoney.moneta.version}
-
-
- org.springframework
- spring-core
- ${spring.core.version}
-
-
- commons-io
- commons-io
- ${commons-io.version}
-
-
- com.google.gdata
- core
- ${gdata.version}
-
-
-
-
- core-java
-
-
- src/main/resources
- true
-
-
-
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
- copy-dependencies
- prepare-package
-
- copy-dependencies
-
-
- ${project.build.directory}/libs
-
-
-
-
-
- org.codehaus.mojo
- exec-maven-plugin
-
- java
- com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
-
- -Xmx300m
- -XX:+UseParallelGC
- -classpath
-
- com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
-
-
-
-
- org.apache.maven.plugins
- maven-javadoc-plugin
- ${maven-javadoc-plugin.version}
-
-
- ${target.version}
-
-
-
-
-
-
-
- integration
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
-
-
- integration-test
-
- test
-
-
-
- **/*ManualTest.java
-
-
- **/*IntegrationTest.java
- **/*IntTest.java
-
-
-
-
-
-
- json
-
-
-
-
- org.codehaus.mojo
- exec-maven-plugin
-
-
- run-benchmarks
-
- none
-
- exec
-
-
- test
- java
-
- -classpath
-
- org.openjdk.jmh.Main
- .*
-
-
-
-
-
-
-
-
-
-
-
-
- 0.4
- 1.8.7
-
- 1.1
- 3.0.0-M1
- 1.8
- 1.8
- 4.3.20.RELEASE
- 1.47.1
-
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java b/core-java-modules/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java
deleted file mode 100644
index 6c79e89717..0000000000
--- a/core-java-modules/core-java/src/main/java/com/baeldung/executable/ExecutableMavenJar.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.baeldung.executable;
-
-import javax.swing.JOptionPane;
-
-public class ExecutableMavenJar {
-
- public static void main(String[] args) {
- JOptionPane.showMessageDialog(null, "It worked!", "Executable Jar with Maven", 1);
- }
-
-}
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java b/core-java-modules/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java
deleted file mode 100644
index 7e6bb5d3b2..0000000000
--- a/core-java-modules/core-java/src/main/java/com/baeldung/filesystem/jndi/LookupFSJNDI.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.baeldung.filesystem.jndi;
-
-import java.io.File;
-import java.util.Hashtable;
-
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-
-public class LookupFSJNDI {
- private InitialContext ctx = null;
-
- public LookupFSJNDI() throws NamingException {
- super();
- init();
- }
-
- private void init() throws NamingException {
- Hashtable env = new Hashtable();
-
- env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
- // URI to namespace (actual directory)
- env.put(Context.PROVIDER_URL, "file:./src/test/resources");
-
- ctx = new InitialContext(env);
- }
-
- public InitialContext getCtx() {
- return ctx;
- }
-
- public File getFile(String fileName) {
- File file;
- try {
- file = (File) getCtx().lookup(fileName);
- } catch (NamingException e) {
- file = null;
- }
- return file;
- }
-
-}
diff --git a/core-java-modules/core-java/src/main/java/com/baeldung/jsonposturlconnection/PostJSONWithHttpURLConnection.java b/core-java-modules/core-java/src/main/java/com/baeldung/jsonposturlconnection/PostJSONWithHttpURLConnection.java
deleted file mode 100644
index b2469ac984..0000000000
--- a/core-java-modules/core-java/src/main/java/com/baeldung/jsonposturlconnection/PostJSONWithHttpURLConnection.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.baeldung.jsonposturlconnection;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.net.HttpURLConnection;
-import java.net.URL;
-
-public class PostJSONWithHttpURLConnection {
-
- public static void main (String []args) throws IOException{
- //Change the URL with any other publicly accessible POST resource, which accepts JSON request body
- URL url = new URL ("https://reqres.in/api/users");
-
- HttpURLConnection con = (HttpURLConnection)url.openConnection();
- con.setRequestMethod("POST");
-
- con.setRequestProperty("Content-Type", "application/json; utf-8");
- con.setRequestProperty("Accept", "application/json");
-
- con.setDoOutput(true);
-
- //JSON String need to be constructed for the specific resource.
- //We may construct complex JSON using any third-party JSON libraries such as jackson or org.json
- String jsonInputString = "{\"name\": \"Upendra\", \"job\": \"Programmer\"}";
-
- try(OutputStream os = con.getOutputStream()){
- byte[] input = jsonInputString.getBytes("utf-8");
- os.write(input, 0, input.length);
- }
-
- int code = con.getResponseCode();
- System.out.println(code);
-
- try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
- StringBuilder response = new StringBuilder();
- String responseLine = null;
- while ((responseLine = br.readLine()) != null) {
- response.append(responseLine.trim());
- }
- System.out.println(response.toString());
- }
- }
-
-}
diff --git a/core-java-modules/core-java/src/main/java/log4j.properties b/core-java-modules/core-java/src/main/java/log4j.properties
deleted file mode 100644
index 5fe42d854c..0000000000
--- a/core-java-modules/core-java/src/main/java/log4j.properties
+++ /dev/null
@@ -1,9 +0,0 @@
-# Set root logger level to DEBUG and its only appender to A1.
-log4j.rootLogger=DEBUG, A1
-
-# A1 is set to be a ConsoleAppender.
-log4j.appender.A1=org.apache.log4j.ConsoleAppender
-
-# A1 uses PatternLayout.
-log4j.appender.A1.layout=org.apache.log4j.PatternLayout
-log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
diff --git a/core-java-modules/core-java/src/main/resources/META-INF/MANIFEST.MF b/core-java-modules/core-java/src/main/resources/META-INF/MANIFEST.MF
deleted file mode 100644
index 988de3193d..0000000000
--- a/core-java-modules/core-java/src/main/resources/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,5 +0,0 @@
-Agent-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
-Can-Redefine-Classes: true
-Can-Retransform-Classes: true
-Premain-Class: com.baeldung.instrumentation.agent.MyInstrumentationAgent
-Main-Class: com.baeldung.instrumentation.application.Launcher
diff --git a/core-java-modules/core-java/src/main/resources/META-INF/persistence.xml b/core-java-modules/core-java/src/main/resources/META-INF/persistence.xml
deleted file mode 100644
index 3966afdcda..0000000000
--- a/core-java-modules/core-java/src/main/resources/META-INF/persistence.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/core-java-modules/core-java/src/main/resources/countries.properties b/core-java-modules/core-java/src/main/resources/countries.properties
deleted file mode 100644
index 50b5e85653..0000000000
--- a/core-java-modules/core-java/src/main/resources/countries.properties
+++ /dev/null
@@ -1,3 +0,0 @@
-UK
-US
-Germany
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/resources/datasource.properties b/core-java-modules/core-java/src/main/resources/datasource.properties
deleted file mode 100644
index 61df0d45f7..0000000000
--- a/core-java-modules/core-java/src/main/resources/datasource.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-dataSourceClassName=//TBD
-dataSource.user=//TBD
-dataSource.password=//TBD
-dataSource.databaseName=//TBD
-dataSource.portNumber=//TBD
-dataSource.serverName=//TBD
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/resources/log4j.properties b/core-java-modules/core-java/src/main/resources/log4j.properties
deleted file mode 100644
index 621cf01735..0000000000
--- a/core-java-modules/core-java/src/main/resources/log4j.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-log4j.rootLogger=DEBUG, A1
-
-log4j.appender.A1=org.apache.log4j.ConsoleAppender
-
-log4j.appender.A1.layout=org.apache.log4j.PatternLayout
-log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/resources/log4j2.xml b/core-java-modules/core-java/src/main/resources/log4j2.xml
deleted file mode 100644
index a824bef9b0..0000000000
--- a/core-java-modules/core-java/src/main/resources/log4j2.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/resources/log4jstructuraldp.properties b/core-java-modules/core-java/src/main/resources/log4jstructuraldp.properties
deleted file mode 100644
index 5bc2bfe4b9..0000000000
--- a/core-java-modules/core-java/src/main/resources/log4jstructuraldp.properties
+++ /dev/null
@@ -1,9 +0,0 @@
-
-# Root logger
-log4j.rootLogger=INFO, file, stdout
-
-# Write to console
-log4j.appender.stdout=org.apache.log4j.ConsoleAppender
-log4j.appender.stdout.Target=System.out
-log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
-log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/main/resources/product.png b/core-java-modules/core-java/src/main/resources/product.png
deleted file mode 100644
index 4edd01c0a1..0000000000
Binary files a/core-java-modules/core-java/src/main/resources/product.png and /dev/null differ
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/arrays/ArraysJoinAndSplitJUnitTest.java b/core-java-modules/core-java/src/test/java/com/baeldung/arrays/ArraysJoinAndSplitJUnitTest.java
deleted file mode 100644
index b31a829f34..0000000000
--- a/core-java-modules/core-java/src/test/java/com/baeldung/arrays/ArraysJoinAndSplitJUnitTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.baeldung.arrays;
-
-import java.util.Arrays;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class ArraysJoinAndSplitJUnitTest {
-
- private final String[] sauces = { "Marinara", "Olive Oil" };
- private final String[] cheeses = { "Mozzarella", "Feta", "Parmesan" };
- private final String[] vegetables = { "Olives", "Spinach", "Green Peppers" };
-
- private final String[] customers = { "Jay", "Harry", "Ronnie", "Gary", "Ross" };
-
- @Test
- public void givenThreeStringArrays_whenJoiningIntoOneStringArray_shouldSucceed() {
- String[] toppings = new String[sauces.length + cheeses.length + vegetables.length];
-
- System.arraycopy(sauces, 0, toppings, 0, sauces.length);
- int AddedSoFar = sauces.length;
-
- System.arraycopy(cheeses, 0, toppings, AddedSoFar, cheeses.length);
- AddedSoFar += cheeses.length;
-
- System.arraycopy(vegetables, 0, toppings, AddedSoFar, vegetables.length);
-
- Assert.assertArrayEquals(toppings, new String[] { "Marinara", "Olive Oil", "Mozzarella", "Feta", "Parmesan", "Olives", "Spinach", "Green Peppers" });
- }
-
- @Test
- public void givenOneStringArray_whenSplittingInHalfTwoStringArrays_shouldSucceed() {
- int ordersHalved = (customers.length / 2) + (customers.length % 2);
-
- String[] driverOne = Arrays.copyOf(customers, ordersHalved);
- String[] driverTwo = Arrays.copyOfRange(customers, ordersHalved, customers.length);
-
- Assert.assertArrayEquals(driverOne, new String[] { "Jay", "Harry", "Ronnie" });
- Assert.assertArrayEquals(driverTwo, new String[] { "Gary", "Ross" });
- }
-}
diff --git a/core-java-modules/core-java/src/test/java/com/baeldung/stringisnumeric.zip b/core-java-modules/core-java/src/test/java/com/baeldung/stringisnumeric.zip
deleted file mode 100644
index b8a7b9b35a..0000000000
Binary files a/core-java-modules/core-java/src/test/java/com/baeldung/stringisnumeric.zip and /dev/null differ
diff --git a/core-java-modules/core-java/src/test/resources/newFile3.txt b/core-java-modules/core-java/src/test/resources/newFile3.txt
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/core-java-modules/core-java/src/test/resources/original.txt b/core-java-modules/core-java/src/test/resources/original.txt
deleted file mode 100644
index 8511f56bef..0000000000
--- a/core-java-modules/core-java/src/test/resources/original.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-#Copy a File with Java (www.Baeldung.com)
-Copying Files with Java is Fun!
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/sourceFile.txt b/core-java-modules/core-java/src/test/resources/sourceFile.txt
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/core-java-modules/core-java/src/test/resources/test.find b/core-java-modules/core-java/src/test/resources/test.find
deleted file mode 100644
index 0cb7d51df1..0000000000
--- a/core-java-modules/core-java/src/test/resources/test.find
+++ /dev/null
@@ -1 +0,0 @@
-Test of JNDI on file.
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read.in b/core-java-modules/core-java/src/test/resources/test_read.in
deleted file mode 100644
index 70c379b63f..0000000000
--- a/core-java-modules/core-java/src/test/resources/test_read.in
+++ /dev/null
@@ -1 +0,0 @@
-Hello world
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read1.in b/core-java-modules/core-java/src/test/resources/test_read1.in
deleted file mode 100644
index 1e46242993..0000000000
--- a/core-java-modules/core-java/src/test/resources/test_read1.in
+++ /dev/null
@@ -1 +0,0 @@
-Hello world 1
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read2.in b/core-java-modules/core-java/src/test/resources/test_read2.in
deleted file mode 100644
index fe47dc003b..0000000000
--- a/core-java-modules/core-java/src/test/resources/test_read2.in
+++ /dev/null
@@ -1 +0,0 @@
-2,3 4
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read3.in b/core-java-modules/core-java/src/test/resources/test_read3.in
deleted file mode 100644
index db9f25a672..0000000000
--- a/core-java-modules/core-java/src/test/resources/test_read3.in
+++ /dev/null
@@ -1 +0,0 @@
-Hello 1
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read4.in b/core-java-modules/core-java/src/test/resources/test_read4.in
deleted file mode 100644
index 5727d54bfc..0000000000
Binary files a/core-java-modules/core-java/src/test/resources/test_read4.in and /dev/null differ
diff --git a/core-java-modules/core-java/src/test/resources/test_read7.in b/core-java-modules/core-java/src/test/resources/test_read7.in
deleted file mode 100644
index 28d4d45d43..0000000000
--- a/core-java-modules/core-java/src/test/resources/test_read7.in
+++ /dev/null
@@ -1 +0,0 @@
-青空
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read8.in b/core-java-modules/core-java/src/test/resources/test_read8.in
deleted file mode 100644
index 10fc1aac8a..0000000000
--- a/core-java-modules/core-java/src/test/resources/test_read8.in
+++ /dev/null
@@ -1,2 +0,0 @@
-Hello world
- Test line
diff --git a/core-java-modules/core-java/src/test/resources/test_read_d.in b/core-java-modules/core-java/src/test/resources/test_read_d.in
deleted file mode 100644
index 82bbb4071f..0000000000
--- a/core-java-modules/core-java/src/test/resources/test_read_d.in
+++ /dev/null
@@ -1 +0,0 @@
-John,Adam-Tom
\ No newline at end of file
diff --git a/core-java-modules/core-java/src/test/resources/test_read_multiple.in b/core-java-modules/core-java/src/test/resources/test_read_multiple.in
deleted file mode 100644
index 7d64000a76..0000000000
--- a/core-java-modules/core-java/src/test/resources/test_read_multiple.in
+++ /dev/null
@@ -1,2 +0,0 @@
-Hello world
-Hi, John
\ No newline at end of file
diff --git a/core-java-modules/core-java/yofile.txt b/core-java-modules/core-java/yofile.txt
deleted file mode 100644
index ad56bf35f7..0000000000
Binary files a/core-java-modules/core-java/yofile.txt and /dev/null differ
diff --git a/core-java-modules/core-java/yofile2.txt b/core-java-modules/core-java/yofile2.txt
deleted file mode 100644
index 8393b6e98b..0000000000
Binary files a/core-java-modules/core-java/yofile2.txt and /dev/null differ
diff --git a/core-java-modules/pom.xml b/core-java-modules/pom.xml
index a96489ec6f..66456d2045 100644
--- a/core-java-modules/pom.xml
+++ b/core-java-modules/pom.xml
@@ -16,9 +16,20 @@
- core-java
- core-java-8
- core-java-8-2
+
+
+
+
+
+
+
+
+
+
+
+
+
+
core-java-annotations
core-java-arrays-sorting
core-java-arrays-guides
@@ -26,6 +37,7 @@
core-java-arrays-convert
core-java-arrays-operations-basic
core-java-arrays-operations-advanced
+ core-java-booleans
core-java-char
core-java-collections
core-java-collections-2
@@ -33,7 +45,6 @@
core-java-collections-4
core-java-collections-5
core-java-collections-conversions
- core-java-collections-conversions-2
core-java-collections-set-2
core-java-collections-list
core-java-collections-list-2
@@ -41,6 +52,7 @@
core-java-collections-maps
core-java-collections-maps-2
core-java-collections-maps-3
+ core-java-compiler
core-java-concurrency-2
core-java-concurrency-advanced
core-java-concurrency-advanced-2
@@ -52,11 +64,10 @@
core-java-concurrency-collections
core-java-concurrency-collections-2
core-java-console
- core-java-8-datetime-2
core-java-datetime-string-2
core-java-date-operations-2
core-java-date-operations-3
- core-java-8-datetime
+ core-java-documentation
core-java-exceptions
core-java-exceptions-2
core-java-exceptions-3
@@ -77,18 +88,16 @@
core-java-jvm-2
core-java-jvm-3
core-java-lambdas
- core-java-lang
core-java-lang-2
core-java-lang-3
core-java-lang-4
core-java-lang-5
core-java-lang-math
core-java-lang-math-2
- core-java-lang-math-3
core-java-lang-oop-constructors
core-java-lang-oop-patterns
core-java-lang-oop-generics
- core-java-lang-oop-modifiers
+
core-java-lang-oop-types
core-java-lang-oop-types-2
core-java-lang-oop-inheritance
@@ -98,27 +107,26 @@
core-java-lang-operators-2
core-java-lang-syntax
core-java-lang-syntax-2
+ core-java-locale
core-java-networking
core-java-networking-2
core-java-networking-4
core-java-nio
- core-java-nio-2
core-java-numbers
core-java-numbers-2
core-java-numbers-3
core-java-numbers-4
core-java-numbers-5
+ core-java-numbers-6
core-java-optional
core-java-perf
+ core-java-properties
core-java-reflection
core-java-reflection-2
- core-java-security
core-java-security-2
core-java-security-3
- core-java-serialization
core-java-security-algorithms
core-java-streams
- core-java-streams-2
core-java-streams-3
core-java-string-algorithms
core-java-string-algorithms-2
@@ -128,12 +136,12 @@
core-java-string-conversions-2
core-java-string-operations
core-java-string-operations-2
- core-java-sun
core-java-regex
core-java-regex-2
core-java-uuid
pre-jpms
core-java-collections-maps-6
+ core-java-records
diff --git a/core-java-modules/pre-jpms/pom.xml b/core-java-modules/pre-jpms/pom.xml
index cd4bd0faa3..67bc913767 100644
--- a/core-java-modules/pre-jpms/pom.xml
+++ b/core-java-modules/pre-jpms/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
pre-jpms
- 0.0.1-SNAPSHOT
pre-jpms
jar
@@ -15,6 +14,11 @@
+
+ javax.xml.bind
+ jaxb-api
+ 2.4.0-b180725.0427
+
org.slf4j
slf4j-api
@@ -32,6 +36,9 @@
${target.version}
+
+ --add-exports=java.base/com.sun.crypto.provider=ALL-UNNAMED
+
@@ -72,8 +79,8 @@
3.1.1
3.8.0
- 1.8
- 1.8
+ 11
+ 11
\ No newline at end of file
diff --git a/core-java-modules/pre-jpms/src/main/java/com/baeldung/prejpms/App.java b/core-java-modules/pre-jpms/src/main/java/com/baeldung/prejpms/App.java
index 1afaae30e4..a69e0555c6 100644
--- a/core-java-modules/pre-jpms/src/main/java/com/baeldung/prejpms/App.java
+++ b/core-java-modules/pre-jpms/src/main/java/com/baeldung/prejpms/App.java
@@ -1,19 +1,18 @@
package com.baeldung.prejpms;
import java.io.StringWriter;
+import java.lang.StackWalker.Option;
+import java.lang.StackWalker.StackFrame;
+import com.sun.crypto.provider.SunJCE;
+import java.util.Base64;
+import java.util.concurrent.atomic.AtomicInteger;
import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.sun.crypto.provider.SunJCE;
-
-import sun.misc.BASE64Encoder;
-import sun.reflect.Reflection;
-
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
@@ -37,14 +36,14 @@ public class App {
private static void getCallStackClassNames() {
try {
StringBuffer sbStack = new StringBuffer();
- int i = 0;
- Class> caller = Reflection.getCallerClass(i++);
- do {
- sbStack.append(i + ".")
- .append(caller.getName())
- .append("\n");
- caller = Reflection.getCallerClass(i++);
- } while (caller != null);
+ AtomicInteger i = new AtomicInteger(0);
+ StackWalker.getInstance((Option.RETAIN_CLASS_REFERENCE))
+ .walk(s -> s.map(StackFrame::getDeclaringClass)
+ .map(e -> {
+ i.getAndIncrement();
+ return e.getName();
+ }))
+ .forEach(name -> sbStack.append(String.format("%d. %s \n", i.get(), name)));
LOGGER.info("2. Call Stack:\n{}", sbStack);
} catch (Throwable e) {
LOGGER.error(e.toString());
@@ -54,7 +53,7 @@ public class App {
private static void getXmlFromObject(Book book) {
try {
Marshaller marshallerObj = JAXBContext.newInstance(Book.class)
- .createMarshaller();
+ .createMarshaller();
marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter sw = new StringWriter();
@@ -68,7 +67,8 @@ public class App {
private static void getBase64EncodedString(String inputString) {
try {
- String encodedString = new BASE64Encoder().encode(inputString.getBytes());
+ String encodedString = new String(Base64.getEncoder()
+ .encode(inputString.getBytes()));
LOGGER.info("4. Base Encoded String: {}", encodedString);
} catch (Throwable e) {
LOGGER.error(e.toString());
diff --git a/couchbase/pom.xml b/couchbase/pom.xml
index e87975a53c..823b33ee29 100644
--- a/couchbase/pom.xml
+++ b/couchbase/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
couchbase
- 0.1-SNAPSHOT
couchbase
jar
Couchbase Tutorials
@@ -64,11 +63,16 @@
${commons-lang3.version}
test
+
+ javax.annotation
+ javax.annotation-api
+ 1.3.2
+
- 2.5.0
- 4.3.5.RELEASE
+ 2.7.2
+ 5.3.25
\ No newline at end of file
diff --git a/custom-pmd/pom.xml b/custom-pmd/pom.xml
index 38a5e30404..8097d4fefa 100644
--- a/custom-pmd/pom.xml
+++ b/custom-pmd/pom.xml
@@ -8,7 +8,6 @@
0.0.1
custom-pmd
jar
- http://maven.apache.org
com.baeldung
diff --git a/data-structures/pom.xml b/data-structures/pom.xml
index cba602878f..aeadfcefc3 100644
--- a/data-structures/pom.xml
+++ b/data-structures/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
data-structures
- 0.0.1-SNAPSHOT
data-structures
@@ -13,13 +12,6 @@
1.0.0-SNAPSHOT
-
-
- github.release.repo
- https://raw.github.com/bulldog2011/bulldog-repo/master/repo/releases/
-
-
-
com.leansoft
@@ -39,6 +31,13 @@
+
+
+ github.release.repo
+ https://raw.github.com/bulldog2011/bulldog-repo/master/repo/releases/
+
+
+
0.7.0
diff --git a/ddd/pom.xml b/ddd/pom.xml
index 6128bb1cd9..443b2b5148 100644
--- a/ddd/pom.xml
+++ b/ddd/pom.xml
@@ -3,7 +3,6 @@
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.ddd
ddd
ddd
jar
diff --git a/deeplearning4j/pom.xml b/deeplearning4j/pom.xml
index 01bac93214..875d8cdf85 100644
--- a/deeplearning4j/pom.xml
+++ b/deeplearning4j/pom.xml
@@ -3,9 +3,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
- com.baeldung.deeplearning4j
deeplearning4j
- 1.0-SNAPSHOT
deeplearning4j
jar
diff --git a/dependeny-exclusion/dummy-surefire-junit47/pom.xml b/dependeny-exclusion/dummy-surefire-junit47/pom.xml
deleted file mode 100644
index 5859ddbe72..0000000000
--- a/dependeny-exclusion/dummy-surefire-junit47/pom.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
- 4.0.0
- org.apache.maven.surefire
- surefire-junit47
- dummy
-
diff --git a/di-modules/cdi/pom.xml b/di-modules/cdi/pom.xml
index bdba3429db..fd920c8ce1 100644
--- a/di-modules/cdi/pom.xml
+++ b/di-modules/cdi/pom.xml
@@ -42,10 +42,24 @@
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ --add-opens java.base/java.lang=ALL-UNNAMED
+
+
+
+
+
+
2.0.SP1
- 3.0.5.Final
- 1.9.2
+ 3.1.6.Final
+ 1.9.19
\ No newline at end of file
diff --git a/di-modules/guice/pom.xml b/di-modules/guice/pom.xml
index a28dbe5297..d0d2876fc8 100644
--- a/di-modules/guice/pom.xml
+++ b/di-modules/guice/pom.xml
@@ -3,7 +3,6 @@
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.examples.guice
guice
guice
jar
diff --git a/disruptor/pom.xml b/disruptor/pom.xml
index c2f9cf34b0..75e783e935 100644
--- a/disruptor/pom.xml
+++ b/disruptor/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
disruptor
- 0.1.0-SNAPSHOT
disruptor
jar
diff --git a/docker-modules/docker-caching/multi-module-caching/core/pom.xml b/docker-modules/docker-caching/multi-module-caching/core-module/pom.xml
similarity index 95%
rename from docker-modules/docker-caching/multi-module-caching/core/pom.xml
rename to docker-modules/docker-caching/multi-module-caching/core-module/pom.xml
index bcfc4b5783..159d76830b 100644
--- a/docker-modules/docker-caching/multi-module-caching/core/pom.xml
+++ b/docker-modules/docker-caching/multi-module-caching/core-module/pom.xml
@@ -3,7 +3,7 @@
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
- core
+ core-module
multi-module-caching
diff --git a/docker-modules/docker-caching/multi-module-caching/core/src/main/java/com/baeldung/maven_caching/CoreClass.java b/docker-modules/docker-caching/multi-module-caching/core-module/src/main/java/com/baeldung/maven_caching/CoreClass.java
similarity index 100%
rename from docker-modules/docker-caching/multi-module-caching/core/src/main/java/com/baeldung/maven_caching/CoreClass.java
rename to docker-modules/docker-caching/multi-module-caching/core-module/src/main/java/com/baeldung/maven_caching/CoreClass.java
diff --git a/docker-modules/docker-caching/multi-module-caching/pom.xml b/docker-modules/docker-caching/multi-module-caching/pom.xml
index 94a370453c..b64cf1a8b8 100644
--- a/docker-modules/docker-caching/multi-module-caching/pom.xml
+++ b/docker-modules/docker-caching/multi-module-caching/pom.xml
@@ -1,7 +1,7 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.baeldung
multi-module-caching
@@ -10,8 +10,8 @@
pom
- runner
- core
+ runner-module
+ core-module
diff --git a/docker-modules/docker-caching/multi-module-caching/runner/pom.xml b/docker-modules/docker-caching/multi-module-caching/runner-module/pom.xml
similarity index 95%
rename from docker-modules/docker-caching/multi-module-caching/runner/pom.xml
rename to docker-modules/docker-caching/multi-module-caching/runner-module/pom.xml
index e3f234bac0..e608706864 100644
--- a/docker-modules/docker-caching/multi-module-caching/runner/pom.xml
+++ b/docker-modules/docker-caching/multi-module-caching/runner-module/pom.xml
@@ -3,7 +3,7 @@
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
- runner
+ runner-module
multi-module-caching
@@ -14,7 +14,7 @@
com.baeldung
- core
+ core-module
0.0.1-SNAPSHOT
diff --git a/docker-modules/docker-caching/multi-module-caching/runner/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java b/docker-modules/docker-caching/multi-module-caching/runner-module/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
similarity index 100%
rename from docker-modules/docker-caching/multi-module-caching/runner/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
rename to docker-modules/docker-caching/multi-module-caching/runner-module/src/main/java/com/baeldung/maven_caching/MavenCachingApplication.java
diff --git a/docker-modules/docker-caching/single-module-caching/pom.xml b/docker-modules/docker-caching/single-module-caching/pom.xml
index 4a4e53f1d3..a388c7563f 100644
--- a/docker-modules/docker-caching/single-module-caching/pom.xml
+++ b/docker-modules/docker-caching/single-module-caching/pom.xml
@@ -1,7 +1,7 @@
+ 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
single-module-caching
diff --git a/docker-modules/docker-compose-2/pom.xml b/docker-modules/docker-compose-2/pom.xml
index 851742309d..3a94ee3901 100644
--- a/docker-modules/docker-compose-2/pom.xml
+++ b/docker-modules/docker-compose-2/pom.xml
@@ -1,7 +1,7 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
docker-compose-2
Demo project for Spring Boot and Docker - Module docker-compose-2
diff --git a/docker-modules/docker-containers/pom.xml b/docker-modules/docker-containers/pom.xml
index 42c2d403e4..79bf0aee72 100644
--- a/docker-modules/docker-containers/pom.xml
+++ b/docker-modules/docker-containers/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.docker
docker-containers
- 0.0.1-SNAPSHOT
Demo project for Spring Boot
diff --git a/docker-modules/pom.xml b/docker-modules/pom.xml
index 1a87fa5d1c..b4c5240718 100644
--- a/docker-modules/pom.xml
+++ b/docker-modules/pom.xml
@@ -3,9 +3,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.baeldung
docker-modules
- 1.0.0-SNAPSHOT
docker-modules
pom
diff --git a/dozer/pom.xml b/dozer/pom.xml
index 840763445c..66f4ee8227 100644
--- a/dozer/pom.xml
+++ b/dozer/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
dozer
- 1.0
dozer
diff --git a/drools/pom.xml b/drools/pom.xml
index daaf1fa8a7..12aaf1318a 100644
--- a/drools/pom.xml
+++ b/drools/pom.xml
@@ -8,9 +8,8 @@
com.baeldung
- parent-spring-4
- 0.0.1-SNAPSHOT
- ../parent-spring-4
+ parent-modules
+ 1.0.0-SNAPSHOT
@@ -57,10 +56,10 @@
- 4.4.6
- 7.4.1.Final
- 3.13
- 7.10.0.Final
+ 4.4.16
+ 8.32.0.Final
+ 5.2.3
+ 8.32.0.Final
-
\ No newline at end of file
+
diff --git a/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java b/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java
index 6f15ee510b..3baabbeb0f 100644
--- a/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java
+++ b/drools/src/main/java/com/baeldung/drools/backward_chaining/BackwardChaining.java
@@ -11,7 +11,6 @@ public class BackwardChaining {
Result result = new BackwardChaining().backwardChaining();
System.out.println(result.getValue());
result.getFacts()
- .stream()
.forEach(System.out::println);
}
diff --git a/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java b/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java
index cf5d56f246..fd2090aecb 100644
--- a/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java
+++ b/drools/src/main/java/com/baeldung/drools/config/DroolsBeanFactory.java
@@ -10,26 +10,25 @@ import org.kie.internal.builder.DecisionTableConfiguration;
import org.kie.internal.builder.DecisionTableInputType;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
-import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class DroolsBeanFactory {
private static final String RULES_PATH = "com/baeldung/drools/rules/";
- private KieServices kieServices=KieServices.Factory.get();
+ private KieServices kieServices = KieServices.Factory.get();
- private KieFileSystem getKieFileSystem() throws IOException{
+ private KieFileSystem getKieFileSystem() {
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
- List rules=Arrays.asList("BackwardChaining.drl","SuggestApplicant.drl","Product_rules.xls");
- for(String rule:rules){
+ List rules = Arrays.asList("BackwardChaining.drl", "SuggestApplicant.drl", "Product_rules.drl.xls");
+ for(String rule:rules) {
kieFileSystem.write(ResourceFactory.newClassPathResource(rule));
}
return kieFileSystem;
}
- public KieContainer getKieContainer() throws IOException {
+ public KieContainer getKieContainer() {
getKieRepository();
KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem());
@@ -44,21 +43,16 @@ public class DroolsBeanFactory {
private void getKieRepository() {
final KieRepository kieRepository = kieServices.getRepository();
- kieRepository.addKieModule(new KieModule() {
- public ReleaseId getReleaseId() {
- return kieRepository.getDefaultReleaseId();
- }
- });
+ kieRepository.addKieModule(kieRepository::getDefaultReleaseId);
}
- public KieSession getKieSession(){
+ public KieSession getKieSession() {
getKieRepository();
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/BackwardChaining.drl"));
kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/SuggestApplicant.drl"));
- kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Product_rules.xls"));
-
+ kieFileSystem.write(ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Product_rules.drl.xls"));
KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
kb.buildAll();
@@ -67,7 +61,6 @@ public class DroolsBeanFactory {
KieContainer kContainer = kieServices.newKieContainer(kieModule.getReleaseId());
return kContainer.newKieSession();
-
}
public KieSession getKieSession(Resource dt) {
@@ -90,7 +83,7 @@ public class DroolsBeanFactory {
/*
* Can be used for debugging
- * Input excelFile example: com/baeldung/drools/rules/Discount.xls
+ * Input excelFile example: com/baeldung/drools/rules/Discount.drl.xls
*/
public String getDrlFromExcel(String excelFile) {
DecisionTableConfiguration configuration = KnowledgeBuilderFactory.newDecisionTableConfiguration();
diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java b/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java
index 7b2ba117a1..d0ae5318b9 100644
--- a/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java
+++ b/drools/src/main/java/com/baeldung/drools/optaplanner/CourseSchedule.java
@@ -6,7 +6,7 @@ import java.util.List;
import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty;
import org.optaplanner.core.api.domain.solution.PlanningScore;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
-import org.optaplanner.core.api.domain.solution.drools.ProblemFactCollectionProperty;
+import org.optaplanner.core.api.domain.solution.ProblemFactCollectionProperty;
import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
import org.slf4j.Logger;
diff --git a/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java b/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java
index 86501cdccd..c9d2b4df99 100644
--- a/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java
+++ b/drools/src/main/java/com/baeldung/drools/optaplanner/ScoreCalculator.java
@@ -2,14 +2,13 @@ package com.baeldung.drools.optaplanner;
import java.util.HashSet;
-import org.optaplanner.core.api.score.Score;
import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore;
-import org.optaplanner.core.impl.score.director.easy.EasyScoreCalculator;
+import org.optaplanner.core.api.score.calculator.EasyScoreCalculator;
-public class ScoreCalculator implements EasyScoreCalculator {
+public class ScoreCalculator implements EasyScoreCalculator {
@Override
- public Score calculateScore(CourseSchedule courseSchedule) {
+ public HardSoftScore calculateScore(CourseSchedule courseSchedule) {
int hardScore = 0;
int softScore = 0;
@@ -27,6 +26,6 @@ public class ScoreCalculator implements EasyScoreCalculator {
}
}
- return HardSoftScore.valueOf(hardScore, softScore);
+ return HardSoftScore.of(hardScore, softScore);
}
}
diff --git a/drools/src/main/java/com/baeldung/drools/service/ApplicantService.java b/drools/src/main/java/com/baeldung/drools/service/ApplicantService.java
index f74298ef05..06f84358b0 100644
--- a/drools/src/main/java/com/baeldung/drools/service/ApplicantService.java
+++ b/drools/src/main/java/com/baeldung/drools/service/ApplicantService.java
@@ -3,19 +3,20 @@ package com.baeldung.drools.service;
import com.baeldung.drools.config.DroolsBeanFactory;
import com.baeldung.drools.model.Applicant;
import com.baeldung.drools.model.SuggestedRole;
-import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
-import java.io.IOException;
-
public class ApplicantService {
- KieSession kieSession=new DroolsBeanFactory().getKieSession();
+ KieSession kieSession = new DroolsBeanFactory().getKieSession();
- public SuggestedRole suggestARoleForApplicant(Applicant applicant,SuggestedRole suggestedRole) throws IOException {
- kieSession.insert(applicant);
- kieSession.setGlobal("suggestedRole",suggestedRole);
- kieSession.fireAllRules();
+ public SuggestedRole suggestARoleForApplicant(Applicant applicant,SuggestedRole suggestedRole) {
+ try {
+ kieSession.insert(applicant);
+ kieSession.setGlobal("suggestedRole", suggestedRole);
+ kieSession.fireAllRules();
+ } finally {
+ kieSession.dispose();
+ }
System.out.println(suggestedRole.getRole());
return suggestedRole;
diff --git a/drools/src/main/java/com/baeldung/drools/service/ProductService.java b/drools/src/main/java/com/baeldung/drools/service/ProductService.java
index be5e43ed7b..401f5a600f 100644
--- a/drools/src/main/java/com/baeldung/drools/service/ProductService.java
+++ b/drools/src/main/java/com/baeldung/drools/service/ProductService.java
@@ -2,18 +2,21 @@ package com.baeldung.drools.service;
import com.baeldung.drools.config.DroolsBeanFactory;
import com.baeldung.drools.model.Product;
-import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
public class ProductService {
- private KieSession kieSession=new DroolsBeanFactory().getKieSession();
+ private KieSession kieSession = new DroolsBeanFactory().getKieSession();
public Product applyLabelToProduct(Product product){
- kieSession.insert(product);
- kieSession.fireAllRules();
+ try {
+ kieSession.insert(product);
+ kieSession.fireAllRules();
+ } finally {
+ kieSession.dispose();
+ }
System.out.println(product.getLabel());
- return product;
+ return product;
}
diff --git a/drools/src/main/resources/com/baeldung/drools/rules/Discount.xls b/drools/src/main/resources/com/baeldung/drools/rules/Discount.drl.xls
similarity index 100%
rename from drools/src/main/resources/com/baeldung/drools/rules/Discount.xls
rename to drools/src/main/resources/com/baeldung/drools/rules/Discount.drl.xls
diff --git a/drools/src/main/resources/com/baeldung/drools/rules/Product_rules.xls b/drools/src/main/resources/com/baeldung/drools/rules/Product_rules.drl.xls
similarity index 100%
rename from drools/src/main/resources/com/baeldung/drools/rules/Product_rules.xls
rename to drools/src/main/resources/com/baeldung/drools/rules/Product_rules.drl.xls
diff --git a/drools/src/main/resources/courseScheduleSolverConfigDrools.xml b/drools/src/main/resources/courseScheduleSolverConfigDrools.xml
index 7cf95fdcd3..74112d9c7d 100644
--- a/drools/src/main/resources/courseScheduleSolverConfigDrools.xml
+++ b/drools/src/main/resources/courseScheduleSolverConfigDrools.xml
@@ -1,7 +1,9 @@
-
-
+
+ com.baeldung.drools.optaplanner.CourseSchedule
+ com.baeldung.drools.optaplanner.Lecture
+
courseSchedule.drl
diff --git a/drools/src/main/resources/courseScheduleSolverConfiguration.xml b/drools/src/main/resources/courseScheduleSolverConfiguration.xml
index dfedb8f2fd..4214b0943a 100644
--- a/drools/src/main/resources/courseScheduleSolverConfiguration.xml
+++ b/drools/src/main/resources/courseScheduleSolverConfiguration.xml
@@ -1,7 +1,9 @@
-
+ com.baeldung.drools.optaplanner.CourseSchedule
+ com.baeldung.drools.optaplanner.Lecture
+
com.baeldung.drools.optaplanner.ScoreCalculator
diff --git a/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java b/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java
index 1880e30b86..36b24349c7 100644
--- a/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java
+++ b/drools/src/test/java/com/baeldung/drools/optaplanner/OptaPlannerUnitTest.java
@@ -21,13 +21,12 @@ public class OptaPlannerUnitTest {
unsolvedCourseSchedule.getLectureList().add(new Lecture());
}
- unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(new Integer[] { 1, 2, 3 }));
- unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(new Integer[] { 1, 2 }));
+ unsolvedCourseSchedule.getPeriodList().addAll(Arrays.asList(1, 2, 3));
+ unsolvedCourseSchedule.getRoomList().addAll(Arrays.asList(1, 2));
}
@Test
public void test_whenCustomJavaSolver() {
-
SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfiguration.xml");
Solver solver = solverFactory.buildSolver();
CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule);
@@ -38,7 +37,6 @@ public class OptaPlannerUnitTest {
@Test
public void test_whenDroolsSolver() {
-
SolverFactory solverFactory = SolverFactory.createFromXmlResource("courseScheduleSolverConfigDrools.xml");
Solver solver = solverFactory.buildSolver();
CourseSchedule solvedCourseSchedule = solver.solve(unsolvedCourseSchedule);
diff --git a/drools/src/test/java/com/baeldung/drools/service/DiscountExcelIntegrationTest.java b/drools/src/test/java/com/baeldung/drools/service/DiscountExcelIntegrationTest.java
index c3c4ebd4f8..49a5f81d38 100644
--- a/drools/src/test/java/com/baeldung/drools/service/DiscountExcelIntegrationTest.java
+++ b/drools/src/test/java/com/baeldung/drools/service/DiscountExcelIntegrationTest.java
@@ -18,7 +18,7 @@ public class DiscountExcelIntegrationTest {
@Before
public void setup() {
- Resource resource = ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Discount.xls", getClass());
+ Resource resource = ResourceFactory.newClassPathResource("com/baeldung/drools/rules/Discount.drl.xls", getClass());
kSession = new DroolsBeanFactory().getKieSession(resource);
}
diff --git a/ethereum/pom.xml b/ethereum/pom.xml
index 6c1a0e900f..8dc25427d9 100644
--- a/ethereum/pom.xml
+++ b/ethereum/pom.xml
@@ -1,7 +1,7 @@
+ 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.ethereum
ethereum
@@ -113,7 +113,8 @@
test
${spring.boot.version}
-
+
junit
junit
@@ -195,4 +196,5 @@
2.0.4.RELEASE
3.1
+
\ No newline at end of file
diff --git a/feign/README.md b/feign/README.md
index 8079c46e9e..074ce1cbd2 100644
--- a/feign/README.md
+++ b/feign/README.md
@@ -6,9 +6,4 @@ This module contains articles about Feign
- [Intro to Feign](https://www.baeldung.com/intro-to-feign)
- [Retrying Feign Calls](https://www.baeldung.com/feign-retry)
-- [Setting Request Headers Using Feign](https://www.baeldung.com/java-feign-request-headers)
-- [File Upload With Open Feign](https://www.baeldung.com/java-feign-file-upload)
-- [Feign Logging Configuration](https://www.baeldung.com/java-feign-logging)
-- [Retrieve Original Message From Feign ErrorDecoder](https://www.baeldung.com/feign-retrieve-original-message)
-- [RequestLine with Feign Client](https://www.baeldung.com/feign-requestline)
-- [Propagating Exceptions With OpenFeign and Spring](https://www.baeldung.com/spring-openfeign-propagate-exception)
\ No newline at end of file
+- [Setting Request Headers Using Feign](https://www.baeldung.com/java-feign-request-headers)
\ No newline at end of file
diff --git a/feign/pom.xml b/feign/pom.xml
index 7338cf7508..edb55e7da5 100644
--- a/feign/pom.xml
+++ b/feign/pom.xml
@@ -3,7 +3,6 @@
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.baeldung.feign
feign
feign
@@ -69,11 +68,6 @@
feign-form-spring
${feign.form.spring.version}
-
- org.springframework.cloud
- spring-cloud-starter-openfeign
- ${spring.cloud.openfeign.version}
-
com.github.tomakehurst
wiremock-jre8
@@ -103,7 +97,7 @@
com.baeldung.feign.soap
-
+
diff --git a/feign/src/main/java/com/baeldung/core/ExampleApplication.java b/feign/src/main/java/com/baeldung/core/ExampleApplication.java
index 391e808ede..881265d5ba 100644
--- a/feign/src/main/java/com/baeldung/core/ExampleApplication.java
+++ b/feign/src/main/java/com/baeldung/core/ExampleApplication.java
@@ -2,10 +2,8 @@ package com.baeldung.core;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
-import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
-@EnableFeignClients
public class ExampleApplication {
public static void main(String[] args) {
diff --git a/feign/src/main/java/com/baeldung/core/fileupload/config/ExceptionMessage.java b/feign/src/main/java/com/baeldung/core/fileupload/config/ExceptionMessage.java
deleted file mode 100644
index 8301705ca6..0000000000
--- a/feign/src/main/java/com/baeldung/core/fileupload/config/ExceptionMessage.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package com.baeldung.core.fileupload.config;
-
-public class ExceptionMessage {
- private String timestamp;
- private int status;
- private String error;
- private String message;
- private String path;
-
- public String getTimestamp() {
- return timestamp;
- }
-
- public void setTimestamp(String timestamp) {
- this.timestamp = timestamp;
- }
-
- public int getStatus() {
- return status;
- }
-
- public void setStatus(int status) {
- this.status = status;
- }
-
- public String getError() {
- return error;
- }
-
- public void setError(String error) {
- this.error = error;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public String getPath() {
- return path;
- }
-
- public void setPath(String path) {
- this.path = path;
- }
-
- @Override
- public String toString() {
- return "ExceptionMessage [timestamp=" + timestamp + ", status=" + status + ", error=" + error + ", message=" + message + ", path=" + path + "]";
- }
-
-}
diff --git a/feign/src/main/java/com/baeldung/core/fileupload/config/RetreiveMessageErrorDecoder.java b/feign/src/main/java/com/baeldung/core/fileupload/config/RetreiveMessageErrorDecoder.java
deleted file mode 100644
index fc2c8da0ed..0000000000
--- a/feign/src/main/java/com/baeldung/core/fileupload/config/RetreiveMessageErrorDecoder.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.baeldung.core.fileupload.config;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import com.baeldung.core.exception.BadRequestException;
-import com.baeldung.core.exception.NotFoundException;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
-import feign.Response;
-import feign.codec.ErrorDecoder;
-
-public class RetreiveMessageErrorDecoder implements ErrorDecoder {
- private final ErrorDecoder errorDecoder = new Default();
-
- @Override
- public Exception decode(String methodKey, Response response) {
- ExceptionMessage message;
- try (InputStream bodyIs = response.body()
- .asInputStream()) {
- ObjectMapper mapper = new ObjectMapper();
- message = mapper.readValue(bodyIs, ExceptionMessage.class);
- } catch (IOException e) {
- return new Exception(e.getMessage());
- }
- switch (response.status()) {
- case 400:
- return new BadRequestException(message.getMessage() != null ? message.getMessage() : "Bad Request");
- case 404:
- return new NotFoundException(message.getMessage() != null ? message.getMessage() : "Not found");
- default:
- return errorDecoder.decode(methodKey, response);
- }
- }
-}
diff --git a/feign/src/main/java/com/baeldung/core/fileupload/service/UploadResource.java b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadResource.java
deleted file mode 100644
index 9d3d173cd4..0000000000
--- a/feign/src/main/java/com/baeldung/core/fileupload/service/UploadResource.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.baeldung.core.fileupload.service;
-
-import org.springframework.web.multipart.MultipartFile;
-
-import feign.Headers;
-import feign.Param;
-import feign.RequestLine;
-import feign.Response;
-
-public interface UploadResource {
-
- @RequestLine("POST /upload-file")
- @Headers("Content-Type: multipart/form-data")
- Response uploadFile(@Param("file") MultipartFile file);
-
-}
\ No newline at end of file
diff --git a/feign/src/main/java/com/baeldung/core/fileupload/service/UploadService.java b/feign/src/main/java/com/baeldung/core/fileupload/service/UploadService.java
deleted file mode 100644
index 5176ddf0fa..0000000000
--- a/feign/src/main/java/com/baeldung/core/fileupload/service/UploadService.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.baeldung.core.fileupload.service;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Service;
-import org.springframework.web.multipart.MultipartFile;
-
-import feign.Feign;
-import feign.Response;
-import feign.form.spring.SpringFormEncoder;
-
-@Service
-public class UploadService {
- private static final String HTTP_FILE_UPLOAD_URL = "http://localhost:8081";
-
- @Autowired
- private UploadClient client;
-
- public boolean uploadFileWithManualClient(MultipartFile file) {
- UploadResource fileUploadResource = Feign.builder().encoder(new SpringFormEncoder())
- .target(UploadResource.class, HTTP_FILE_UPLOAD_URL);
- Response response = fileUploadResource.uploadFile(file);
- return response.status() == 200;
- }
-
- public String uploadFile(MultipartFile file) {
- return client.fileUpload(file);
- }
-
- public String uploadFileError(MultipartFile file) {
- return client.fileUpload(file);
- }
-}
\ No newline at end of file
diff --git a/feign/src/test/java/com/baeldung/core/OpenFeignFileUploadLiveTest.java b/feign/src/test/java/com/baeldung/core/OpenFeignFileUploadLiveTest.java
deleted file mode 100644
index f9dc8b13ed..0000000000
--- a/feign/src/test/java/com/baeldung/core/OpenFeignFileUploadLiveTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package com.baeldung.core;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-
-import org.apache.commons.io.IOUtils;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.mock.web.MockMultipartFile;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.web.multipart.MultipartFile;
-
-import com.baeldung.core.fileupload.service.UploadService;
-
-@RunWith(SpringRunner.class)
-@SpringBootTest(classes = ExampleApplication.class)
-public class OpenFeignFileUploadLiveTest {
-
- @Autowired
- private UploadService uploadService;
-
- private static String FILE_NAME = "fileupload.txt";
-
- @Test
- public void whenFeignBuilder_thenFileUploadSuccess() throws IOException {
- ClassLoader classloader = Thread.currentThread().getContextClassLoader();
- File file = new File(classloader.getResource(FILE_NAME).getFile());
- Assert.assertTrue(file.exists());
- FileInputStream input = new FileInputStream(file);
- MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
- IOUtils.toByteArray(input));
- Assert.assertTrue(uploadService.uploadFileWithManualClient(multipartFile));
- }
-
- @Test
- public void whenAnnotatedFeignClient_thenFileUploadSuccess() throws IOException {
- ClassLoader classloader = Thread.currentThread().getContextClassLoader();
- File file = new File(classloader.getResource(FILE_NAME).getFile());
- Assert.assertTrue(file.exists());
- FileInputStream input = new FileInputStream(file);
- MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
- IOUtils.toByteArray(input));
- String uploadFile = uploadService.uploadFile(multipartFile);
- Assert.assertNotNull(uploadFile);
- }
-}
diff --git a/gcp-firebase/pom.xml b/gcp-firebase/pom.xml
index c563099ad6..10a899f370 100644
--- a/gcp-firebase/pom.xml
+++ b/gcp-firebase/pom.xml
@@ -1,48 +1,51 @@
-
- 4.0.0
+
+ 4.0.0
+ gcp-firebase
+
com.baeldung
parent-boot-2
0.0.1-SNAPSHOT
../parent-boot-2
- gcp-firebase
-
-
- 9.1.1
-
-
-
- com.google.firebase
- firebase-admin
- ${firebase-admin.version}
-
-
-
-
- org.springframework.boot
- spring-boot-starter-web
-
-
- org.springframework.boot
- spring-boot-starter-test
- test
-
-
- org.springframework.boot
- spring-boot-configuration-processor
- true
-
-
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
+
+
+ com.google.firebase
+ firebase-admin
+ ${firebase-admin.version}
+
+
+
+
+ org.springframework.boot
+ spring-boot-starter-web
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+ org.springframework.boot
+ spring-boot-configuration-processor
+ true
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
+
+
+ 9.1.1
+
+
\ No newline at end of file
diff --git a/gcp-firebase/src/main/resources/firebase-service-account.json b/gcp-firebase/src/main/resources/firebase-service-account.json
index ed5afa9f13..cd87ff6bda 100644
--- a/gcp-firebase/src/main/resources/firebase-service-account.json
+++ b/gcp-firebase/src/main/resources/firebase-service-account.json
@@ -1,10 +1,10 @@
{
"type": "service_account",
- "project_id": "tutorials-2cdfb",
- "private_key_id": "d9f6a684d6814f85ed2d0490585eb7bf590f983a",
- "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDdJWTeGT2eBFo+\nXxzT9xFJYPtyawTAj0K1rVUNlWNUwj3zszK6P2sAsrpI2Rz1klwQ9aDz9i3+Opxv\n7UZ3pOzur6S58JnoswtNs6BZ9P7oeggLJJC6MPjioxwh8jLLIGMgdVtC2/iPYW3r\nGzurWlwkM8M8DyCgNq7KKJcx44pGcyy16ZGCYiijuTEmK6R+WHJTTyICzRFu3Org\nuHGlZUs/G4E76p10HanoFX2AIS/fDEEMP2DXBB73yoCal5GuvMY9yZWxnvV65Y5z\nGveY3NDB9EESbO2AAhDvHekWT17uWhymtO5N3gM8da48J9d51tVzi0D/NIPZnF0u\nTS64uxK3AgMBAAECggEAYuEQa7oPcfLyQscWRbRH1250n2E4e7zSkBcTW4J7Km+7\ncZajTOGEP4iqgF4Lc8XgQnkBYXOmdvDP97+47VAh3EtOtRDeUEyV9kUlonNH8rx1\nkj3kNEwnTHav4oG/slEl4WJ3zro6NinTEvdXQ7OgVVOLrPP6m4g3uQ5TJCxgLEUI\nTd3Hs3cg3P71mzEqfBF4NmGVmC1ea5lXFELd6giJJMvL7g+O2w22/fquGWOrreAM\ncj/G2Xv9/vmzeb9yzbgGxqCJyY6vspmd90fQLUu7bxkEY5/PPc6Zk8qay4AdEn47\nkL6hnJiR8H1wMCzV2RTUKE7ospriNVdBilXgxm9IMQKBgQD1TmF0Bg85zvXmEKBa\nLBhbc3xTtM7DOgKs+pI12sYDKwgL/QKEI/TKkYXua0aVGiQWc2Bk2/0sYhO6aB2f\n6AN1ZUrf4PRM8c53jebChc7beVLSjWI8Tx+kE+0t8864OwvELYZUzP35oSx3RdJD\nE/CvqBM7NQfJwx2Mw2VJK/YRGQKBgQDmyWLm/IWitehkITw6xMQpkkFs2m4Joq3A\nJvAyri58TRkw/7rqWaIxb5Wcy/7BOvjDN8PZNTHh4ZvhQiHpn7NGUks2/ULnWxUB\nWAA9YbeO9PNHJfZ6PjD2FSvwOXHj+vVkWt2GCXT8pDGYM2ImqXon85Oe3OH/h+N5\nktO9taesTwKBgQCSdPGKK/P7N61oZpTWQW1pbFHWSCUKOiBO1mtk6/E9AvwS7EQM\nUMteBfRInJPPgYP6Q3hRv2YwkX3l1TOavRMTjB5f/BbfuZ7jkj0r9mfCcXUZcIAu\nMa9abus0fFP3eolT3zpMdvdLiwbZTz5x/f29YkPZHZhAxdVmrWJThYOsQQKBgBDu\nZVsc25D8V3hBF/IXzWxfVn1t6PS8ApM+SBDvxmlIHrkBiez3dna6APfn32C9utJX\nnP6qcGZp7s2v1F0XYkeecfYuzmG6xOe8VQgryxOp1M87ccG2HlFvbDHLhRd8qdQa\n9nWG7BY81Yac/m5nsJaNwB6/hbUBeybIJtCcKxjxAoGBAJ3y+QSFb4AYmxLFtmMA\nklOvlT+r70w4RV/z4SEO1gjWEh9IozNSXknl5Q/8Zh9IVm3+/qYap//IzEv9JUc3\nv4+HlpZu0trxTpvRWWjPqVr3ssxRdiFLC0LCLEk4rzqWLBVyzJm8uHVIF9Inv8PE\naudInvdbnfAWi60+1Wi8u0Co\n-----END PRIVATE KEY-----\n",
- "client_email": "firebase-adminsdk-2afzd@tutorials-2cdfb.iam.gserviceaccount.com",
- "client_id": "111111112074248894669",
+ "project_id": "REPLACE WITH VALID PROJECT ID",
+ "private_key_id": "REPLACE WITH VALID PRIVATE KEY ID",
+ "private_key": "REPLACE WITH VALID PRIVATE KEY",
+ "client_email": "REPLACE WITH VALID CLIENT EMAIL",
+ "client_id": "REPLACE WITH VALID CLIENT ID",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
diff --git a/geotools/pom.xml b/geotools/pom.xml
index 6edb344c8c..61682ae0f5 100644
--- a/geotools/pom.xml
+++ b/geotools/pom.xml
@@ -4,10 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
geotools
- 0.0.1-SNAPSHOT
geotools
jar
- http://maven.apache.org
com.baeldung
@@ -15,14 +13,6 @@
1.0.0-SNAPSHOT
-
-
- osgeo-release
- OSGeo Repository
- https://repo.osgeo.org/repository/release/
-
-
-
org.geotools
@@ -39,15 +29,16 @@
gt-swing
${geotools-swing.version}
-
- org.locationtech.jts
- jts-core
- 1.19.0
-
-
-
+
+
+ osgeo-release
+ OSGeo Repository
+ https://repo.osgeo.org/repository/release/
+
+
+
28.1
28.1
diff --git a/code-generation/README.md b/google-auto-project/README.md
similarity index 100%
rename from code-generation/README.md
rename to google-auto-project/README.md
diff --git a/code-generation/pom.xml b/google-auto-project/pom.xml
similarity index 96%
rename from code-generation/pom.xml
rename to google-auto-project/pom.xml
index ed8890e1dd..839ccabc5f 100644
--- a/code-generation/pom.xml
+++ b/google-auto-project/pom.xml
@@ -3,9 +3,9 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
- code-generation
+ google-auto-project
1.0
- code-generation
+ google-auto-project
com.baeldung
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/App.java b/google-auto-project/src/main/java/com/baeldung/autofactory/App.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/App.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/App.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/CustomStorage.java b/google-auto-project/src/main/java/com/baeldung/autofactory/CustomStorage.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/CustomStorage.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/CustomStorage.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/custom/AbstractFactory.java b/google-auto-project/src/main/java/com/baeldung/autofactory/custom/AbstractFactory.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/custom/AbstractFactory.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/custom/AbstractFactory.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/custom/CustomPhone.java b/google-auto-project/src/main/java/com/baeldung/autofactory/custom/CustomPhone.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/custom/CustomPhone.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/custom/CustomPhone.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/custom/SmartPhone.java b/google-auto-project/src/main/java/com/baeldung/autofactory/custom/SmartPhone.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/custom/SmartPhone.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/custom/SmartPhone.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/model/Camera.java b/google-auto-project/src/main/java/com/baeldung/autofactory/model/Camera.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/model/Camera.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/model/Camera.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/model/ClassicPhone.java b/google-auto-project/src/main/java/com/baeldung/autofactory/model/ClassicPhone.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/model/ClassicPhone.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/model/ClassicPhone.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/model/Phone.java b/google-auto-project/src/main/java/com/baeldung/autofactory/model/Phone.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/model/Phone.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/model/Phone.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/modules/SonyCameraModule.java b/google-auto-project/src/main/java/com/baeldung/autofactory/modules/SonyCameraModule.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/modules/SonyCameraModule.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/modules/SonyCameraModule.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/provided/IntermediateAssembler.java b/google-auto-project/src/main/java/com/baeldung/autofactory/provided/IntermediateAssembler.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/provided/IntermediateAssembler.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/provided/IntermediateAssembler.java
diff --git a/code-generation/src/main/java/com/baeldung/autofactory/provider/SonyCameraProvider.java b/google-auto-project/src/main/java/com/baeldung/autofactory/provider/SonyCameraProvider.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autofactory/provider/SonyCameraProvider.java
rename to google-auto-project/src/main/java/com/baeldung/autofactory/provider/SonyCameraProvider.java
diff --git a/code-generation/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java b/google-auto-project/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java
rename to google-auto-project/src/main/java/com/baeldung/autoservice/BingTranslationServiceProvider.java
diff --git a/code-generation/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java b/google-auto-project/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java
rename to google-auto-project/src/main/java/com/baeldung/autoservice/GoogleTranslationServiceProvider.java
diff --git a/code-generation/src/main/java/com/baeldung/autoservice/TranslationService.java b/google-auto-project/src/main/java/com/baeldung/autoservice/TranslationService.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autoservice/TranslationService.java
rename to google-auto-project/src/main/java/com/baeldung/autoservice/TranslationService.java
diff --git a/code-generation/src/main/java/com/baeldung/autovalue/AutoValueMoney.java b/google-auto-project/src/main/java/com/baeldung/autovalue/AutoValueMoney.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autovalue/AutoValueMoney.java
rename to google-auto-project/src/main/java/com/baeldung/autovalue/AutoValueMoney.java
diff --git a/code-generation/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java b/google-auto-project/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java
rename to google-auto-project/src/main/java/com/baeldung/autovalue/AutoValueMoneyWithBuilder.java
diff --git a/code-generation/src/main/java/com/baeldung/autovalue/Foo.java b/google-auto-project/src/main/java/com/baeldung/autovalue/Foo.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autovalue/Foo.java
rename to google-auto-project/src/main/java/com/baeldung/autovalue/Foo.java
diff --git a/code-generation/src/main/java/com/baeldung/autovalue/ImmutableMoney.java b/google-auto-project/src/main/java/com/baeldung/autovalue/ImmutableMoney.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autovalue/ImmutableMoney.java
rename to google-auto-project/src/main/java/com/baeldung/autovalue/ImmutableMoney.java
diff --git a/code-generation/src/main/java/com/baeldung/autovalue/MutableMoney.java b/google-auto-project/src/main/java/com/baeldung/autovalue/MutableMoney.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autovalue/MutableMoney.java
rename to google-auto-project/src/main/java/com/baeldung/autovalue/MutableMoney.java
diff --git a/code-generation/src/main/java/com/baeldung/autovalue/Person.java b/google-auto-project/src/main/java/com/baeldung/autovalue/Person.java
similarity index 100%
rename from code-generation/src/main/java/com/baeldung/autovalue/Person.java
rename to google-auto-project/src/main/java/com/baeldung/autovalue/Person.java
diff --git a/code-generation/src/main/resources/logback.xml b/google-auto-project/src/main/resources/logback.xml
similarity index 100%
rename from code-generation/src/main/resources/logback.xml
rename to google-auto-project/src/main/resources/logback.xml
diff --git a/code-generation/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java b/google-auto-project/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java
similarity index 100%
rename from code-generation/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java
rename to google-auto-project/src/test/java/com/baeldung/autoservice/TranslationServiceUnitTest.java
diff --git a/code-generation/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java b/google-auto-project/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java
similarity index 100%
rename from code-generation/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java
rename to google-auto-project/src/test/java/com/baeldung/autovalue/MoneyUnitTest.java
diff --git a/code-generation/src/test/java/com/baeldung/autovalue/PersonUnitTest.java b/google-auto-project/src/test/java/com/baeldung/autovalue/PersonUnitTest.java
similarity index 100%
rename from code-generation/src/test/java/com/baeldung/autovalue/PersonUnitTest.java
rename to google-auto-project/src/test/java/com/baeldung/autovalue/PersonUnitTest.java
diff --git a/google-cloud/pom.xml b/google-cloud/pom.xml
index 72b9647bc8..8bb535f12a 100644
--- a/google-cloud/pom.xml
+++ b/google-cloud/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
google-cloud
- 0.1-SNAPSHOT
google-cloud
jar
Google Cloud Tutorials
@@ -24,7 +23,6 @@
org.projectlombok
lombok
-
${lombok.version}
provided
diff --git a/gradle-modules/gradle-customization/protobuf/README.md b/gradle-modules/gradle-customization/protobuf/README.md
new file mode 100644
index 0000000000..4e94aa3557
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Configuring Protobuf Compilation with Custom Source Directories](https://www.baeldung.com/java-configure-protobuf-compilation-custom-source-directories)
diff --git a/gradle-modules/gradle-customization/protobuf/build.gradle b/gradle-modules/gradle-customization/protobuf/build.gradle
new file mode 100644
index 0000000000..3cac57fb03
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/build.gradle
@@ -0,0 +1,45 @@
+plugins {
+ id 'java'
+ id "com.google.protobuf" version "0.8.18"
+}
+
+group = 'com.baeldung'
+version = '0.0.1-SNAPSHOT'
+sourceCompatibility = '17'
+
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ implementation group: 'com.google.protobuf', name: 'protobuf-java', version: '3.15.0'
+ implementation group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'
+ testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
+ testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
+}
+
+tasks.named('test') {
+ useJUnitPlatform()
+}
+
+protobuf {
+ protoc {
+ artifact = 'com.google.protobuf:protoc:3.15.0'
+ }
+}
+
+sourceSets {
+ main {
+ proto {
+ srcDir 'src/sample_protofiles'
+ }
+ java {
+ srcDirs 'build/generated/source/proto/main/java'
+ }
+ }
+ test {
+ proto {
+ srcDir 'src/sample_protofiles'
+ }
+ }
+}
\ No newline at end of file
diff --git a/gradle-modules/gradle-customization/protobuf/gradle/wrapper/gradle-wrapper.properties b/gradle-modules/gradle-customization/protobuf/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000000..774fae8767
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradle-modules/gradle-customization/protobuf/gradlew b/gradle-modules/gradle-customization/protobuf/gradlew
new file mode 100755
index 0000000000..a69d9cb6c2
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/gradlew
@@ -0,0 +1,240 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+
+APP_NAME="Gradle"
+APP_BASE_NAME=${0##*/}
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+# Collect all arguments for the java command;
+# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
+# shell script including quotes and variable substitutions, so put them in
+# double quotes to make sure that they get re-expanded; and
+# * put everything else in single quotes, so that it's not re-expanded.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/gradle-modules/gradle-customization/protobuf/gradlew.bat b/gradle-modules/gradle-customization/protobuf/gradlew.bat
new file mode 100644
index 0000000000..f127cfd49d
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/gradlew.bat
@@ -0,0 +1,91 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/gradle-modules/gradle-customization/protobuf/settings.gradle b/gradle-modules/gradle-customization/protobuf/settings.gradle
new file mode 100644
index 0000000000..63483bae11
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/settings.gradle
@@ -0,0 +1 @@
+rootProject.name = 'protobuf'
diff --git a/gradle-modules/gradle-customization/protobuf/src/main/resources/application.properties b/gradle-modules/gradle-customization/protobuf/src/main/resources/application.properties
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/src/main/resources/application.properties
@@ -0,0 +1 @@
+
diff --git a/gradle-modules/gradle-customization/protobuf/src/sample_protofiles/user_message.proto b/gradle-modules/gradle-customization/protobuf/src/sample_protofiles/user_message.proto
new file mode 100644
index 0000000000..60e06c2016
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/src/sample_protofiles/user_message.proto
@@ -0,0 +1,13 @@
+syntax = "proto3";
+
+package com.baeldung.protobuf;
+
+option java_multiple_files = true;
+option java_package = "com.baeldung.protobuf.service";
+
+message User {
+ string firstName = 1;
+ optional string middleName = 2;
+ string lastName = 3;
+ optional uint32 age = 4;
+}
\ No newline at end of file
diff --git a/gradle-modules/gradle-customization/protobuf/src/test/java/com/baeldung/protobuf/ProtobufCodeGenerationUnitTest.java b/gradle-modules/gradle-customization/protobuf/src/test/java/com/baeldung/protobuf/ProtobufCodeGenerationUnitTest.java
new file mode 100644
index 0000000000..12187e3efb
--- /dev/null
+++ b/gradle-modules/gradle-customization/protobuf/src/test/java/com/baeldung/protobuf/ProtobufCodeGenerationUnitTest.java
@@ -0,0 +1,28 @@
+package com.baeldung.protobuf;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+import com.baeldung.protobuf.service.User;
+
+class ProtobufCodeGenerationUnitTest {
+
+ @Test
+ void givenUserData_whenObjectCreated_thenDataShouldMatch() {
+ final String firstName = "John";
+ final String lastName = "Doe";
+ final int age = 28;
+
+ User user = User.newBuilder()
+ .setFirstName(firstName)
+ .setLastName(lastName)
+ .setAge(age)
+ .build();
+
+ assertEquals(firstName, user.getFirstName());
+ assertEquals(lastName, user.getLastName());
+ assertEquals(age, user.getAge());
+ }
+
+}
diff --git a/graphql-modules/graphql-dgs/pom.xml b/graphql-modules/graphql-dgs/pom.xml
index 051785b4b8..313e598130 100644
--- a/graphql-modules/graphql-dgs/pom.xml
+++ b/graphql-modules/graphql-dgs/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
graphql-dgs
- 1.0
graphql-dgs
diff --git a/graphql-modules/graphql-java/pom.xml b/graphql-modules/graphql-java/pom.xml
index 01b7a4fbc3..88f2beb574 100644
--- a/graphql-modules/graphql-java/pom.xml
+++ b/graphql-modules/graphql-java/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
graphql-java
- 1.0
graphql-java
@@ -13,21 +12,6 @@
1.0.0-SNAPSHOT
-
-
- jitpack.io
- https://jitpack.io
-
-
-
- false
-
- central
- Central Repository
- https://repo.maven.apache.org/maven2
-
-
-
com.graphql-java
@@ -143,6 +127,13 @@
+
+
+ jitpack.io
+ https://jitpack.io
+
+
+
11.0
5.2.4
diff --git a/graphql-modules/graphql-spqr-boot-starter/pom.xml b/graphql-modules/graphql-spqr-boot-starter/pom.xml
index 6cb1d74329..fd9ebc0224 100644
--- a/graphql-modules/graphql-spqr-boot-starter/pom.xml
+++ b/graphql-modules/graphql-spqr-boot-starter/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
graphql-spqr-boot-starter
- 1.0
graphql-spqr-boot-starter
diff --git a/graphql-modules/graphql-spqr/pom.xml b/graphql-modules/graphql-spqr/pom.xml
index d845d1ac8a..756930f2ac 100644
--- a/graphql-modules/graphql-spqr/pom.xml
+++ b/graphql-modules/graphql-spqr/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
graphql-spqr
- 1.0
graphql-spqr
diff --git a/graphql-modules/pom.xml b/graphql-modules/pom.xml
index a42400b7cc..4b43cbffde 100644
--- a/graphql-modules/pom.xml
+++ b/graphql-modules/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.graphql
graphql-modules
- 1.0.0-SNAPSHOT
graphql-modules
pom
diff --git a/grpc/pom.xml b/grpc/pom.xml
index 40d35183dc..fed1e801f2 100644
--- a/grpc/pom.xml
+++ b/grpc/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
grpc
- 0.0.1-SNAPSHOT
grpc
jar
diff --git a/guava-modules/guava-18/pom.xml b/guava-modules/guava-18/pom.xml
index 8f5108bff1..873555bf24 100644
--- a/guava-modules/guava-18/pom.xml
+++ b/guava-modules/guava-18/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-18
- 0.1.0-SNAPSHOT
guava-18
diff --git a/guava-modules/guava-19/pom.xml b/guava-modules/guava-19/pom.xml
index ba85fe0ae8..9a40677e08 100644
--- a/guava-modules/guava-19/pom.xml
+++ b/guava-modules/guava-19/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-19
- 0.1.0-SNAPSHOT
guava-19
diff --git a/guava-modules/guava-21/pom.xml b/guava-modules/guava-21/pom.xml
index 9e791bfe23..a26176ba0b 100644
--- a/guava-modules/guava-21/pom.xml
+++ b/guava-modules/guava-21/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-21
- 1.0-SNAPSHOT
guava-21
diff --git a/guava-modules/guava-collections-list/pom.xml b/guava-modules/guava-collections-list/pom.xml
index 6863b4011c..a07f34e56c 100644
--- a/guava-modules/guava-collections-list/pom.xml
+++ b/guava-modules/guava-collections-list/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-collections-list
- 0.1.0-SNAPSHOT
guava-collections-list
diff --git a/guava-modules/guava-collections-map/pom.xml b/guava-modules/guava-collections-map/pom.xml
index 04beaa13a1..6b73e8c29a 100644
--- a/guava-modules/guava-collections-map/pom.xml
+++ b/guava-modules/guava-collections-map/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.guava
guava-collections-map
- 0.1.0-SNAPSHOT
guava-collections-map
diff --git a/guava-modules/guava-collections-set/pom.xml b/guava-modules/guava-collections-set/pom.xml
index 49bfc46ee2..ffd6c80a3e 100644
--- a/guava-modules/guava-collections-set/pom.xml
+++ b/guava-modules/guava-collections-set/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-collections-set
- 0.1.0-SNAPSHOT
guava-collections-set
diff --git a/guava-modules/guava-collections/pom.xml b/guava-modules/guava-collections/pom.xml
index 9283107023..e016b1c547 100644
--- a/guava-modules/guava-collections/pom.xml
+++ b/guava-modules/guava-collections/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-collections
- 0.1.0-SNAPSHOT
guava-collections
@@ -37,6 +36,7 @@
${java-hamcrest.version}
test
+
diff --git a/guava-modules/guava-core/pom.xml b/guava-modules/guava-core/pom.xml
index dd68fef43a..6c4f76356f 100644
--- a/guava-modules/guava-core/pom.xml
+++ b/guava-modules/guava-core/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-core
- 0.1.0-SNAPSHOT
guava-core
diff --git a/guava-modules/guava-io/pom.xml b/guava-modules/guava-io/pom.xml
index 2ea91c5e4f..367533139e 100644
--- a/guava-modules/guava-io/pom.xml
+++ b/guava-modules/guava-io/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-io
- 0.1.0-SNAPSHOT
guava-io
diff --git a/guava-modules/guava-utilities/pom.xml b/guava-modules/guava-utilities/pom.xml
index ab849072a5..407a44587e 100644
--- a/guava-modules/guava-utilities/pom.xml
+++ b/guava-modules/guava-utilities/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
guava-utilities
- 0.1.0-SNAPSHOT
guava-utilities
diff --git a/hazelcast/pom.xml b/hazelcast/pom.xml
index 694563790f..4742f213e5 100644
--- a/hazelcast/pom.xml
+++ b/hazelcast/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
hazelcast
- 0.0.1-SNAPSHOT
hazelcast
diff --git a/httpclient-simple/pom.xml b/httpclient-simple/pom.xml
index eea056477c..a6049432ce 100644
--- a/httpclient-simple/pom.xml
+++ b/httpclient-simple/pom.xml
@@ -1,10 +1,9 @@
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
httpclient-simple
- 0.1-SNAPSHOT
httpclient-simple
war
diff --git a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java
index 616b6470af..3992fd821e 100644
--- a/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java
+++ b/httpclient-simple/src/test/java/com/baeldung/httpclient/HttpClientHeadersLiveTest.java
@@ -25,26 +25,22 @@ class HttpClientHeadersLiveTest {
@Test
void whenClientUsesCustomUserAgent_thenCorrect() throws IOException {
+ final CloseableHttpClient client = HttpClients.custom()
+ .setUserAgent("Mozilla/5.0 Firefox/26.0")
+ .build();
final HttpGet request = new HttpGet(SAMPLE_URL);
- try (CloseableHttpClient client = HttpClients.custom()
- .setUserAgent("Mozilla/5.0 Firefox/26.0")
- .build()) {
-
- String response = client.execute(request, new BasicHttpClientResponseHandler());
- logger.info("Response -> {}", response);
- }
+ String response = client.execute(request, new BasicHttpClientResponseHandler());
+ logger.info("Response -> {}", response);
}
@Test
void whenRequestHasCustomUserAgent_thenCorrect() throws IOException {
+ CloseableHttpClient client = HttpClients.createDefault();
final HttpGet request = new HttpGet(SAMPLE_URL);
request.setHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 Firefox/26.0");
-
- try (CloseableHttpClient client = HttpClients.createDefault()) {
- String response = client.execute(request, new BasicHttpClientResponseHandler());
- logger.info("Response -> {}", response);
- }
+ String response = client.execute(request, new BasicHttpClientResponseHandler());
+ logger.info("Response -> {}", response);
}
@Test
diff --git a/httpclient4/.gitignore b/httpclient4/.gitignore
deleted file mode 100644
index 83c05e60c8..0000000000
--- a/httpclient4/.gitignore
+++ /dev/null
@@ -1,13 +0,0 @@
-*.class
-
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-
-# Packaged files #
-*.jar
-*.war
-*.ear
\ No newline at end of file
diff --git a/httpclient4/src/test/resources/.gitignore b/httpclient4/src/test/resources/.gitignore
deleted file mode 100644
index 83c05e60c8..0000000000
--- a/httpclient4/src/test/resources/.gitignore
+++ /dev/null
@@ -1,13 +0,0 @@
-*.class
-
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-
-# Packaged files #
-*.jar
-*.war
-*.ear
\ No newline at end of file
diff --git a/hystrix/pom.xml b/hystrix/pom.xml
index 639d4eba02..007c2e237b 100644
--- a/hystrix/pom.xml
+++ b/hystrix/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
hystrix
- 1.0
hystrix
diff --git a/image-processing/pom.xml b/image-processing/pom.xml
index 3780ecfd33..2a2b92ca48 100644
--- a/image-processing/pom.xml
+++ b/image-processing/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
image-processing
- 1.0-SNAPSHOT
image-processing
diff --git a/jackson-modules/jackson-annotations/pom.xml b/jackson-modules/jackson-annotations/pom.xml
index 4bb9341e43..e2d5e1e607 100644
--- a/jackson-modules/jackson-annotations/pom.xml
+++ b/jackson-modules/jackson-annotations/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-annotations
- 0.0.1-SNAPSHOT
jackson-annotations
diff --git a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/format/User.java b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/format/User.java
index e655deb93b..119c1e3ce3 100644
--- a/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/format/User.java
+++ b/jackson-modules/jackson-annotations/src/main/java/com/baeldung/jackson/format/User.java
@@ -1,26 +1,41 @@
package com.baeldung.jackson.format;
+import com.fasterxml.jackson.annotation.JsonFormat;
+
import java.util.Date;
-import com.baeldung.jackson.domain.Person;
-import com.fasterxml.jackson.annotation.JsonFormat;
-
-/**
- * @author Jay Sridhar
- * @version 1.0
- */
-public class User extends Person {
+public class User {
private String firstName;
private String lastName;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
private Date createdDate;
+ public User() {
+ }
+
public User(String firstName, String lastName) {
- super(firstName, lastName);
+ this.firstName = firstName;
+ this.lastName = lastName;
this.createdDate = new Date();
}
+ 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 Date getCreatedDate() {
return createdDate;
}
@@ -35,3 +50,51 @@ public class User extends Person {
return new Date();
}
}
+
+@JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES)
+class UserIgnoreCase {
+ private String firstName;
+ private String lastName;
+
+ @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ")
+ private Date createdDate;
+
+ public UserIgnoreCase() {
+ }
+
+ public UserIgnoreCase(String firstName, String lastName) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.createdDate = new Date();
+ }
+
+ 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 Date getCreatedDate() {
+ return createdDate;
+ }
+
+ @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB")
+ public Date getCurrentDate() {
+ return new Date();
+ }
+
+ @JsonFormat(shape = JsonFormat.Shape.NUMBER)
+ public Date getDateNum() {
+ return new Date();
+ }
+}
\ No newline at end of file
diff --git a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java
index cf166fdc36..5cdc248d3b 100644
--- a/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java
+++ b/jackson-modules/jackson-annotations/src/test/java/com/baeldung/jackson/format/JsonFormatUnitTest.java
@@ -1,24 +1,25 @@
package com.baeldung.jackson.format;
-import java.util.Date;
-
import com.fasterxml.jackson.core.JsonProcessingException;
-
import com.fasterxml.jackson.databind.ObjectMapper;
-
+import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;
import org.junit.Test;
-import static io.restassured.path.json.JsonPath.from;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.TimeZone;
+import static io.restassured.path.json.JsonPath.from;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.from;
import static org.assertj.core.data.Percentage.withPercentage;
-/**
- * @author Jay Sridhar
- * @version 1.0
- */
public class JsonFormatUnitTest {
+ private static final String JSON_STRING = "{\"FIRSTNAME\":\"John\",\"lastname\":\"Smith\",\"cReAtEdDaTe\":\"2016-12-18@07:53:34.740+0000\"}";
+
@Test
public void whenSerializedDateFormat_thenCorrect() throws JsonProcessingException {
@@ -32,6 +33,24 @@ public class JsonFormatUnitTest {
// Expected to be close to current time
long now = new Date().getTime();
assertThat(from(result).getLong("dateNum")).isCloseTo(now, withPercentage(10.0));
-
}
-}
+
+ @Test
+ public void whenDeserializeJsonStrToUserObject_thenFail() {
+ assertThatThrownBy(() -> new ObjectMapper().readValue(JSON_STRING, User.class)).isInstanceOf(UnrecognizedPropertyException.class);
+ }
+
+ @Test
+ public void whenDeserializeJsonStrToUserIgnoreCaseObject_thenSuccess() throws JsonProcessingException, ParseException {
+ UserIgnoreCase result = new ObjectMapper().readValue(JSON_STRING, UserIgnoreCase.class);
+ SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSzz");
+ Date expectedDate = fmt.parse("2016-12-18T07:53:34.740+0000");
+
+ assertThat(result)
+ .isNotNull()
+ .returns("John", from(UserIgnoreCase::getFirstName))
+ .returns("Smith", from(UserIgnoreCase::getLastName))
+ .returns(expectedDate, from(UserIgnoreCase::getCreatedDate));
+ }
+
+}
\ No newline at end of file
diff --git a/jackson-modules/jackson-conversions-2/pom.xml b/jackson-modules/jackson-conversions-2/pom.xml
index 1c6d2fc002..457045b460 100644
--- a/jackson-modules/jackson-conversions-2/pom.xml
+++ b/jackson-modules/jackson-conversions-2/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-conversions-2
- 0.0.1-SNAPSHOT
jackson-conversions-2
diff --git a/jackson-modules/jackson-conversions/pom.xml b/jackson-modules/jackson-conversions/pom.xml
index 9218f209ac..e0990ed34f 100644
--- a/jackson-modules/jackson-conversions/pom.xml
+++ b/jackson-modules/jackson-conversions/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-conversions
- 0.0.1-SNAPSHOT
jackson-conversions
@@ -24,6 +23,11 @@
jackson-datatype-jsr310
${jackson.version}
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson.version}
+
diff --git a/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/Fruit.java b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/Fruit.java
new file mode 100644
index 0000000000..49e45f2161
--- /dev/null
+++ b/jackson-modules/jackson-conversions/src/main/java/com/baeldung/jackson/map/Fruit.java
@@ -0,0 +1,21 @@
+package com.baeldung.jackson.map;
+
+import com.fasterxml.jackson.annotation.JsonKey;
+import com.fasterxml.jackson.annotation.JsonValue;
+
+public class Fruit {
+ public String variety;
+
+ @JsonKey
+ public String name;
+
+ public Fruit(String variety, String name) {
+ this.variety = variety;
+ this.name = name;
+ }
+
+ @JsonValue
+ public String getFullName() {
+ return this.variety + " " + this.name;
+ }
+}
diff --git a/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/map/MapWithJsonKeyValueUnitTest.java b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/map/MapWithJsonKeyValueUnitTest.java
new file mode 100644
index 0000000000..0b4639ca3b
--- /dev/null
+++ b/jackson-modules/jackson-conversions/src/test/java/com/baeldung/jackson/map/MapWithJsonKeyValueUnitTest.java
@@ -0,0 +1,48 @@
+package com.baeldung.jackson.map;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+public class MapWithJsonKeyValueUnitTest {
+ private static final Fruit FRUIT1 = new Fruit("Alphonso", "Mango");
+ private static final Fruit FRUIT2 = new Fruit("Black", "Grapes");
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+
+ @Test
+ public void givenObject_WhenSerialize_ThenUseJsonValueForSerialization() throws JsonProcessingException {
+ String serializedValueForFruit1 = OBJECT_MAPPER.writeValueAsString(FRUIT1);
+ Assertions.assertEquals("\"Alphonso Mango\"", serializedValueForFruit1);
+ String serializedValueForFruit2 = OBJECT_MAPPER.writeValueAsString(FRUIT2);
+ Assertions.assertEquals("\"Black Grapes\"", serializedValueForFruit2);
+ }
+
+ @Test
+ public void givenMapWithObjectKeys_WhenSerialize_ThenUseJsonKeyForSerialization() throws JsonProcessingException {
+ // Given
+ Map selectionByFruit = new LinkedHashMap();
+ selectionByFruit.put(FRUIT1, "Hagrid");
+ selectionByFruit.put(FRUIT2, "Hercules");
+ // When
+ String serializedValue = OBJECT_MAPPER.writeValueAsString(selectionByFruit);
+ // Then
+ Assertions.assertEquals("{\"Mango\":\"Hagrid\",\"Grapes\":\"Hercules\"}", serializedValue);
+ }
+
+ @Test
+ public void givenMapWithObjectValues_WhenSerialize_ThenUseJsonValueForSerialization() throws JsonProcessingException {
+ // Given
+ Map selectionByPerson = new LinkedHashMap();
+ selectionByPerson.put("Hagrid", FRUIT1);
+ selectionByPerson.put("Hercules", FRUIT2);
+ // When
+ String serializedValue = OBJECT_MAPPER.writeValueAsString(selectionByPerson);
+ // Then
+ Assertions.assertEquals("{\"Hagrid\":\"Alphonso Mango\",\"Hercules\":\"Black Grapes\"}", serializedValue);
+ }
+}
diff --git a/jackson-modules/jackson-core/README.md b/jackson-modules/jackson-core/README.md
index 0aa3dc5aef..73293b1e84 100644
--- a/jackson-modules/jackson-core/README.md
+++ b/jackson-modules/jackson-core/README.md
@@ -14,3 +14,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Inheritance with Jackson](https://www.baeldung.com/jackson-inheritance)
- [Working with Tree Model Nodes in Jackson](https://www.baeldung.com/jackson-json-node-tree-model)
- [Get all the Keys in a JSON String Using JsonNode](https://www.baeldung.com/java-jsonnode-get-keys)
+- [Difference Between asText() and toString() in JsonNode](https://www.baeldung.com/java-jsonnode-astext-vs-tostring)
+- [Deserialize Generic Type with Jackson](https://www.baeldung.com/java-deserialize-generic-type-with-jackson)
diff --git a/jackson-modules/jackson-core/pom.xml b/jackson-modules/jackson-core/pom.xml
index f3edffc07c..4eccd4d8f8 100644
--- a/jackson-modules/jackson-core/pom.xml
+++ b/jackson-modules/jackson-core/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-core
- 0.0.1-SNAPSHOT
jackson-core
diff --git a/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/deserialization/jsongeneric/JsonResponse.java b/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/deserialization/jsongeneric/JsonResponse.java
new file mode 100644
index 0000000000..14f6b3f8ad
--- /dev/null
+++ b/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/deserialization/jsongeneric/JsonResponse.java
@@ -0,0 +1,14 @@
+package com.baeldung.jackson.deserialization.jsongeneric;
+
+public class JsonResponse {
+
+ private T result;
+
+ public T getResult() {
+ return result;
+ }
+
+ public void setResult(T result) {
+ this.result = result;
+ }
+}
diff --git a/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/deserialization/jsongeneric/User.java b/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/deserialization/jsongeneric/User.java
new file mode 100644
index 0000000000..1efb3af7f9
--- /dev/null
+++ b/jackson-modules/jackson-core/src/main/java/com/baeldung/jackson/deserialization/jsongeneric/User.java
@@ -0,0 +1,33 @@
+package com.baeldung.jackson.deserialization.jsongeneric;
+
+public class User {
+
+ private Long id;
+ private String firstName;
+ private String lastName;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ 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;
+ }
+}
+
diff --git a/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/deserialization/jsongeneric/GenericTypeDeserializerUnitTest.java b/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/deserialization/jsongeneric/GenericTypeDeserializerUnitTest.java
new file mode 100644
index 0000000000..24baeb7f1f
--- /dev/null
+++ b/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/deserialization/jsongeneric/GenericTypeDeserializerUnitTest.java
@@ -0,0 +1,40 @@
+package com.baeldung.jackson.deserialization.jsongeneric;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+class GenericTypeDeserializerUnitTest {
+
+ ObjectMapper objectMapper = new ObjectMapper();
+
+ @Test
+ void givenJsonObject_whenDeserializeIntoGenericTypeByTypeReference_thenCorrect() throws JsonProcessingException {
+ String json = "{\"result\":{\"id\":1,\"firstName\":\"John\",\"lastName\":\"Lewis\"}}";
+
+ TypeReference> typeRef = new TypeReference>() {};
+ JsonResponse jsonResponse = objectMapper.readValue(json, typeRef);
+ User user = jsonResponse.getResult();
+
+ assertThat(user.getId()).isEqualTo(1);
+ assertThat(user.getFirstName()).isEqualTo("John");
+ assertThat(user.getLastName()).isEqualTo("Lewis");
+ }
+
+ @Test
+ void givenJsonObject_whenDeserializeIntoGenericTypeByJavaType_thenCorrect() throws JsonProcessingException {
+ String json = "{\"result\":{\"id\":1,\"firstName\":\"John\",\"lastName\":\"Lewis\"}}";
+
+ JavaType javaType = objectMapper.getTypeFactory().constructParametricType(JsonResponse.class, User.class);
+ JsonResponse jsonResponse = objectMapper.readValue(json, javaType);
+ User user = jsonResponse.getResult();
+
+ assertThat(user.getId()).isEqualTo(1);
+ assertThat(user.getFirstName()).isEqualTo("John");
+ assertThat(user.getLastName()).isEqualTo("Lewis");
+ }
+}
\ No newline at end of file
diff --git a/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/jsonnode/AsTextVsAsStringTest.java b/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/jsonnode/AsTextVsAsStringTest.java
new file mode 100644
index 0000000000..4a566594ae
--- /dev/null
+++ b/jackson-modules/jackson-core/src/test/java/com/baeldung/jackson/jsonnode/AsTextVsAsStringTest.java
@@ -0,0 +1,53 @@
+package com.baeldung.jackson.jsonnode;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+
+class AsTextVsAsStringUnitTest {
+ @Test
+ void shouldUseAsText() throws JsonProcessingException {
+ String json = "{\"name\":\"John\",\"age\":30}";
+ JsonNode node = new ObjectMapper().readTree(json);
+
+ String name = node.get("name")
+ .asText();
+ String age = node.get("age")
+ .asText();
+ String jsonText = node.asText();
+ assertThat(jsonText).isEmpty();
+ assertThat(name).isEqualTo("John");
+ assertThat(age).isEqualTo("30");
+ }
+
+ @Test
+ void shouldUseAsTextWithEscapeCharacters() throws JsonProcessingException {
+ String specialCharsJson = "{\"text\":\"Hello \\\"world\\\" !\"}";
+ JsonNode specialCharsNode = new ObjectMapper().readTree(specialCharsJson);
+ String specialCharsJsonAsText = specialCharsNode.get("text")
+ .asText();
+ String specialCharsJsonToString = specialCharsNode.get("text")
+ .toString();
+ assertThat(specialCharsJsonAsText).isEqualTo("Hello \"world\" !");
+ assertThat(specialCharsJsonToString).isEqualTo("\"Hello \\\"world\\\" !\"");
+ }
+
+ @Test
+ void shouldUseToString() throws JsonProcessingException {
+ String json = "{\"name\":\"John\",\"age\":30}";
+ JsonNode node = new ObjectMapper().readTree(json);
+
+ String jsonString = node.toString();
+ String name = node.get("name")
+ .toString();
+ String age = node.get("age")
+ .toString();
+ assertThat(jsonString).isEqualTo("{\"name\":\"John\",\"age\":30}");
+ assertThat(name).isEqualTo("\"John\"");
+ assertThat(age).isEqualTo("30");
+ }
+}
\ No newline at end of file
diff --git a/jackson-modules/jackson-custom-conversions/README.md b/jackson-modules/jackson-custom-conversions/README.md
index 68e9a6d50d..2f45a2f43b 100644
--- a/jackson-modules/jackson-custom-conversions/README.md
+++ b/jackson-modules/jackson-custom-conversions/README.md
@@ -7,3 +7,4 @@ This module contains articles about Jackson custom conversions.
- [Getting Started with Custom Deserialization in Jackson](https://www.baeldung.com/jackson-deserialization)
- [Serialize Only Fields that meet a Custom Criteria with Jackson](https://www.baeldung.com/jackson-serialize-field-custom-criteria)
- [Calling Default Serializer from Custom Serializer in Jackson](https://www.baeldung.com/jackson-call-default-serializer-from-custom-serializer)
+- [OffsetDateTime Serialization With Jackson](https://www.baeldung.com/java-jackson-offsetdatetime)
diff --git a/jackson-modules/jackson-custom-conversions/pom.xml b/jackson-modules/jackson-custom-conversions/pom.xml
index 79af962eec..31e460511a 100644
--- a/jackson-modules/jackson-custom-conversions/pom.xml
+++ b/jackson-modules/jackson-custom-conversions/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-custom-conversions
- 0.0.1-SNAPSHOT
jackson-custom-conversions
diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/offsetdatetime/Main.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/offsetdatetime/Main.java
new file mode 100644
index 0000000000..eb82c3c4c8
--- /dev/null
+++ b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/offsetdatetime/Main.java
@@ -0,0 +1,50 @@
+package com.baeldung.offsetdatetime;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+
+import java.time.OffsetDateTime;
+
+public class Main {
+ public static void main(String[] args) throws JsonProcessingException {
+ System.out.println(serializeUser());
+ System.out.println(customSerialize());
+ System.out.println(customDeserialize());
+ }
+
+ static String serializeUser() throws JsonProcessingException {
+ ObjectMapper objectMapper = new ObjectMapper();
+ objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
+ objectMapper.registerModule(new JavaTimeModule());
+
+ User user = new User();
+ user.setCreatedAt(OffsetDateTime.parse("2021-09-30T15:30:00+01:00"));
+
+ return objectMapper.writeValueAsString(user);
+ }
+
+ static String customSerialize() throws JsonProcessingException {
+ ObjectMapper objectMapper = new ObjectMapper();
+
+ objectMapper.registerModule(new SimpleModule().addSerializer(OffsetDateTime.class, new OffsetDateTimeSerializer()));
+
+ User user = new User();
+ user.setCreatedAt(OffsetDateTime.parse("2021-09-30T15:30:00+01:00"));
+
+ return objectMapper.writeValueAsString(user);
+ }
+
+ static String customDeserialize() throws JsonProcessingException {
+ ObjectMapper objectMapper = new ObjectMapper();
+
+ objectMapper.registerModule(new SimpleModule().addDeserializer(OffsetDateTime.class, new OffsetDateTimeDeserializer()));
+
+ String jsonString = "{\"createdAt\":\"30-09-2021 15:30:00 +01:00\"}";
+ User returnedUser = objectMapper.readValue(jsonString, User.class);
+
+ return returnedUser.getCreatedAt().toString();
+ }
+}
diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/offsetdatetime/OffsetDateTimeDeserializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/offsetdatetime/OffsetDateTimeDeserializer.java
new file mode 100644
index 0000000000..a76d598b8f
--- /dev/null
+++ b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/offsetdatetime/OffsetDateTimeDeserializer.java
@@ -0,0 +1,24 @@
+package com.baeldung.offsetdatetime;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+
+import java.io.IOException;
+import java.time.OffsetDateTime;
+import java.time.format.DateTimeFormatter;
+
+public class OffsetDateTimeDeserializer extends JsonDeserializer {
+ private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter
+ .ofPattern("dd-MM-yyyy HH:mm:ss XXX");
+
+ @Override
+ public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
+ throws IOException {
+ String dateAsString = jsonParser.getText();
+ if (dateAsString == null) {
+ throw new IOException("OffsetDateTime argument is null.");
+ }
+ return OffsetDateTime.parse(dateAsString, DATE_TIME_FORMATTER);
+ }
+}
\ No newline at end of file
diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/offsetdatetime/OffsetDateTimeSerializer.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/offsetdatetime/OffsetDateTimeSerializer.java
new file mode 100644
index 0000000000..8821f37e8e
--- /dev/null
+++ b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/offsetdatetime/OffsetDateTimeSerializer.java
@@ -0,0 +1,23 @@
+package com.baeldung.offsetdatetime;
+
+import com.fasterxml.jackson.core.JsonGenerator;
+import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.SerializerProvider;
+
+import java.io.IOException;
+import java.time.OffsetDateTime;
+import java.time.format.DateTimeFormatter;
+
+public class OffsetDateTimeSerializer extends JsonSerializer {
+ private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter
+ .ofPattern("dd-MM-yyyy HH:mm:ss XXX");
+
+ @Override
+ public void serialize(OffsetDateTime value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
+ throws IOException {
+ if (value == null) {
+ throw new IOException("OffsetDateTime argument is null.");
+ }
+ jsonGenerator.writeString(DATE_TIME_FORMATTER.format(value));
+ }
+}
\ No newline at end of file
diff --git a/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/offsetdatetime/User.java b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/offsetdatetime/User.java
new file mode 100644
index 0000000000..44978cac87
--- /dev/null
+++ b/jackson-modules/jackson-custom-conversions/src/main/java/com/baeldung/offsetdatetime/User.java
@@ -0,0 +1,18 @@
+package com.baeldung.offsetdatetime;
+
+import java.time.OffsetDateTime;
+
+public class User {
+ private OffsetDateTime createdAt;
+
+ public User() {
+ }
+
+ public OffsetDateTime getCreatedAt() {
+ return createdAt;
+ }
+
+ public void setCreatedAt(OffsetDateTime createdAt) {
+ this.createdAt = createdAt;
+ }
+}
\ No newline at end of file
diff --git a/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/offsetdatetime/MainUnitTest.java b/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/offsetdatetime/MainUnitTest.java
new file mode 100644
index 0000000000..553adc8fdf
--- /dev/null
+++ b/jackson-modules/jackson-custom-conversions/src/test/java/com/baeldung/offsetdatetime/MainUnitTest.java
@@ -0,0 +1,23 @@
+package com.baeldung.offsetdatetime;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class MainUnitTest {
+
+ @Test
+ void givenUser_whenSerialized_thenCreatedDateIsSerialized() throws JsonProcessingException {
+ Assertions.assertEquals("{\"createdAt\":\"2021-09-30T15:30:00+01:00\"}", Main.serializeUser());
+ }
+
+ @Test
+ void givenUser_whenCustomSerialized_thenCreatedDateIsSerialized() throws JsonProcessingException {
+ Assertions.assertEquals("{\"createdAt\":\"30-09-2021 15:30:00 +01:00\"}", Main.customSerialize());
+ }
+
+ @Test
+ void givenUser_whenCustomDeserialized_thenCreatedDateIsDeserialized() throws JsonProcessingException {
+ Assertions.assertEquals("2021-09-30T15:30+01:00", Main.customDeserialize());
+ }
+}
\ No newline at end of file
diff --git a/jackson-modules/jackson-exceptions/README.md b/jackson-modules/jackson-exceptions/README.md
index 6f082aaaa5..b9c43cb09f 100644
--- a/jackson-modules/jackson-exceptions/README.md
+++ b/jackson-modules/jackson-exceptions/README.md
@@ -5,3 +5,4 @@ This module contains articles about Jackson exceptions.
### Relevant Articles:
- [Jackson Exceptions – Problems and Solutions](https://www.baeldung.com/jackson-exception)
- [Jackson – JsonMappingException (No serializer found for class)](https://www.baeldung.com/jackson-jsonmappingexception)
+- [Fix the JsonMappingException: Can not deserialize instance of java.util.ArrayList from Object value (token `JsonToken.START_OBJECT`)](https://www.baeldung.com/jsonmappingexception-can-not-deserialize-instance-of-java-util-arraylist-from-object-value-token-jsontoken-start_object)
diff --git a/jackson-modules/jackson-exceptions/pom.xml b/jackson-modules/jackson-exceptions/pom.xml
index a24a0ab4b7..e19ef4f883 100644
--- a/jackson-modules/jackson-exceptions/pom.xml
+++ b/jackson-modules/jackson-exceptions/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-exceptions
- 0.0.1-SNAPSHOT
jackson-exceptions
diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Contact.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Contact.java
new file mode 100644
index 0000000000..6417d60310
--- /dev/null
+++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Contact.java
@@ -0,0 +1,15 @@
+package com.baeldung.exceptions;
+
+public class Contact {
+
+ private String email;
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+
+}
diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Person.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Person.java
new file mode 100644
index 0000000000..1572d7a71f
--- /dev/null
+++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/Person.java
@@ -0,0 +1,33 @@
+package com.baeldung.exceptions;
+
+public class Person {
+
+ private String firstName;
+ private String lastName;
+ private String contact;
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getLastName() {
+ return lastName;
+ }
+
+ public void setLastName(String lastName) {
+ this.lastName = lastName;
+ }
+
+ public String getContact() {
+ return contact;
+ }
+
+ public void setContact(String contact) {
+ this.contact = contact;
+ }
+
+}
diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/PersonContact.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/PersonContact.java
new file mode 100644
index 0000000000..0c75240d94
--- /dev/null
+++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/exceptions/PersonContact.java
@@ -0,0 +1,33 @@
+package com.baeldung.exceptions;
+
+public class PersonContact {
+
+ private String firstName;
+ private String lastName;
+ private Contact contact;
+
+ 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 Contact getContact() {
+ return contact;
+ }
+
+ public void setContact(Contact contact) {
+ this.contact = contact;
+ }
+
+}
diff --git a/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/Country.java b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/Country.java
new file mode 100644
index 0000000000..a8e6dfbc94
--- /dev/null
+++ b/jackson-modules/jackson-exceptions/src/main/java/com/baeldung/mappingexception/Country.java
@@ -0,0 +1,26 @@
+package com.baeldung.mappingexception;
+
+import java.util.List;
+
+public class Country {
+
+ private String name;
+ private List cities;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public List getCities() {
+ return cities;
+ }
+
+ public void setCities(List cities) {
+ this.cities = cities;
+ }
+
+}
diff --git a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java
index 38ef3f9390..127d466436 100644
--- a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java
+++ b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/exceptions/JacksonExceptionsUnitTest.java
@@ -3,17 +3,14 @@ package com.baeldung.exceptions;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
-import com.baeldung.exceptions.User;
-import com.baeldung.exceptions.UserWithPrivateFields;
-import com.baeldung.exceptions.UserWithRoot;
-import com.baeldung.exceptions.Zoo;
-import com.baeldung.exceptions.ZooConfigured;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonFactory;
@@ -82,6 +79,32 @@ public class JacksonExceptionsUnitTest {
.readValue(json);
}
+ @Test
+ public void givenJsonObject_whenDeserializingIntoString_thenException() throws IOException {
+ final String json = "{\"firstName\":\"Azhrioun\",\"lastName\":\"Abderrahim\",\"contact\":{\"email\":\"azh@email.com\"}}";
+ final ObjectMapper mapper = new ObjectMapper();
+
+ Exception exception = assertThrows(JsonMappingException.class, () -> mapper.reader()
+ .forType(Person.class)
+ .readValue(json));
+
+ assertTrue(exception.getMessage()
+ .contains("Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)"));
+ }
+
+ @Test
+ public void givenJsonObject_whenDeserializingIntoObject_thenDeserialize() throws IOException {
+ final String json = "{\"firstName\":\"Azhrioun\",\"lastName\":\"Abderrahim\",\"contact\":{\"email\":\"azh@email.com\"}}";
+ final ObjectMapper mapper = new ObjectMapper();
+
+ PersonContact person = mapper.reader()
+ .forType(PersonContact.class)
+ .readValue(json);
+
+ assertEquals("azh@email.com", person.getContact()
+ .getEmail());
+ }
+
@Test
public void givenDefaultConstructor_whenDeserializing_thenCorrect() throws IOException {
final String json = "{\"id\":1,\"name\":\"John\"}";
diff --git a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java
index df35626828..026fd6719f 100644
--- a/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java
+++ b/jackson-modules/jackson-exceptions/src/test/java/com/baeldung/mappingexception/JacksonMappingExceptionUnitTest.java
@@ -1,34 +1,33 @@
package com.baeldung.mappingexception;
import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.Arrays;
-import java.io.IOException;
-import java.util.List;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
-import com.fasterxml.jackson.core.JsonGenerationException;
-import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.module.SimpleModule;
-import com.google.common.collect.Lists;
public class JacksonMappingExceptionUnitTest {
@Test(expected = JsonMappingException.class)
- public final void givenObjectHasNoAccessors_whenSerializing_thenException() throws JsonParseException, IOException {
+ public void givenObjectHasNoAccessors_whenSerializing_thenException() throws JsonProcessingException {
final String dtoAsString = new ObjectMapper().writeValueAsString(new MyDtoNoAccessors());
assertThat(dtoAsString, notNullValue());
}
@Test
- public final void givenObjectHasNoAccessors_whenSerializingWithPrivateFieldsVisibility_thenNoException() throws JsonParseException, IOException {
+ public void givenObjectHasNoAccessors_whenSerializingWithPrivateFieldsVisibility_thenNoException() throws JsonProcessingException {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
final String dtoAsString = objectMapper.writeValueAsString(new MyDtoNoAccessors());
@@ -39,7 +38,7 @@ public class JacksonMappingExceptionUnitTest {
}
@Test
- public final void givenObjectHasNoAccessorsButHasVisibleFields_whenSerializing_thenNoException() throws JsonParseException, IOException {
+ public void givenObjectHasNoAccessorsButHasVisibleFields_whenSerializing_thenNoException() throws JsonProcessingException {
final ObjectMapper objectMapper = new ObjectMapper();
final String dtoAsString = objectMapper.writeValueAsString(new MyDtoNoAccessorsAndFieldVisibility());
@@ -48,4 +47,30 @@ public class JacksonMappingExceptionUnitTest {
assertThat(dtoAsString, containsString("booleanValue"));
}
+ @Test
+ public void givenJsonWithInvalidList_whenDeserializing_thenThrowException() throws JsonProcessingException {
+ final String json = "{\"name\":\"Netherlands\",\"cities\":{\"Amsterdam\", \"Tamassint\"}}";
+ final ObjectMapper mapper = new ObjectMapper();
+
+ Exception exception = assertThrows(JsonMappingException.class, () -> mapper.reader()
+ .forType(Country.class)
+ .readValue(json));
+
+ assertTrue(exception.getMessage()
+ .contains("Cannot deserialize value of type `java.util.ArrayList`"));
+ }
+
+ @Test
+ public void givenJsonWithValidList_whenDeserializing_thenCorrect() throws JsonProcessingException {
+ final String json = "{\"name\":\"Netherlands\",\"cities\":[\"Amsterdam\", \"Tamassint\"]}";
+ final ObjectMapper mapper = new ObjectMapper();
+
+ Country country = mapper.reader()
+ .forType(Country.class)
+ .readValue(json);
+
+ assertEquals("Netherlands", country.getName());
+ assertEquals(Arrays.asList("Amsterdam", "Tamassint"), country.getCities());
+ }
+
}
diff --git a/jackson-modules/pom.xml b/jackson-modules/pom.xml
index 4163d1912f..531d5628f7 100644
--- a/jackson-modules/pom.xml
+++ b/jackson-modules/pom.xml
@@ -24,11 +24,6 @@
-
- com.fasterxml.jackson.core
- jackson-databind
- ${jackson.version}
-
com.fasterxml.jackson.dataformat
diff --git a/jackson-simple/pom.xml b/jackson-simple/pom.xml
index f71cb1ffbf..d1fcc867cf 100644
--- a/jackson-simple/pom.xml
+++ b/jackson-simple/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jackson-simple
- 0.0.1-SNAPSHOT
jackson-simple
@@ -33,4 +32,8 @@
+
+ 2.14.2
+
+
\ No newline at end of file
diff --git a/jackson-simple/src/main/java/com/baeldung/jackson/annotation/BeanWithInclude.java b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/BeanWithInclude.java
new file mode 100644
index 0000000000..18130fc9f2
--- /dev/null
+++ b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/BeanWithInclude.java
@@ -0,0 +1,18 @@
+package com.baeldung.jackson.annotation;
+
+import com.fasterxml.jackson.annotation.JsonIncludeProperties;
+
+@JsonIncludeProperties({ "name" })
+public class BeanWithInclude {
+ public int id;
+ public String name;
+
+ public BeanWithInclude() {
+
+ }
+
+ public BeanWithInclude(final int id, final String name) {
+ this.id = id;
+ this.name = name;
+ }
+}
diff --git a/jackson-simple/src/main/java/com/baeldung/jackson/annotation/GeneralBean.java b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/GeneralBean.java
new file mode 100644
index 0000000000..a8333f54ae
--- /dev/null
+++ b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/GeneralBean.java
@@ -0,0 +1,26 @@
+package com.baeldung.jackson.annotation;
+
+import com.fasterxml.jackson.annotation.JsonValue;
+
+public class GeneralBean {
+ Integer id;
+
+ @JsonValue
+ String name;
+
+ public GeneralBean() {
+ }
+
+ public GeneralBean(Integer id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+}
diff --git a/jackson-simple/src/main/java/com/baeldung/jackson/annotation/PriorityEnum.java b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/PriorityEnum.java
new file mode 100644
index 0000000000..ed74052ede
--- /dev/null
+++ b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/PriorityEnum.java
@@ -0,0 +1,16 @@
+package com.baeldung.jackson.annotation;
+
+import com.fasterxml.jackson.annotation.JsonValue;
+
+public enum PriorityEnum {
+
+ LOW(0), MEDIUM(1), HIGH(3);
+
+ @JsonValue
+ private int level;
+
+ PriorityEnum(int level) {
+ this.level = level;
+ }
+
+}
diff --git a/jackson-simple/src/main/java/com/baeldung/jackson/annotation/dtos/withEnum/TypeEnumWithValue.java b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/dtos/withEnum/TypeEnumWithValue.java
new file mode 100644
index 0000000000..2c8718dfd8
--- /dev/null
+++ b/jackson-simple/src/main/java/com/baeldung/jackson/annotation/dtos/withEnum/TypeEnumWithValue.java
@@ -0,0 +1,23 @@
+package com.baeldung.jackson.annotation.dtos.withEnum;
+
+import com.fasterxml.jackson.annotation.JsonValue;
+
+public enum TypeEnumWithValue {
+ TYPE1(1, "Type A"), TYPE2(2, "Type 2");
+
+ private Integer id;
+
+ @JsonValue
+ private String name;
+
+
+ TypeEnumWithValue(int id, String name) {
+ this.id = id;
+ this.name = name;
+ }
+
+ //@JsonValue
+ public String getName() {
+ return name;
+ }
+}
diff --git a/jackson-simple/src/test/java/com/baeldung/jackson/annotation/JacksonAnnotationUnitTest.java b/jackson-simple/src/test/java/com/baeldung/jackson/annotation/JacksonAnnotationUnitTest.java
index bbbb79b0a8..1a6c7b1286 100644
--- a/jackson-simple/src/test/java/com/baeldung/jackson/annotation/JacksonAnnotationUnitTest.java
+++ b/jackson-simple/src/test/java/com/baeldung/jackson/annotation/JacksonAnnotationUnitTest.java
@@ -20,10 +20,12 @@ import com.baeldung.jackson.annotation.bidirection.UserWithIdentity;
import com.baeldung.jackson.annotation.bidirection.UserWithRef;
import com.baeldung.jackson.annotation.date.EventWithFormat;
import com.baeldung.jackson.annotation.date.EventWithSerializer;
+import com.baeldung.jackson.annotation.dtos.withEnum.TypeEnumWithValue;
import com.baeldung.jackson.annotation.ignore.MyMixInForIgnoreType;
import com.baeldung.jackson.annotation.dtos.withEnum.DistanceEnumWithValue;
import com.baeldung.jackson.annotation.exception.UserWithRoot;
import com.baeldung.jackson.annotation.exception.UserWithRootNamespace;
+import com.baeldung.jackson.annotation.ignore.MyMixInForIgnoreType;
import com.baeldung.jackson.annotation.jsonview.Item;
import com.baeldung.jackson.annotation.jsonview.Views;
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -95,6 +97,14 @@ public class JacksonAnnotationUnitTest {
assertThat(enumAsString, is("1609.34"));
}
+
+ @Test
+ public void whenSerializingFieldUsingJsonValue_thenCorrect() throws IOException {
+ final String enumAsString = new ObjectMapper().writeValueAsString(PriorityEnum.HIGH);
+
+ assertEquals("3", enumAsString);
+ }
+
@Test
public void whenSerializingUsingJsonSerialize_thenCorrect() throws JsonProcessingException, ParseException {
final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
@@ -107,6 +117,19 @@ public class JacksonAnnotationUnitTest {
assertThat(result, containsString(toParse));
}
+ @Test
+ public void whenSerializingUsingJsonValueAnnotatedField_thenCorrect() throws JsonProcessingException {
+ final String enumValue = new ObjectMapper().writeValueAsString(TypeEnumWithValue.TYPE1);
+ assertThat(enumValue, is("\"Type A\""));
+ }
+
+ @Test
+ public void whenSerializingUsingJsonValueAnnotatedFieldInPojo_thenCorrect() throws JsonProcessingException {
+ GeneralBean bean1 = new GeneralBean(1, "Bean 1");
+ final String bean1AsString = new ObjectMapper().writeValueAsString(bean1);
+ assertThat(bean1AsString, is("\"Bean 1\""));
+ }
+
// ========================= Deserializing annotations ============================
@Test
@@ -118,6 +141,7 @@ public class JacksonAnnotationUnitTest {
assertEquals("My bean", bean.name);
}
+
@Test
public void whenDeserializingUsingJsonInject_thenCorrect() throws IOException {
final String json = "{\"name\":\"My bean\"}";
@@ -161,6 +185,23 @@ public class JacksonAnnotationUnitTest {
assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
}
+ @Test
+ public void whenDeserializingUsingJsonValue_thenCorrect() throws JsonProcessingException {
+ final String str = "\"Type A\"";
+ TypeEnumWithValue te = new ObjectMapper().readerFor(TypeEnumWithValue.class)
+ .readValue(str);
+ assertThat(te, is(TypeEnumWithValue.TYPE1));
+ }
+
+ @Test(expected = Exception.class)
+ public void whenDeserializingUsingJsonValueAnnotatedFieldInPojo_thenGetException() throws JsonProcessingException {
+ GeneralBean bean1 = new GeneralBean(1, "Bean 1");
+ final String bean1AsString = new ObjectMapper().writeValueAsString(bean1);
+ GeneralBean bean = new ObjectMapper().readerFor(GeneralBean.class)
+ .readValue(bean1AsString);
+ assertThat(bean.getName(), is(bean1.getName()));
+ }
+
// ========================= Inclusion annotations ============================
@Test
@@ -172,6 +213,15 @@ public class JacksonAnnotationUnitTest {
assertThat(result, not(containsString("id")));
}
+ @Test
+ public void whenSerializingUsingJsonIncludeProperties_thenCorrect() throws JsonProcessingException {
+ final BeanWithInclude bean = new BeanWithInclude(1, "My bean");
+ final String result = new ObjectMapper().writeValueAsString(bean);
+ assertThat(result, containsString("My bean"));
+ assertThat(result, not(containsString("id")));
+ assertThat(result, containsString("name"));
+ }
+
@Test
public void whenSerializingUsingJsonIgnore_thenCorrect() throws JsonProcessingException {
final BeanWithIgnore bean = new BeanWithIgnore(1, "My bean");
@@ -399,7 +449,5 @@ public class JacksonAnnotationUnitTest {
*/
}
-
-
}
diff --git a/java-blockchain/pom.xml b/java-blockchain/pom.xml
index 2279a7ceff..d45d2bf573 100644
--- a/java-blockchain/pom.xml
+++ b/java-blockchain/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.blockchain
java-blockchain
- 0.1.0-SNAPSHOT
java-blockchain
jar
diff --git a/java-jdi/pom.xml b/java-jdi/pom.xml
index a8716de4ee..dded13896f 100644
--- a/java-jdi/pom.xml
+++ b/java-jdi/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
java-jdi
- 0.1.0-SNAPSHOT
java-jdi
jar
@@ -16,13 +15,7 @@
-
- com.sun
- tools
- ${tools.version}
- system
- ${java.home}/../lib/tools.jar
-
+
@@ -33,10 +26,25 @@
true
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ ${maven.compiler.target.version}
+
+ --add-exports=jdk.jdi/com.sun.jdi=ALL-UNNAMED
+
+
+
+
+
- 1.8
+ 17
+ 17
\ No newline at end of file
diff --git a/java-panama/README.md b/java-panama/README.md
new file mode 100644
index 0000000000..9c7d824cad
--- /dev/null
+++ b/java-panama/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Guide to Java Project Panama](https://www.baeldung.com/java-project-panama)
diff --git a/java-panama/pom.xml b/java-panama/pom.xml
new file mode 100644
index 0000000000..7c6b420eeb
--- /dev/null
+++ b/java-panama/pom.xml
@@ -0,0 +1,48 @@
+
+ ${project.model.version}
+ com.baeldung.java.panama
+ java-panama
+ ${project.version}
+ java-panama
+ jar
+
+
+
+ org.junit.jupiter
+ junit-jupiter
+ ${junit.jupiter.version}
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven.compiler.version}
+
+
+ ${maven.compiler.target}
+
+ --add-opens=java.base/java.lang.foreign=ALL-UNNAMED
+ --enable-preview
+
+
+
+
+
+
+
+ 4.0.0
+ UTF-8
+ 1.0
+ 19
+ 19
+ 3.10.1
+ 5.9.0
+
+
+
diff --git a/java-panama/src/main/java/com/baeldung/java/panama/core/Greetings.java b/java-panama/src/main/java/com/baeldung/java/panama/core/Greetings.java
new file mode 100644
index 0000000000..1937bd65e9
--- /dev/null
+++ b/java-panama/src/main/java/com/baeldung/java/panama/core/Greetings.java
@@ -0,0 +1,40 @@
+package com.baeldung.java.panama.core;
+
+import static java.lang.foreign.ValueLayout.ADDRESS;
+import static java.lang.foreign.ValueLayout.JAVA_INT;
+
+import java.lang.foreign.FunctionDescriptor;
+import java.lang.foreign.Linker;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.MemorySession;
+import java.lang.foreign.SymbolLookup;
+import java.lang.invoke.MethodHandle;
+
+public class Greetings {
+
+ public static void main(String[] args) throws Throwable {
+
+ String symbolName = "printf";
+ String greeting = "Hello World from Project Panama Baeldung Article";
+
+ Linker nativeLinker = Linker.nativeLinker();
+ SymbolLookup stdlibLookup = nativeLinker.defaultLookup();
+ SymbolLookup loaderLookup = SymbolLookup.loaderLookup();
+
+ FunctionDescriptor descriptor = FunctionDescriptor.of(JAVA_INT, ADDRESS);
+
+ MethodHandle methodHandle = loaderLookup.lookup(symbolName)
+ .or(() -> stdlibLookup.lookup(symbolName))
+ .map(symbolSegment -> nativeLinker.downcallHandle(symbolSegment, descriptor))
+ .orElse(null);
+
+ if (methodHandle == null) {
+ throw new NoSuchMethodError("Method Handle was not found");
+ }
+
+ try (MemorySession memorySession = MemorySession.openConfined()) {
+ MemorySegment greetingSegment = memorySession.allocateUtf8String(greeting);
+ methodHandle.invoke(greetingSegment);
+ }
+ }
+}
diff --git a/java-panama/src/main/java/com/baeldung/java/panama/core/MemoryAllocation.java b/java-panama/src/main/java/com/baeldung/java/panama/core/MemoryAllocation.java
new file mode 100644
index 0000000000..239b25b69e
--- /dev/null
+++ b/java-panama/src/main/java/com/baeldung/java/panama/core/MemoryAllocation.java
@@ -0,0 +1,23 @@
+package com.baeldung.java.panama.core;
+
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.MemorySession;
+import java.lang.foreign.SegmentAllocator;
+import java.lang.foreign.ValueLayout;
+
+public class MemoryAllocation {
+
+ public static void main(String[] args) throws Throwable {
+
+ try (MemorySession session = MemorySession.openConfined()) {
+ String[] greetingStrings = { "hello", "world", "panama", "baeldung" };
+ SegmentAllocator allocator = SegmentAllocator.implicitAllocator();
+ MemorySegment offHeapSegment = allocator.allocateArray(ValueLayout.ADDRESS, greetingStrings.length);
+ for (int i = 0; i < greetingStrings.length; i++) {
+ // Allocate a string off-heap, then store a pointer to it
+ MemorySegment cString = allocator.allocateUtf8String(greetingStrings[i]);
+ offHeapSegment.setAtIndex(ValueLayout.ADDRESS, i, cString);
+ }
+ }
+ }
+}
diff --git a/java-panama/src/main/java/com/baeldung/java/panama/core/MemoryLayout.java b/java-panama/src/main/java/com/baeldung/java/panama/core/MemoryLayout.java
new file mode 100644
index 0000000000..612997e35e
--- /dev/null
+++ b/java-panama/src/main/java/com/baeldung/java/panama/core/MemoryLayout.java
@@ -0,0 +1,53 @@
+package com.baeldung.java.panama.core;
+
+import static java.lang.foreign.MemoryLayout.sequenceLayout;
+import static java.lang.foreign.MemoryLayout.structLayout;
+import static java.lang.foreign.ValueLayout.JAVA_DOUBLE;
+import static java.lang.foreign.ValueLayout.JAVA_FLOAT;
+import static java.lang.foreign.ValueLayout.PathElement;
+
+import java.lang.foreign.GroupLayout;
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.MemorySession;
+import java.lang.foreign.SequenceLayout;
+import java.lang.invoke.VarHandle;
+
+public class MemoryLayout {
+
+ public static void main(String[] args) {
+
+ GroupLayout pointLayout = structLayout(JAVA_DOUBLE.withName("x"), JAVA_DOUBLE.withName("y"));
+
+ SequenceLayout ptsLayout = sequenceLayout(10, pointLayout);
+
+ VarHandle xvarHandle = pointLayout.varHandle(PathElement.groupElement("x"));
+ VarHandle yvarHandle = pointLayout.varHandle(PathElement.groupElement("y"));
+
+ try (MemorySession memorySession = MemorySession.openConfined()) {
+
+ MemorySegment pointSegment = memorySession.allocate(pointLayout);
+ xvarHandle.set(pointSegment, 3d);
+ yvarHandle.set(pointSegment, 4d);
+
+ System.out.println(pointSegment.toString());
+
+ }
+
+ }
+
+ static class ValueLayout {
+
+ public static void main(String[] args) {
+
+ try (MemorySession memorySession = MemorySession.openConfined()) {
+ int byteSize = 5;
+ int index = 3;
+ float value = 6;
+ MemorySegment segment = MemorySegment.allocateNative(byteSize, memorySession);
+ segment.setAtIndex(JAVA_FLOAT, index, value);
+ float result = segment.getAtIndex(JAVA_FLOAT, index);
+ System.out.println("Float value is:" + result);
+ }
+ }
+ }
+}
diff --git a/java-panama/src/main/java/com/baeldung/java/panama/jextract/Greetings.java b/java-panama/src/main/java/com/baeldung/java/panama/jextract/Greetings.java
new file mode 100644
index 0000000000..43b575d52a
--- /dev/null
+++ b/java-panama/src/main/java/com/baeldung/java/panama/jextract/Greetings.java
@@ -0,0 +1,19 @@
+package com.baeldung.java.panama.jextract;
+
+import java.lang.foreign.MemorySegment;
+import java.lang.foreign.MemorySession;
+// Generate JExtract bindings before uncommenting
+// import static foreign.c.stdio_h.printf;
+
+public class Greetings {
+
+ public static void main(String[] args) {
+ String greeting = "Hello World from Project Panama Baeldung Article, using JExtract!";
+
+ try (MemorySession memorySession = MemorySession.openConfined()) {
+ MemorySegment greetingSegment = memorySession.allocateUtf8String(greeting);
+ // Generate JExtract bingings before uncommenting
+ // printf(greetingSegment);
+ }
+ }
+}
diff --git a/java-panama/src/main/resources/hello.c b/java-panama/src/main/resources/hello.c
new file mode 100644
index 0000000000..3f2d3fce6a
--- /dev/null
+++ b/java-panama/src/main/resources/hello.c
@@ -0,0 +1,5 @@
+#include
+int main() {
+ printf("Hello World from Project Panama Baeldung Article");
+ return 0;
+}
\ No newline at end of file
diff --git a/java-rmi/pom.xml b/java-rmi/pom.xml
index fee5107423..2256883f84 100644
--- a/java-rmi/pom.xml
+++ b/java-rmi/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.rmi
java-rmi
- 1.0-SNAPSHOT
java-rmi
jar
diff --git a/java-websocket/pom.xml b/java-websocket/pom.xml
index ffc2b0631e..7c5c006aa9 100644
--- a/java-websocket/pom.xml
+++ b/java-websocket/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
java-websocket
- 0.0.1-SNAPSHOT
java-websocket
war
@@ -31,6 +30,7 @@
1.1
2.8.0
+ 3.3.2
\ No newline at end of file
diff --git a/javafx/pom.xml b/javafx/pom.xml
index 9b0b6002a8..69855a9494 100644
--- a/javafx/pom.xml
+++ b/javafx/pom.xml
@@ -12,4 +12,35 @@
1.0.0-SNAPSHOT
+
+
+ org.openjfx
+ javafx-controls
+ ${javafx.version}
+
+
+ org.openjfx
+ javafx-fxml
+ ${javafx.version}
+
+
+
+
+
+
+ org.openjfx
+ javafx-maven-plugin
+ ${javafx-maven-plugin.version}
+
+ Main
+
+
+
+
+
+
+ 19
+ 0.0.8
+
+
\ No newline at end of file
diff --git a/javax-sound/pom.xml b/javax-sound/pom.xml
index dcd08cbcb8..6652022a40 100644
--- a/javax-sound/pom.xml
+++ b/javax-sound/pom.xml
@@ -5,7 +5,6 @@
4.0.0
com.baeldung.javax-sound
javax-sound
- 1.0-SNAPSHOT
javax-sound
jar
diff --git a/javax-validation-advanced/pom.xml b/javax-validation-advanced/pom.xml
index 39da166071..7709f37883 100644
--- a/javax-validation-advanced/pom.xml
+++ b/javax-validation-advanced/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
javax-validation-advanced
- 0.1-SNAPSHOT
javax-validation-advanced
diff --git a/javaxval-2/README.md b/javaxval-2/README.md
index 52c9b42ac4..0fd5ce163b 100644
--- a/javaxval-2/README.md
+++ b/javaxval-2/README.md
@@ -4,7 +4,6 @@ This module contains articles about Bean Validation.
### Relevant Articles:
- [Method Constraints with Bean Validation 2.0](https://www.baeldung.com/javax-validation-method-constraints)
-- [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank)
- [Guide to ParameterMessageInterpolator](https://www.baeldung.com/hibernate-parametermessageinterpolator)
- [Hibernate Validator Annotation Processor in Depth](https://www.baeldung.com/hibernate-validator-annotation-processor)
- More articles: [[<-- prev]](../javaxval)
\ No newline at end of file
diff --git a/javaxval/README.md b/javaxval/README.md
index 95d9410fff..b7e19d5794 100644
--- a/javaxval/README.md
+++ b/javaxval/README.md
@@ -10,4 +10,5 @@ This module contains articles about Bean Validation.
- [Grouping Javax Validation Constraints](https://www.baeldung.com/javax-validation-groups)
- [Constraint Composition with Bean Validation](https://www.baeldung.com/java-bean-validation-constraint-composition)
- [Using @NotNull on a Method Parameter](https://www.baeldung.com/java-notnull-method-parameter)
+- [Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation](https://www.baeldung.com/java-bean-validation-not-null-empty-blank)
- More articles: [[next -->]](../javaxval-2)
\ No newline at end of file
diff --git a/javaxval/pom.xml b/javaxval/pom.xml
index 1feed71abb..bececb2ea7 100644
--- a/javaxval/pom.xml
+++ b/javaxval/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
javaxval
- 0.1-SNAPSHOT
javaxval
@@ -14,26 +13,6 @@
-
- org.hibernate.validator
- hibernate-validator
- ${hibernate-validator.version}
-
-
- org.glassfish
- javax.el
- ${javax.el.version}
-
-
- org.springframework
- spring-context
- ${org.springframework.version}
-
-
- org.springframework
- spring-test
- ${org.springframework.version}
-
org.springframework.boot
spring-boot-starter-validation
@@ -46,7 +25,7 @@
test
-
+
@@ -58,11 +37,8 @@
- 6.2.3.Final
6.2.0.Final
- 3.0.0
- 5.3.21
- 2.7.1
+ 3.0.4
\ No newline at end of file
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/beanvalidation/User.java b/javaxval/src/main/java/com/baeldung/javaxval/beanvalidation/User.java
index d583ac51d2..7305b6c201 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/beanvalidation/User.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/beanvalidation/User.java
@@ -4,14 +4,14 @@ import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
-import javax.validation.constraints.AssertTrue;
-import javax.validation.constraints.Email;
-import javax.validation.constraints.Max;
-import javax.validation.constraints.Min;
-import javax.validation.constraints.NotBlank;
-import javax.validation.constraints.NotNull;
-import javax.validation.constraints.Past;
-import javax.validation.constraints.Size;
+import jakarta.validation.constraints.AssertTrue;
+import jakarta.validation.constraints.Email;
+import jakarta.validation.constraints.Max;
+import jakarta.validation.constraints.Min;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Past;
+import jakarta.validation.constraints.Size;
public class User {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/bigdecimal/Invoice.java b/javaxval/src/main/java/com/baeldung/javaxval/bigdecimal/Invoice.java
index c14a6bd2b1..c946a8df68 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/bigdecimal/Invoice.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/bigdecimal/Invoice.java
@@ -2,8 +2,8 @@ package com.baeldung.javaxval.bigdecimal;
import java.math.BigDecimal;
-import javax.validation.constraints.DecimalMin;
-import javax.validation.constraints.Digits;
+import jakarta.validation.constraints.DecimalMin;
+import jakarta.validation.constraints.Digits;
public class Invoice {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/AlphanumericReturnValue.java b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/AlphanumericReturnValue.java
index 6e3408712b..65f6eceb34 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/AlphanumericReturnValue.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/AlphanumericReturnValue.java
@@ -2,12 +2,12 @@ package com.baeldung.javaxval.constraint.composition;
import org.hibernate.validator.constraints.Length;
-import javax.validation.Constraint;
-import javax.validation.Payload;
-import javax.validation.constraints.NotNull;
-import javax.validation.constraints.Pattern;
-import javax.validation.constraintvalidation.SupportedValidationTarget;
-import javax.validation.constraintvalidation.ValidationTarget;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Pattern;
+import jakarta.validation.constraintvalidation.SupportedValidationTarget;
+import jakarta.validation.constraintvalidation.ValidationTarget;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumeric.java b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumeric.java
index 916b4e36a4..9d4d4995c5 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumeric.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumeric.java
@@ -11,10 +11,10 @@ import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import javax.validation.Constraint;
-import javax.validation.Payload;
-import javax.validation.constraints.NotNull;
-import javax.validation.constraints.Pattern;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumericWithSingleViolation.java b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumericWithSingleViolation.java
index edc5b6af3e..31eca29a07 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumericWithSingleViolation.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidAlphanumericWithSingleViolation.java
@@ -11,11 +11,11 @@ import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import javax.validation.Constraint;
-import javax.validation.Payload;
-import javax.validation.ReportAsSingleViolation;
-import javax.validation.constraints.NotNull;
-import javax.validation.constraints.Pattern;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
+import jakarta.validation.ReportAsSingleViolation;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidLengthOrNumericCharacter.java b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidLengthOrNumericCharacter.java
index 444cb4a63a..9f46e1e7b8 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidLengthOrNumericCharacter.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/constraint/composition/ValidLengthOrNumericCharacter.java
@@ -4,9 +4,9 @@ import org.hibernate.validator.constraints.CompositionType;
import org.hibernate.validator.constraints.ConstraintComposition;
import org.hibernate.validator.constraints.Length;
-import javax.validation.Constraint;
-import javax.validation.Payload;
-import javax.validation.constraints.Pattern;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
+import jakarta.validation.constraints.Pattern;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java
index 03811635ee..c0b23f0ae8 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/Customer.java
@@ -4,9 +4,9 @@ import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
-import javax.validation.constraints.Min;
-import javax.validation.constraints.NotBlank;
-import javax.validation.constraints.PositiveOrZero;
+import jakarta.validation.constraints.Min;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.PositiveOrZero;
public class Customer {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/CustomerMap.java b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/CustomerMap.java
index 554285fbae..902f04c654 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/CustomerMap.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/CustomerMap.java
@@ -2,8 +2,8 @@ package com.baeldung.javaxval.container.validation;
import java.util.Map;
-import javax.validation.constraints.Email;
-import javax.validation.constraints.NotNull;
+import jakarta.validation.constraints.Email;
+import jakarta.validation.constraints.NotNull;
public class CustomerMap {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java
index 03e0c7aac4..a3a21fe88b 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/container/validation/valueextractors/ProfileValueExtractor.java
@@ -1,8 +1,8 @@
package com.baeldung.javaxval.container.validation.valueextractors;
-import javax.validation.valueextraction.ExtractedValue;
-import javax.validation.valueextraction.UnwrapByDefault;
-import javax.validation.valueextraction.ValueExtractor;
+import jakarta.validation.valueextraction.ExtractedValue;
+import jakarta.validation.valueextraction.UnwrapByDefault;
+import jakarta.validation.valueextraction.ValueExtractor;
import com.baeldung.javaxval.container.validation.Profile;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java
index c91f449bad..da86ec6c89 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidator.java
@@ -2,8 +2,8 @@ package com.baeldung.javaxval.enums;
import java.util.Arrays;
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
+import jakarta.validation.ConstraintValidator;
+import jakarta.validation.ConstraintValidatorContext;
import com.baeldung.javaxval.enums.constraints.CustomerTypeSubset;
import com.baeldung.javaxval.enums.demo.CustomerType;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumNamePatternValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumNamePatternValidator.java
index 3d56d40563..5cce8e10e7 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumNamePatternValidator.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumNamePatternValidator.java
@@ -4,8 +4,8 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
+import jakarta.validation.ConstraintValidator;
+import jakarta.validation.ConstraintValidatorContext;
import com.baeldung.javaxval.enums.constraints.EnumNamePattern;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumSubSetValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumSubSetValidator.java
index 04cccb8b0c..a3a92a4f4e 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumSubSetValidator.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/EnumSubSetValidator.java
@@ -3,8 +3,8 @@ package com.baeldung.javaxval.enums;
import java.lang.annotation.Annotation;
import java.util.Arrays;
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
+import jakarta.validation.ConstraintValidator;
+import jakarta.validation.ConstraintValidatorContext;
public abstract class EnumSubSetValidator implements ConstraintValidator {
private U[] subset;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/ValueOfEnumValidator.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/ValueOfEnumValidator.java
index 0203d63923..c2f2ecee3b 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/ValueOfEnumValidator.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/ValueOfEnumValidator.java
@@ -4,8 +4,8 @@ import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
+import jakarta.validation.ConstraintValidator;
+import jakarta.validation.ConstraintValidatorContext;
import com.baeldung.javaxval.enums.constraints.ValueOfEnum;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java
index 97c2137f6a..fe03e228f6 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/CustomerTypeSubset.java
@@ -12,8 +12,8 @@ import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import javax.validation.Constraint;
-import javax.validation.Payload;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
import com.baeldung.javaxval.enums.CustomerTypeSubSetValidator;
import com.baeldung.javaxval.enums.demo.CustomerType;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/EnumNamePattern.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/EnumNamePattern.java
index 29fff857c8..4ef1eac9c0 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/EnumNamePattern.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/EnumNamePattern.java
@@ -12,8 +12,8 @@ import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import javax.validation.Constraint;
-import javax.validation.Payload;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
import com.baeldung.javaxval.enums.EnumNamePatternValidator;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/ValueOfEnum.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/ValueOfEnum.java
index 29b44a1793..bbfe6ed5ab 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/ValueOfEnum.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/constraints/ValueOfEnum.java
@@ -12,8 +12,8 @@ import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import javax.validation.Constraint;
-import javax.validation.Payload;
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
import com.baeldung.javaxval.enums.ValueOfEnumValidator;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/Customer.java b/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/Customer.java
index 15cd9e0da7..db38dd0015 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/Customer.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/enums/demo/Customer.java
@@ -1,6 +1,6 @@
package com.baeldung.javaxval.enums.demo;
-import javax.validation.constraints.NotNull;
+import jakarta.validation.constraints.NotNull;
import com.baeldung.javaxval.enums.constraints.CustomerTypeSubset;
import com.baeldung.javaxval.enums.constraints.EnumNamePattern;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/application/Application.java b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/application/Application.java
index 22157f351c..b1c53c5be3 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/application/Application.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/application/Application.java
@@ -1,7 +1,7 @@
package com.baeldung.javaxval.javabeanconstraints.application;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import com.baeldung.javaxval.javabeanconstraints.entities.UserNotBlank;
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java
index 5542be8c25..1a6c634ed4 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotBlank.java
@@ -1,6 +1,6 @@
package com.baeldung.javaxval.javabeanconstraints.entities;
-import javax.validation.constraints.NotBlank;
+import jakarta.validation.constraints.NotBlank;
public class UserNotBlank {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java
index e3dbe27b0e..0e01c41388 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotEmpty.java
@@ -1,6 +1,6 @@
package com.baeldung.javaxval.javabeanconstraints.entities;
-import javax.validation.constraints.NotEmpty;
+import jakarta.validation.constraints.NotEmpty;
public class UserNotEmpty {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java
index b3a0f90d36..39164e2f6b 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/javabeanconstraints/entities/UserNotNull.java
@@ -1,6 +1,6 @@
package com.baeldung.javaxval.javabeanconstraints.entities;
-import javax.validation.constraints.NotNull;
+import jakarta.validation.constraints.NotNull;
public class UserNotNull {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/CompleteInfo.java b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/CompleteInfo.java
index 4ecdc3c5f1..22c0b01ddf 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/CompleteInfo.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/CompleteInfo.java
@@ -1,6 +1,6 @@
package com.baeldung.javaxval.validationgroup;
-import javax.validation.GroupSequence;
+import jakarta.validation.GroupSequence;
@GroupSequence({ BasicInfo.class, AdvanceInfo.class })
public interface CompleteInfo {
diff --git a/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/RegistrationForm.java b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/RegistrationForm.java
index a30a074556..2f759d633d 100644
--- a/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/RegistrationForm.java
+++ b/javaxval/src/main/java/com/baeldung/javaxval/validationgroup/RegistrationForm.java
@@ -1,7 +1,7 @@
package com.baeldung.javaxval.validationgroup;
-import javax.validation.constraints.Email;
-import javax.validation.constraints.NotBlank;
+import jakarta.validation.constraints.Email;
+import jakarta.validation.constraints.NotBlank;
public class RegistrationForm {
@NotBlank(groups = BasicInfo.class)
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java b/javaxval/src/test/java/com/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java
index 3e60fa7acd..132dddad5d 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/beanvalidation/ValidationIntegrationTest.java
@@ -6,10 +6,10 @@ import java.time.LocalDate;
import java.util.Collections;
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
-import javax.validation.ValidatorFactory;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
+import jakarta.validation.ValidatorFactory;
import org.junit.Before;
import org.junit.Test;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java
index 801d7966a5..a149a3a6fe 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/bigdecimal/InvoiceUnitTest.java
@@ -4,9 +4,9 @@ import com.baeldung.javaxval.LocaleAwareUnitTest;
import org.junit.BeforeClass;
import org.junit.Test;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import java.math.BigDecimal;
import java.util.Set;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/constraint/composition/ConstraintCompositionUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/constraint/composition/ConstraintCompositionUnitTest.java
index 6c2b8f801c..918944cd5f 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/constraint/composition/ConstraintCompositionUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/constraint/composition/ConstraintCompositionUnitTest.java
@@ -5,11 +5,11 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.ConstraintViolationException;
-import javax.validation.Validation;
-import javax.validation.Validator;
-import javax.validation.ValidatorFactory;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.ConstraintViolationException;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
+import jakarta.validation.ValidatorFactory;
import org.junit.Before;
import org.junit.Test;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java b/javaxval/src/test/java/com/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java
index d96b641442..5c50fde7c6 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/container/validation/ContainerValidationIntegrationTest.java
@@ -6,10 +6,10 @@ import java.util.Collections;
import java.util.OptionalInt;
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
-import javax.validation.ValidatorFactory;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
+import jakarta.validation.ValidatorFactory;
import com.baeldung.javaxval.container.validation.valueextractors.ProfileValueExtractor;
import org.junit.Before;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java
index 524f8eec36..7ccd840e8c 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/enums/CustomerTypeSubSetValidatorUnitTest.java
@@ -4,9 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import org.junit.BeforeClass;
import org.junit.Test;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java
index 805d40ee5e..0556f88832 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/enums/EnumNamePatternValidatorUnitTest.java
@@ -6,9 +6,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import org.junit.BeforeClass;
import org.junit.Test;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java
index 150da5d83b..c7eb740d86 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/enums/ValueOfEnumValidatorUnitTest.java
@@ -4,9 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import org.junit.BeforeClass;
import org.junit.Test;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/enums/demo/CustomerUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/enums/demo/CustomerUnitTest.java
index 02a49f50fa..c4380f75fa 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/enums/demo/CustomerUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/enums/demo/CustomerUnitTest.java
@@ -5,9 +5,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
import java.util.function.Predicate;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import org.junit.BeforeClass;
import org.junit.Test;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotBlankUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotBlankUnitTest.java
index 4cb87e8e27..68e48de41d 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotBlankUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotBlankUnitTest.java
@@ -4,9 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import com.baeldung.javaxval.javabeanconstraints.entities.UserNotBlank;
import org.junit.BeforeClass;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotEmptyUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotEmptyUnitTest.java
index eb76ac260c..bd83d30601 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotEmptyUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotEmptyUnitTest.java
@@ -4,9 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import com.baeldung.javaxval.javabeanconstraints.entities.UserNotEmpty;
import org.junit.BeforeClass;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotNullUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotNullUnitTest.java
index f0280000de..36874f4f21 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotNullUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/javabeanconstraints/UserNotNullUnitTest.java
@@ -4,9 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import com.baeldung.javaxval.javabeanconstraints.entities.UserNotNull;
import org.junit.BeforeClass;
diff --git a/javaxval/src/test/java/com/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java
index 3333703328..52aadf80b0 100644
--- a/javaxval/src/test/java/com/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java
+++ b/javaxval/src/test/java/com/baeldung/javaxval/validationgroup/RegistrationFormUnitTest.java
@@ -4,9 +4,9 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
import org.junit.BeforeClass;
import org.junit.Test;
diff --git a/jaxb/pom.xml b/jaxb/pom.xml
index 183f7f13cb..ac448d2d62 100644
--- a/jaxb/pom.xml
+++ b/jaxb/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jaxb
- 0.0.1-SNAPSHOT
jaxb
@@ -25,6 +24,11 @@
commons-lang3
${commons-lang3.version}
+
+ org.glassfish.jaxb
+ jaxb-runtime
+ ${jaxb-runtime.version}
+
@@ -97,8 +101,9 @@
- 2.3
+ 3.1.0
1.0.0
+ 4.0.0
\ No newline at end of file
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/Book.java b/jaxb/src/main/java/com/baeldung/jaxb/Book.java
index b7a5d39ce5..8c78e0f8b0 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/Book.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/Book.java
@@ -2,11 +2,11 @@ package com.baeldung.jaxb;
import java.util.Date;
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlTransient;
-import javax.xml.bind.annotation.XmlType;
+import jakarta.xml.bind.annotation.XmlAttribute;
+import jakarta.xml.bind.annotation.XmlElement;
+import jakarta.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.XmlTransient;
+import jakarta.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/DateAdapter.java b/jaxb/src/main/java/com/baeldung/jaxb/DateAdapter.java
index 6631525619..418f88065f 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/DateAdapter.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/DateAdapter.java
@@ -4,7 +4,7 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
-import javax.xml.bind.annotation.adapters.XmlAdapter;
+import jakarta.xml.bind.annotation.adapters.XmlAdapter;
public class DateAdapter extends XmlAdapter {
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/Book.java b/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/Book.java
index 0625c58344..c61220dd55 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/Book.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/Book.java
@@ -1,9 +1,11 @@
package com.baeldung.jaxb.dateunmarshalling;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.datatype.XMLGregorianCalendar;
+import jakarta.xml.bind.annotation.XmlElement;
+import jakarta.xml.bind.annotation.XmlRootElement;
+
+
@XmlRootElement(name = "book")
public class Book {
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/BookDateAdapter.java b/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/BookDateAdapter.java
index c882f37a04..4ecc041d35 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/BookDateAdapter.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/BookDateAdapter.java
@@ -1,8 +1,8 @@
package com.baeldung.jaxb.dateunmarshalling;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+import jakarta.xml.bind.annotation.XmlElement;
+import jakarta.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.Date;
@XmlRootElement(name = "book")
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/BookLocalDateTimeAdapter.java b/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/BookLocalDateTimeAdapter.java
index 53a780a87a..3d3e988c98 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/BookLocalDateTimeAdapter.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/BookLocalDateTimeAdapter.java
@@ -1,8 +1,8 @@
package com.baeldung.jaxb.dateunmarshalling;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+import jakarta.xml.bind.annotation.XmlElement;
+import jakarta.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.time.LocalDateTime;
@XmlRootElement(name = "book")
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/DateAdapter.java b/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/DateAdapter.java
index 3b0fd0bd26..27484976a4 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/DateAdapter.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/DateAdapter.java
@@ -1,6 +1,6 @@
package com.baeldung.jaxb.dateunmarshalling;
-import javax.xml.bind.annotation.adapters.XmlAdapter;
+import jakarta.xml.bind.annotation.adapters.XmlAdapter;
import java.text.SimpleDateFormat;
import java.util.Date;
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/JaxbDateUnmarshalling.java b/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/JaxbDateUnmarshalling.java
index 205859b2bf..311156d265 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/JaxbDateUnmarshalling.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/JaxbDateUnmarshalling.java
@@ -1,8 +1,8 @@
package com.baeldung.jaxb.dateunmarshalling;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Unmarshaller;
import java.io.InputStream;
public class JaxbDateUnmarshalling {
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/LocalDateTimeAdapter.java b/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/LocalDateTimeAdapter.java
index 7fa224334c..5ace605593 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/LocalDateTimeAdapter.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/dateunmarshalling/LocalDateTimeAdapter.java
@@ -1,6 +1,6 @@
package com.baeldung.jaxb.dateunmarshalling;
-import javax.xml.bind.annotation.adapters.XmlAdapter;
+import jakarta.xml.bind.annotation.adapters.XmlAdapter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java
index 0a3da677ce..132c41dbb3 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/ObjectFactory.java
@@ -1,7 +1,7 @@
package com.baeldung.jaxb.gen;
-import javax.xml.bind.annotation.XmlRegistry;
+import jakarta.xml.bind.annotation.XmlRegistry;
/**
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java
index 1c1abc61a6..7ba9064e9e 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserRequest.java
@@ -2,11 +2,11 @@
package com.baeldung.jaxb.gen;
import java.io.Serializable;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlType;
+import jakarta.xml.bind.annotation.XmlAccessType;
+import jakarta.xml.bind.annotation.XmlAccessorType;
+import jakarta.xml.bind.annotation.XmlElement;
+import jakarta.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.XmlType;
/**
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java
index b80405e4a9..f35b001a68 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/UserResponse.java
@@ -3,13 +3,13 @@ package com.baeldung.jaxb.gen;
import java.io.Serializable;
import java.util.Calendar;
-import javax.xml.bind.annotation.XmlAccessType;
-import javax.xml.bind.annotation.XmlAccessorType;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlSchemaType;
-import javax.xml.bind.annotation.XmlType;
-import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
+import jakarta.xml.bind.annotation.XmlAccessType;
+import jakarta.xml.bind.annotation.XmlAccessorType;
+import jakarta.xml.bind.annotation.XmlElement;
+import jakarta.xml.bind.annotation.XmlRootElement;
+import jakarta.xml.bind.annotation.XmlSchemaType;
+import jakarta.xml.bind.annotation.XmlType;
+import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.w3._2001.xmlschema.Adapter1;
diff --git a/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java b/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java
index 639d00179c..1818dc82fe 100644
--- a/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java
+++ b/jaxb/src/main/java/com/baeldung/jaxb/gen/package-info.java
@@ -1,2 +1,2 @@
-@javax.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
+@jakarta.xml.bind.annotation.XmlSchema(namespace = "http://www.baeldung.com/jaxb/gen", elementFormDefault = jakarta.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.baeldung.jaxb.gen;
diff --git a/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java b/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java
index 54b3c360dc..1607fa7dce 100644
--- a/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java
+++ b/jaxb/src/main/java/org/w3/_2001/xmlschema/Adapter1.java
@@ -2,7 +2,7 @@
package org.w3._2001.xmlschema;
import java.util.Calendar;
-import javax.xml.bind.annotation.adapters.XmlAdapter;
+import jakarta.xml.bind.annotation.adapters.XmlAdapter;
public class Adapter1
extends XmlAdapter
@@ -10,14 +10,14 @@ public class Adapter1
public Calendar unmarshal(String value) {
- return (javax.xml.bind.DatatypeConverter.parseDateTime(value));
+ return (jakarta.xml.bind.DatatypeConverter.parseDateTime(value));
}
public String marshal(Calendar value) {
if (value == null) {
return null;
}
- return (javax.xml.bind.DatatypeConverter.printDateTime(value));
+ return (jakarta.xml.bind.DatatypeConverter.printDateTime(value));
}
}
diff --git a/jaxb/src/main/resources/global.xjb b/jaxb/src/main/resources/global.xjb
index de9dcf1577..3cda00b31a 100644
--- a/jaxb/src/main/resources/global.xjb
+++ b/jaxb/src/main/resources/global.xjb
@@ -1,5 +1,5 @@
-
@@ -7,7 +7,7 @@
+ parseMethod="jakarta.xml.bind.DatatypeConverter.parseDateTime"
+ printMethod="jakarta.xml.bind.DatatypeConverter.printDateTime" />
\ No newline at end of file
diff --git a/jaxb/src/test/java/com/baeldung/jaxb/dateunmarshalling/JaxbDateUnmarshallingUnitTest.java b/jaxb/src/test/java/com/baeldung/jaxb/dateunmarshalling/JaxbDateUnmarshallingUnitTest.java
index 298034be3d..7862a8194f 100644
--- a/jaxb/src/test/java/com/baeldung/jaxb/dateunmarshalling/JaxbDateUnmarshallingUnitTest.java
+++ b/jaxb/src/test/java/com/baeldung/jaxb/dateunmarshalling/JaxbDateUnmarshallingUnitTest.java
@@ -2,7 +2,7 @@ package com.baeldung.jaxb.dateunmarshalling;
import org.junit.Test;
-import javax.xml.bind.JAXBException;
+import jakarta.xml.bind.JAXBException;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
diff --git a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java
index 77b7f1a0b3..9117bb621e 100644
--- a/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java
+++ b/jaxb/src/test/java/com/baeldung/jaxb/test/JaxbIntegrationTest.java
@@ -6,10 +6,10 @@ import java.io.IOException;
import java.util.Date;
import java.util.TimeZone;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-import javax.xml.bind.Unmarshaller;
+import jakarta.xml.bind.JAXBContext;
+import jakarta.xml.bind.JAXBException;
+import jakarta.xml.bind.Marshaller;
+import jakarta.xml.bind.Unmarshaller;
import org.apache.commons.io.FileUtils;
import org.junit.Assert;
@@ -48,7 +48,7 @@ public class JaxbIntegrationTest {
}
@Test
- public void unMashal() throws JAXBException, IOException {
+ public void unmarshal() throws JAXBException, IOException {
Unmarshaller unmarshaller = context.createUnmarshaller();
String bookFile = this.getClass().getResource("/book.xml").getFile();
Book unMarshallerbook = (Book) unmarshaller.unmarshal(new FileReader(bookFile));
diff --git a/jenkins-modules/jenkins-jobs/README.md b/jenkins-modules/jenkins-jobs/README.md
index d29a25244f..e6de0d57e0 100644
--- a/jenkins-modules/jenkins-jobs/README.md
+++ b/jenkins-modules/jenkins-jobs/README.md
@@ -3,3 +3,5 @@
- [Fixing the “No Such DSL method” Error in Jenkins Pipeline](https://www.baeldung.com/ops/jenkins-pipeline-no-such-dsl-method-error)
- [Jenkins Pipeline – Change to Another Folder](https://www.baeldung.com/ops/jenkins-pipeline-change-to-another-folder)
- [How to Stop a Zombie Job on Jenkins Without Restarting the Server?](https://www.baeldung.com/ops/stop-zombie-job-on-jenkins-without-restarting-the-server)
+- [Running Stages in Parallel With Jenkins Workflow / Pipeline](https://www.baeldung.com/ops/running-stages-in-parallel-jenkins-workflow-pipeline)
+- [Skip a Stage in a Jenkins Pipeline](https://www.baeldung.com/ops/jenkins-pipeline-skip-stage)
diff --git a/jenkins-modules/jenkins-jobs/output-job/pipeline-command-substitution-job b/jenkins-modules/jenkins-jobs/output-job/pipeline-command-substitution-job
new file mode 100644
index 0000000000..acaacfa867
--- /dev/null
+++ b/jenkins-modules/jenkins-jobs/output-job/pipeline-command-substitution-job
@@ -0,0 +1,13 @@
+pipeline {
+ agent any
+ stages {
+ stage('Example') {
+ steps {
+ script {
+ def output = sh(script: "echo \$(ls)", returnStdout: true)
+ echo "Output: ${output}"
+ }
+ }
+ }
+ }
+}
diff --git a/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstatus-job b/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstatus-job
new file mode 100644
index 0000000000..1b1dc7d315
--- /dev/null
+++ b/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstatus-job
@@ -0,0 +1,17 @@
+pipeline {
+ agent any
+ stages {
+ stage('Example') {
+ steps {
+ script {
+ def status = sh(returnStatus: true, script: 'ls /test')
+ if (status != 0) {
+ echo "Error: Command exited with status ${status}"
+ } else {
+ echo "Command executed successfully"
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstdout-job b/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstdout-job
new file mode 100644
index 0000000000..ad00b30d92
--- /dev/null
+++ b/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstdout-job
@@ -0,0 +1,13 @@
+pipeline {
+ agent any
+ stages {
+ stage('Example') {
+ steps {
+ script {
+ def output = sh(returnStdout: true, script: 'pwd')
+ echo "Output: ${output}"
+ }
+ }
+ }
+ }
+}
diff --git a/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstdouttrim-job b/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstdouttrim-job
new file mode 100644
index 0000000000..d253173934
--- /dev/null
+++ b/jenkins-modules/jenkins-jobs/output-job/pipeline-returnstdouttrim-job
@@ -0,0 +1,13 @@
+pipeline {
+ agent any
+ stages {
+ stage('Example') {
+ steps {
+ script {
+ def output = sh(returnStdout: true, returnStdoutTrim: true, script: 'echo " hello "')
+ echo "Output: '${output}'"
+ }
+ }
+ }
+ }
+}
diff --git a/jenkins-modules/jenkins-jobs/parallel-stage-job/pipeline-parallel-job b/jenkins-modules/jenkins-jobs/parallel-stage-job/pipeline-parallel-job
new file mode 100644
index 0000000000..c44d61d099
--- /dev/null
+++ b/jenkins-modules/jenkins-jobs/parallel-stage-job/pipeline-parallel-job
@@ -0,0 +1,34 @@
+pipeline {
+ agent any
+ stages {
+ stage('Build') {
+ steps {
+ sh 'echo "Building the application"'
+ // Add commands to build application
+ }
+ }
+ stage('Test') {
+ parallel {
+ stage('Unit Tests') {
+ steps {
+ sh 'sleep 5s'
+ sh 'echo "Running unit tests"'
+ // Add commands to run unit tests
+ }
+ }
+ stage('Integration Tests') {
+ steps {
+ sh 'echo "Running integration tests"'
+ // Add commands to run integration tests
+ }
+ }
+ }
+ }
+ stage('Deploy') {
+ steps {
+ sh 'echo "Deploying the application"'
+ // Add commands to deploy application
+ }
+ }
+ }
+}
diff --git a/jenkins-modules/jenkins-jobs/skip-stage-job/skip-function-script b/jenkins-modules/jenkins-jobs/skip-stage-job/skip-function-script
new file mode 100644
index 0000000000..62163d6301
--- /dev/null
+++ b/jenkins-modules/jenkins-jobs/skip-stage-job/skip-function-script
@@ -0,0 +1,32 @@
+pipeline {
+ agent any
+ parameters {
+ booleanParam(name: 'skip_test', defaultValue: false, description: 'Set to true to skip the test stage')
+ }
+ stages {
+ stage('Build') {
+ steps {
+ sh 'echo "Building the application"'
+ }
+ }
+ stage('Test') {
+ steps {
+ execute_stage('Test', params.skip_test)
+ }
+ }
+ stage('Deploy') {
+ steps {
+ sh 'echo "Deploying the application"'
+ }
+ }
+ }
+}
+
+def execute_stage(stage_name, skip) {
+ stage(stage_name) {
+ if(skip) {
+ echo "Skipping ${stage_name} stage"
+ return
+ }
+ // Add steps to test the application
+ }
diff --git a/jenkins-modules/jenkins-jobs/skip-stage-job/skip-input-script b/jenkins-modules/jenkins-jobs/skip-stage-job/skip-input-script
new file mode 100644
index 0000000000..ba5560578a
--- /dev/null
+++ b/jenkins-modules/jenkins-jobs/skip-stage-job/skip-input-script
@@ -0,0 +1,29 @@
+pipeline {
+ agent any
+ stages {
+ stage('Build') {
+ steps {
+ sh 'echo "Building the application"'
+ // Add steps to build the application
+ }
+ }
+ stage('Test') {
+ steps {
+ input message: 'Do you want to skip the test stage?', ok: 'Yes', parameters: [booleanParam(name: 'skip_test', defaultValue: false)], timeout: time(minutes: 5))
+ script {
+ if(params.skip_test) {
+ sh 'echo "Testing the application"'
+ return
+ }
+ }
+ // Add steps to test the application
+ }
+ }
+ stage('Deploy') {
+ steps {
+ sh 'echo "Deploying the application"'
+ // Add steps to deploy the application
+ }
+ }
+ }
+}
diff --git a/jenkins-modules/jenkins-jobs/skip-stage-job/skip-when-script b/jenkins-modules/jenkins-jobs/skip-stage-job/skip-when-script
new file mode 100644
index 0000000000..0b62a819e1
--- /dev/null
+++ b/jenkins-modules/jenkins-jobs/skip-stage-job/skip-when-script
@@ -0,0 +1,27 @@
+pipeline {
+ agent any
+ parameters {
+ booleanParam(name: 'skip_test', defaultValue: false, description: 'Set to true to skip the test stage')
+ }
+ stages {
+ stage('Build') {
+ steps {
+ sh 'echo "Building application"'
+ // Add build steps here
+ }
+ }
+ stage('Test') {
+ when { expression { params.skip_test != true } }
+ steps {
+ sh 'echo "Testing application"'
+ // Add test steps here
+ }
+ }
+ stage('Deploy') {
+ steps {
+ sh 'echo "Deploying application"'
+ // Add deployment steps here
+ }
+ }
+ }
+}
diff --git a/jenkins-modules/plugins/pom.xml b/jenkins-modules/plugins/pom.xml
index 7f88382e22..42add1664e 100644
--- a/jenkins-modules/plugins/pom.xml
+++ b/jenkins-modules/plugins/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
plugins
- 1.0-SNAPSHOT
plugins
hpi
A sample Jenkins Hello World plugin
diff --git a/jersey/pom.xml b/jersey/pom.xml
index 7c7330d84f..005fa85077 100644
--- a/jersey/pom.xml
+++ b/jersey/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jersey
- 0.0.1-SNAPSHOT
jersey
war
@@ -100,7 +99,8 @@
- 2.38
+ 3.1.1
+ 3.3.2
\ No newline at end of file
diff --git a/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java b/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java
index 88ad891411..3865e64aa0 100644
--- a/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java
+++ b/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java
@@ -1,19 +1,20 @@
package com.baeldung.jersey.client;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.client.ClientBuilder;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.Response;
-
import org.glassfish.jersey.client.ClientConfig;
import com.baeldung.jersey.client.filter.RequestClientFilter;
import com.baeldung.jersey.client.filter.ResponseClientFilter;
import com.baeldung.jersey.client.interceptor.RequestClientWriterInterceptor;
+import com.baeldung.jersey.server.Greetings;
+
+import jakarta.ws.rs.client.Client;
+import jakarta.ws.rs.client.ClientBuilder;
+import jakarta.ws.rs.client.Entity;
+import jakarta.ws.rs.core.Response;
public class JerseyClient {
- private static final String URI_GREETINGS = "http://localhost:8080/jersey/greetings";
+ public static final String URI_GREETINGS = "http://localhost:8080/jersey/greetings";
public static String getHelloGreeting() {
return createClient().target(URI_GREETINGS)
@@ -38,6 +39,7 @@ public class JerseyClient {
config.register(RequestClientFilter.class);
config.register(ResponseClientFilter.class);
config.register(RequestClientWriterInterceptor.class);
+ config.register(Greetings.class);
return ClientBuilder.newClient(config);
}
diff --git a/jersey/src/main/java/com/baeldung/jersey/client/JerseyClientHeaders.java b/jersey/src/main/java/com/baeldung/jersey/client/JerseyClientHeaders.java
index 29db298e9e..f0d62111aa 100644
--- a/jersey/src/main/java/com/baeldung/jersey/client/JerseyClientHeaders.java
+++ b/jersey/src/main/java/com/baeldung/jersey/client/JerseyClientHeaders.java
@@ -9,17 +9,17 @@ import org.glassfish.jersey.client.oauth1.ConsumerCredentials;
import org.glassfish.jersey.client.oauth1.OAuth1ClientSupport;
import org.glassfish.jersey.client.oauth2.OAuth2ClientSupport;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.client.ClientBuilder;
-import javax.ws.rs.client.Invocation;
-import javax.ws.rs.client.WebTarget;
-import javax.ws.rs.core.Feature;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.sse.InboundSseEvent;
-import javax.ws.rs.sse.SseEventSource;
-
import static org.glassfish.jersey.client.authentication.HttpAuthenticationFeature.*;
+import jakarta.ws.rs.client.Client;
+import jakarta.ws.rs.client.ClientBuilder;
+import jakarta.ws.rs.client.Invocation;
+import jakarta.ws.rs.client.WebTarget;
+import jakarta.ws.rs.core.Feature;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.sse.InboundSseEvent;
+import jakarta.ws.rs.sse.SseEventSource;
+
public class JerseyClientHeaders {
private static final String BEARER_CONSUMER_SECRET = "my-consumer-secret";
diff --git a/jersey/src/main/java/com/baeldung/jersey/client/filter/AddHeaderOnRequestFilter.java b/jersey/src/main/java/com/baeldung/jersey/client/filter/AddHeaderOnRequestFilter.java
index a874928c16..61f2dfe475 100644
--- a/jersey/src/main/java/com/baeldung/jersey/client/filter/AddHeaderOnRequestFilter.java
+++ b/jersey/src/main/java/com/baeldung/jersey/client/filter/AddHeaderOnRequestFilter.java
@@ -1,9 +1,10 @@
package com.baeldung.jersey.client.filter;
-import javax.ws.rs.client.ClientRequestContext;
-import javax.ws.rs.client.ClientRequestFilter;
import java.io.IOException;
+import jakarta.ws.rs.client.ClientRequestContext;
+import jakarta.ws.rs.client.ClientRequestFilter;
+
public class AddHeaderOnRequestFilter implements ClientRequestFilter {
public static final String FILTER_HEADER_VALUE = "filter-header-value";
diff --git a/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java b/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java
index 8c6ac2c5fb..5d7d8be684 100644
--- a/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java
+++ b/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java
@@ -2,13 +2,13 @@ package com.baeldung.jersey.client.filter;
import java.io.IOException;
-import javax.ws.rs.client.ClientRequestContext;
-import javax.ws.rs.client.ClientRequestFilter;
-import javax.ws.rs.ext.Provider;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import jakarta.ws.rs.client.ClientRequestContext;
+import jakarta.ws.rs.client.ClientRequestFilter;
+import jakarta.ws.rs.ext.Provider;
+
@Provider
public class RequestClientFilter implements ClientRequestFilter {
diff --git a/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java b/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java
index 1676fa2094..4348937364 100644
--- a/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java
+++ b/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java
@@ -2,14 +2,14 @@ package com.baeldung.jersey.client.filter;
import java.io.IOException;
-import javax.ws.rs.client.ClientRequestContext;
-import javax.ws.rs.client.ClientResponseContext;
-import javax.ws.rs.client.ClientResponseFilter;
-import javax.ws.rs.ext.Provider;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import jakarta.ws.rs.client.ClientRequestContext;
+import jakarta.ws.rs.client.ClientResponseContext;
+import jakarta.ws.rs.client.ClientResponseFilter;
+import jakarta.ws.rs.ext.Provider;
+
@Provider
public class ResponseClientFilter implements ClientResponseFilter {
diff --git a/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java b/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java
index 7216cf18cc..3f55f56ec2 100644
--- a/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java
+++ b/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java
@@ -2,14 +2,14 @@ package com.baeldung.jersey.client.interceptor;
import java.io.IOException;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.ext.Provider;
-import javax.ws.rs.ext.WriterInterceptor;
-import javax.ws.rs.ext.WriterInterceptorContext;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.ext.Provider;
+import jakarta.ws.rs.ext.WriterInterceptor;
+import jakarta.ws.rs.ext.WriterInterceptorContext;
+
@Provider
public class RequestClientWriterInterceptor implements WriterInterceptor {
diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/ExceptionHandlingConfig.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/ExceptionHandlingConfig.java
index d4cc1a81a1..efe3b6877e 100644
--- a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/ExceptionHandlingConfig.java
+++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/ExceptionHandlingConfig.java
@@ -1,12 +1,12 @@
package com.baeldung.jersey.exceptionhandling;
-import javax.ws.rs.ApplicationPath;
-
import org.glassfish.jersey.server.ResourceConfig;
import com.baeldung.jersey.exceptionhandling.rest.exceptions.IllegalArgumentExceptionMapper;
import com.baeldung.jersey.exceptionhandling.rest.exceptions.ServerExceptionMapper;
+import jakarta.ws.rs.ApplicationPath;
+
@ApplicationPath("/exception-handling/*")
public class ExceptionHandlingConfig extends ResourceConfig {
diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/StocksResource.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/StocksResource.java
index 64b645a1c6..de21440049 100644
--- a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/StocksResource.java
+++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/StocksResource.java
@@ -2,19 +2,19 @@ package com.baeldung.jersey.exceptionhandling.rest;
import java.util.Optional;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
import com.baeldung.jersey.exceptionhandling.data.Stock;
import com.baeldung.jersey.exceptionhandling.repo.Db;
import com.baeldung.jersey.exceptionhandling.service.Repository;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
@Path("/stocks")
public class StocksResource {
private static final Db stocks = Repository.STOCKS_DB;
diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/WalletsResource.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/WalletsResource.java
index e5f8ddec06..667f721e4a 100644
--- a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/WalletsResource.java
+++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/WalletsResource.java
@@ -2,18 +2,6 @@ package com.baeldung.jersey.exceptionhandling.rest;
import java.util.Optional;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-
import com.baeldung.jersey.exceptionhandling.data.Stock;
import com.baeldung.jersey.exceptionhandling.data.Wallet;
import com.baeldung.jersey.exceptionhandling.repo.Db;
@@ -21,6 +9,17 @@ import com.baeldung.jersey.exceptionhandling.rest.exceptions.InvalidTradeExcepti
import com.baeldung.jersey.exceptionhandling.rest.exceptions.RestErrorResponse;
import com.baeldung.jersey.exceptionhandling.service.Repository;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.PUT;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
@Path("/wallets")
public class WalletsResource {
private static final Db stocks = Repository.STOCKS_DB;
@@ -84,7 +83,7 @@ public class WalletsResource {
RestErrorResponse response = new RestErrorResponse();
response.setSubject(wallet);
response.setMessage("insufficient balance");
- throw new WebApplicationException(Response.status(Status.NOT_ACCEPTABLE)
+ throw new WebApplicationException(Response.status(Response.Status.NOT_ACCEPTABLE)
.entity(response)
.build());
}
diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/IllegalArgumentExceptionMapper.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/IllegalArgumentExceptionMapper.java
index b577121027..fdaeb218c0 100644
--- a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/IllegalArgumentExceptionMapper.java
+++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/IllegalArgumentExceptionMapper.java
@@ -1,8 +1,8 @@
package com.baeldung.jersey.exceptionhandling.rest.exceptions;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.ExceptionMapper;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.ext.ExceptionMapper;
public class IllegalArgumentExceptionMapper implements ExceptionMapper {
public static final String DEFAULT_MESSAGE = "an illegal argument was provided";
diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/InvalidTradeException.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/InvalidTradeException.java
index 11277c048a..966683dd6a 100644
--- a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/InvalidTradeException.java
+++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/InvalidTradeException.java
@@ -1,7 +1,7 @@
package com.baeldung.jersey.exceptionhandling.rest.exceptions;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.core.Response;
public class InvalidTradeException extends WebApplicationException {
private static final long serialVersionUID = 1L;
diff --git a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/ServerExceptionMapper.java b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/ServerExceptionMapper.java
index adfac000e8..f537c1756a 100644
--- a/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/ServerExceptionMapper.java
+++ b/jersey/src/main/java/com/baeldung/jersey/exceptionhandling/rest/exceptions/ServerExceptionMapper.java
@@ -1,19 +1,18 @@
package com.baeldung.jersey.exceptionhandling.rest.exceptions;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.ext.ExceptionMapper;
+import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.ext.ExceptionMapper;
public class ServerExceptionMapper implements ExceptionMapper {
public static final String HTTP_405_MESSAGE = "use one of";
@Override
public Response toResponse(final WebApplicationException exception) {
- String message = exception.getMessage();
+ String message;
Response response = exception.getResponse();
- Status status = response.getStatusInfo()
+ Response.Status status = response.getStatusInfo()
.toEnum();
switch (status) {
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/EchoHeaders.java b/jersey/src/main/java/com/baeldung/jersey/server/EchoHeaders.java
index a8df3c10a8..b3b03fbb4d 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/EchoHeaders.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/EchoHeaders.java
@@ -2,14 +2,17 @@ package com.baeldung.jersey.server;
import com.baeldung.jersey.client.filter.AddHeaderOnRequestFilter;
-import javax.annotation.security.RolesAllowed;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.*;
-import javax.ws.rs.sse.OutboundSseEvent;
-import javax.ws.rs.sse.Sse;
-import javax.ws.rs.sse.SseEventSink;
+import jakarta.annotation.security.RolesAllowed;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.Context;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.sse.OutboundSseEvent;
+import jakarta.ws.rs.sse.Sse;
+import jakarta.ws.rs.sse.SseEventSink;
@Path("/echo-headers")
public class EchoHeaders {
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java b/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java
index d0ea873db1..e753d34901 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java
@@ -1,13 +1,12 @@
package com.baeldung.jersey.server;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-
import com.baeldung.jersey.server.config.HelloBinding;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.core.Response;
+
@Path("/greetings")
public class Greetings {
@@ -26,7 +25,7 @@ public class Greetings {
@POST
@Path("/custom")
public Response getCustomGreeting(String name) {
- return Response.status(Status.OK.getStatusCode())
+ return Response.status(Response.Status.OK.getStatusCode())
.build();
}
}
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/ItemParam.java b/jersey/src/main/java/com/baeldung/jersey/server/ItemParam.java
index 0f60a20b92..6c05f5b650 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/ItemParam.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/ItemParam.java
@@ -1,8 +1,8 @@
package com.baeldung.jersey.server;
-import javax.ws.rs.FormParam;
-import javax.ws.rs.HeaderParam;
-import javax.ws.rs.PathParam;
+import jakarta.ws.rs.FormParam;
+import jakarta.ws.rs.HeaderParam;
+import jakarta.ws.rs.PathParam;
public class ItemParam {
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/Items.java b/jersey/src/main/java/com/baeldung/jersey/server/Items.java
index c24e6820f5..4aab765351 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/Items.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/Items.java
@@ -1,6 +1,15 @@
package com.baeldung.jersey.server;
-import javax.ws.rs.*;
+import jakarta.ws.rs.BeanParam;
+import jakarta.ws.rs.CookieParam;
+import jakarta.ws.rs.FormParam;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.HeaderParam;
+import jakarta.ws.rs.MatrixParam;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.QueryParam;
@Path("items")
public class Items {
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/Responder.java b/jersey/src/main/java/com/baeldung/jersey/server/Responder.java
index cb0c976fe3..3ce8e65bd0 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/Responder.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/Responder.java
@@ -2,11 +2,11 @@ package com.baeldung.jersey.server;
import com.baeldung.jersey.server.model.Person;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
@Path("/response")
public class Responder {
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java b/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java
index 49b11adeab..f620514094 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java
@@ -3,7 +3,7 @@ package com.baeldung.jersey.server.config;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
-import javax.ws.rs.NameBinding;
+import jakarta.ws.rs.NameBinding;
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java b/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java
index 19c407f80d..89b520bf97 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java
@@ -1,13 +1,13 @@
package com.baeldung.jersey.server.config;
-import javax.ws.rs.container.DynamicFeature;
-import javax.ws.rs.container.ResourceInfo;
-import javax.ws.rs.core.FeatureContext;
-import javax.ws.rs.ext.Provider;
-
import com.baeldung.jersey.server.Greetings;
import com.baeldung.jersey.server.filter.ResponseServerFilter;
+import jakarta.ws.rs.container.DynamicFeature;
+import jakarta.ws.rs.container.ResourceInfo;
+import jakarta.ws.rs.core.FeatureContext;
+import jakarta.ws.rs.ext.Provider;
+
@Provider
public class HelloDynamicBinding implements DynamicFeature {
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java b/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java
index 4670cc291c..c4db7df223 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java
@@ -1,9 +1,9 @@
package com.baeldung.jersey.server.config;
-import javax.ws.rs.ApplicationPath;
-
import org.glassfish.jersey.server.ResourceConfig;
+import jakarta.ws.rs.ApplicationPath;
+
@ApplicationPath("/*")
public class ServerConfig extends ResourceConfig {
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/constraints/SerialNumber.java b/jersey/src/main/java/com/baeldung/jersey/server/constraints/SerialNumber.java
index ca49797e31..d18375c152 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/constraints/SerialNumber.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/constraints/SerialNumber.java
@@ -4,10 +4,10 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.regex.Pattern;
-import javax.validation.Constraint;
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
-import javax.validation.Payload;
+import jakarta.validation.Constraint;
+import jakarta.validation.ConstraintValidator;
+import jakarta.validation.ConstraintValidatorContext;
+import jakarta.validation.Payload;
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { SerialNumber.Validator.class })
@@ -21,7 +21,7 @@ public @interface SerialNumber {
Class extends Payload>[] payload() default {};
- public class Validator implements ConstraintValidator {
+ class Validator implements ConstraintValidator {
@Override
public void initialize(final SerialNumber serial) {
}
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java b/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java
index 181fa7f043..2c9da1afba 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java
@@ -2,14 +2,15 @@ package com.baeldung.jersey.server.filter;
import java.io.IOException;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.container.PreMatching;
-import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerRequestFilter;
+import jakarta.ws.rs.container.PreMatching;
+import jakarta.ws.rs.ext.Provider;
+
@Provider
@PreMatching
public class PrematchingRequestFilter implements ContainerRequestFilter {
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java b/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java
index de0dcbdce7..3e92b081fe 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java
@@ -2,13 +2,13 @@ package com.baeldung.jersey.server.filter;
import java.io.IOException;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerResponseContext;
-import javax.ws.rs.container.ContainerResponseFilter;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerResponseContext;
+import jakarta.ws.rs.container.ContainerResponseFilter;
+
public class ResponseServerFilter implements ContainerResponseFilter {
private static final Logger LOG = LoggerFactory.getLogger(ResponseServerFilter.class);
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java b/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java
index cb0cd185f7..1064b04204 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java
@@ -2,18 +2,18 @@ package com.baeldung.jersey.server.filter;
import java.io.IOException;
-import javax.annotation.Priority;
-import javax.ws.rs.Priorities;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.Provider;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baeldung.jersey.server.config.HelloBinding;
+import jakarta.annotation.Priority;
+import jakarta.ws.rs.Priorities;
+import jakarta.ws.rs.container.ContainerRequestContext;
+import jakarta.ws.rs.container.ContainerRequestFilter;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.ext.Provider;
+
@Provider
@Priority(Priorities.AUTHORIZATION)
@HelloBinding
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java b/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java
index 1d75508c6d..8a696d8f34 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/http/EmbeddedHttpServer.java
@@ -19,10 +19,7 @@ public class EmbeddedHttpServer {
try {
final HttpServer server = GrizzlyHttpServerFactory.createHttpServer(BASE_URI, new ViewApplicationConfig(), false);
- Runtime.getRuntime()
- .addShutdownHook(new Thread(() -> {
- server.shutdownNow();
- }));
+ Runtime.getRuntime().addShutdownHook(new Thread(server::shutdownNow));
server.start();
@@ -34,8 +31,8 @@ public class EmbeddedHttpServer {
}
- public static HttpServer startServer() {
+ public static HttpServer startServer(URI url) {
final ResourceConfig rc = new ResourceConfig().packages("com.baeldung.jersey.server");
- return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI.toString()), rc);
+ return GrizzlyHttpServerFactory.createHttpServer(URI.create(url.toString()), rc);
}
}
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java b/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java
index e9cc57fc2a..9a11c212d7 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java
@@ -7,14 +7,14 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.ext.Provider;
-import javax.ws.rs.ext.ReaderInterceptor;
-import javax.ws.rs.ext.ReaderInterceptorContext;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.ext.Provider;
+import jakarta.ws.rs.ext.ReaderInterceptor;
+import jakarta.ws.rs.ext.ReaderInterceptorContext;
+
@Provider
public class RequestServerReaderInterceptor implements ReaderInterceptor {
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java b/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java
index 1a648290a3..83c96e2784 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/model/Fruit.java
@@ -1,8 +1,8 @@
package com.baeldung.jersey.server.model;
-import javax.validation.constraints.Min;
-import javax.validation.constraints.Size;
-import javax.xml.bind.annotation.XmlRootElement;
+import jakarta.validation.constraints.Min;
+import jakarta.validation.constraints.Size;
+import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Fruit {
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/providers/FruitExceptionMapper.java b/jersey/src/main/java/com/baeldung/jersey/server/providers/FruitExceptionMapper.java
index cea61c897b..10e1c6d60c 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/providers/FruitExceptionMapper.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/providers/FruitExceptionMapper.java
@@ -1,9 +1,9 @@
package com.baeldung.jersey.server.providers;
-import javax.validation.ConstraintViolation;
-import javax.validation.ConstraintViolationException;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.ext.ExceptionMapper;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.ConstraintViolationException;
+import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.ext.ExceptionMapper;
public class FruitExceptionMapper implements ExceptionMapper {
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java b/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java
index 88692dcc55..3ee5de8073 100644
--- a/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java
+++ b/jersey/src/main/java/com/baeldung/jersey/server/rest/FruitResource.java
@@ -5,20 +5,6 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import javax.validation.Valid;
-import javax.validation.constraints.NotNull;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.FormParam;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-
import org.glassfish.jersey.server.mvc.ErrorTemplate;
import org.glassfish.jersey.server.mvc.Template;
import org.glassfish.jersey.server.mvc.Viewable;
@@ -27,6 +13,19 @@ import com.baeldung.jersey.server.constraints.SerialNumber;
import com.baeldung.jersey.server.model.Fruit;
import com.baeldung.jersey.service.SimpleStorageService;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotNull;
+import jakarta.ws.rs.Consumes;
+import jakarta.ws.rs.FormParam;
+import jakarta.ws.rs.GET;
+import jakarta.ws.rs.POST;
+import jakarta.ws.rs.PUT;
+import jakarta.ws.rs.Path;
+import jakarta.ws.rs.PathParam;
+import jakarta.ws.rs.Produces;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
@Path("/fruit")
public class FruitResource {
@@ -66,7 +65,7 @@ public class FruitResource {
@Path("/create")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void createFruit(
- @NotNull(message = "Fruit name must not be null") @FormParam("name") String name,
+ @NotNull(message = "Fruit name must not be null") @FormParam("name") String name,
@NotNull(message = "Fruit colour must not be null") @FormParam("colour") String colour) {
Fruit fruit = new Fruit(name, colour);
@@ -94,7 +93,7 @@ public class FruitResource {
@Consumes(MediaType.APPLICATION_JSON)
public Response createNewFruit(@Valid Fruit fruit) {
String result = "Fruit saved : " + fruit;
- return Response.status(Status.CREATED.getStatusCode())
+ return Response.status(Response.Status.CREATED.getStatusCode())
.entity(result)
.build();
}
diff --git a/jersey/src/main/java/com/baeldung/jersey/service/SimpleStorageService.java b/jersey/src/main/java/com/baeldung/jersey/service/SimpleStorageService.java
index e21dd584a1..2c718c9d17 100644
--- a/jersey/src/main/java/com/baeldung/jersey/service/SimpleStorageService.java
+++ b/jersey/src/main/java/com/baeldung/jersey/service/SimpleStorageService.java
@@ -7,7 +7,7 @@ import com.baeldung.jersey.server.model.Fruit;
public class SimpleStorageService {
- private static final Map fruits = new HashMap();
+ private static final Map fruits = new HashMap<>();
public static void storeFruit(final Fruit fruit) {
fruits.put(fruit.getName(), fruit);
@@ -17,7 +17,7 @@ public class SimpleStorageService {
return fruits.entrySet()
.stream()
.filter(map -> name.equals(map.getKey()))
- .map(map -> map.getValue())
+ .map(Map.Entry::getValue)
.findFirst()
.get();
}
diff --git a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java
index a6fd606e3f..e0166d0331 100644
--- a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java
+++ b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientIntegrationTest.java
@@ -1,35 +1,53 @@
package com.baeldung.jersey.client;
-import javax.ws.rs.core.Response;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Assert;
-import org.junit.Ignore;
-import org.junit.Test;
+import java.net.URI;
+
+import org.glassfish.grizzly.http.server.HttpServer;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import com.baeldung.jersey.server.http.EmbeddedHttpServer;
+
+import jakarta.ws.rs.core.Response;
-@Ignore
public class JerseyClientIntegrationTest {
private static int HTTP_OK = 200;
+ private static HttpServer httpServer;
+
+ @BeforeAll
+ public static void beforeAllTests() {
+ httpServer = EmbeddedHttpServer.startServer(URI.create("http://localhost:8080/jersey"));
+ }
+
+ @AfterAll
+ public static void afterAllTests() {
+ httpServer.stop();
+ }
+
@Test
public void givenGreetingResource_whenCallingHelloGreeting_thenHelloReturned() {
String response = JerseyClient.getHelloGreeting();
- Assert.assertEquals("hello", response);
+ assertEquals("hello", response);
}
@Test
public void givenGreetingResource_whenCallingHiGreeting_thenHiReturned() {
String response = JerseyClient.getHiGreeting();
- Assert.assertEquals("hi", response);
+ assertEquals("hi", response);
}
@Test
public void givenGreetingResource_whenCallingCustomGreeting_thenCustomGreetingReturned() {
Response response = JerseyClient.getCustomGreeting();
- Assert.assertEquals(HTTP_OK, response.getStatus());
+ assertEquals(HTTP_OK, response.getStatus());
}
}
diff --git a/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java
index ceb59adc1f..eff5d5ae6e 100644
--- a/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java
+++ b/jersey/src/test/java/com/baeldung/jersey/exceptionhandling/rest/StocksResourceIntegrationTest.java
@@ -2,31 +2,30 @@ package com.baeldung.jersey.exceptionhandling.rest;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.startsWith;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashMap;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.client.Invocation;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-
+import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import com.baeldung.jersey.exceptionhandling.ExceptionHandlingConfig;
import com.baeldung.jersey.exceptionhandling.data.Stock;
import com.baeldung.jersey.exceptionhandling.data.Wallet;
import com.baeldung.jersey.exceptionhandling.rest.exceptions.IllegalArgumentExceptionMapper;
import com.baeldung.jersey.exceptionhandling.rest.exceptions.RestErrorResponse;
import com.baeldung.jersey.exceptionhandling.rest.exceptions.ServerExceptionMapper;
+import jakarta.ws.rs.client.Entity;
+import jakarta.ws.rs.client.Invocation;
+import jakarta.ws.rs.core.Application;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
public class StocksResourceIntegrationTest extends JerseyTest {
private static final Entity EMPTY_BODY = Entity.json("");
private static final Stock STOCK = new Stock("BAEL", 51.57);
@@ -36,8 +35,13 @@ public class StocksResourceIntegrationTest extends JerseyTest {
@Override
protected Application configure() {
- forceSet(TestProperties.CONTAINER_PORT, "0");
- return new ExceptionHandlingConfig();
+ final ResourceConfig resourceConfig = new ResourceConfig();
+ resourceConfig.register(StocksResource.class);
+ resourceConfig.register(WalletsResource.class);
+ resourceConfig.register(IllegalArgumentExceptionMapper.class);
+ resourceConfig.register(ServerExceptionMapper.class);
+ resourceConfig.packages("com.baeldung.jersey.exceptionhandling.rest");
+ return resourceConfig;
}
private Invocation.Builder stocks(String path) {
@@ -56,7 +60,7 @@ public class StocksResourceIntegrationTest extends JerseyTest {
public void whenMethodNotAllowed_thenCustomMessage() {
Response response = stocks("").get();
- assertEquals(Status.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus());
+ assertEquals(Response.Status.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus());
String content = response.readEntity(String.class);
assertThat(content, containsString(ServerExceptionMapper.HTTP_405_MESSAGE));
@@ -64,9 +68,9 @@ public class StocksResourceIntegrationTest extends JerseyTest {
@Test
public void whenTickerNotExists_thenRestErrorResponse() {
- Response response = stocks("/UNDEFINED").get();
+ Response response = stocks("/TEST").get();
- assertEquals(Status.EXPECTATION_FAILED.getStatusCode(), response.getStatus());
+ assertEquals(Response.Status.EXPECTATION_FAILED.getStatusCode(), response.getStatus());
RestErrorResponse content = response.readEntity(RestErrorResponse.class);
assertThat(content.getMessage(), startsWith(IllegalArgumentExceptionMapper.DEFAULT_MESSAGE));
@@ -77,7 +81,7 @@ public class StocksResourceIntegrationTest extends JerseyTest {
wallets("").post(entity(WALLET));
Response response = wallets("/%s/%d", MY_WALLET, INSUFFICIENT_AMOUNT).put(EMPTY_BODY);
- assertEquals(Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
+ assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
String content = response.readEntity(String.class);
assertThat(content, containsString(Wallet.MIN_CHARGE_MSG));
@@ -89,7 +93,7 @@ public class StocksResourceIntegrationTest extends JerseyTest {
wallets("").post(entity(WALLET));
Response response = wallets("/%s/buy/%s", MY_WALLET, STOCK.getId()).post(EMPTY_BODY);
- assertEquals(Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
+ assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatus());
RestErrorResponse content = response.readEntity(RestErrorResponse.class);
assertNotNull(content.getSubject());
diff --git a/jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersUnitTest.java b/jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersIntegrationTest.java
similarity index 98%
rename from jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersUnitTest.java
rename to jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersIntegrationTest.java
index 24552f6d81..e6f06383db 100644
--- a/jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersUnitTest.java
+++ b/jersey/src/test/java/com/baeldung/jersey/server/EchoHeadersIntegrationTest.java
@@ -6,8 +6,6 @@ import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.Response;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
@@ -15,7 +13,10 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
-public class EchoHeadersUnitTest extends JerseyTest {
+import jakarta.ws.rs.core.Application;
+import jakarta.ws.rs.core.Response;
+
+public class EchoHeadersIntegrationTest extends JerseyTest {
private static final String SIMPLE_HEADER_KEY = "my-header-key";
private static final String SIMPLE_HEADER_VALUE = "my-header-value";
diff --git a/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java
index 8953f4161c..97934369e2 100644
--- a/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java
+++ b/jersey/src/test/java/com/baeldung/jersey/server/GreetingsResourceIntegrationTest.java
@@ -2,16 +2,15 @@ package com.baeldung.jersey.server;
import static org.junit.Assert.assertEquals;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.Test;
+import jakarta.ws.rs.core.Application;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
public class GreetingsResourceIntegrationTest extends JerseyTest {
@Override
@@ -24,7 +23,7 @@ public class GreetingsResourceIntegrationTest extends JerseyTest {
Response response = target("/greetings/hi").request()
.get();
- assertEquals("Http Response should be 200: ", Status.OK.getStatusCode(), response.getStatus());
+ assertEquals("Http Response should be 200: ", Response.Status.OK.getStatusCode(), response.getStatus());
assertEquals("Http Content-Type should be: ", MediaType.TEXT_HTML, response.getHeaderString(HttpHeaders.CONTENT_TYPE));
String content = response.readEntity(String.class);
diff --git a/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java b/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java
index b158d63720..9954c5bd53 100644
--- a/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java
+++ b/jersey/src/test/java/com/baeldung/jersey/server/ItemsUnitTest.java
@@ -1,35 +1,32 @@
package com.baeldung.jersey.server;
+import static com.baeldung.jersey.server.http.EmbeddedHttpServer.BASE_URI;
import static org.junit.Assert.assertEquals;
-import javax.ws.rs.client.ClientBuilder;
-import javax.ws.rs.client.WebTarget;
-
import org.glassfish.grizzly.http.server.HttpServer;
import org.junit.After;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Test;
-import org.junit.jupiter.api.Disabled;
import com.baeldung.jersey.server.http.EmbeddedHttpServer;
-@Disabled
-@Ignore
+import jakarta.ws.rs.client.ClientBuilder;
+import jakarta.ws.rs.client.WebTarget;
+
public class ItemsUnitTest {
private HttpServer server;
private WebTarget target;
@Before
- public void setUp() throws Exception {
- server = EmbeddedHttpServer.startServer();
- target = ClientBuilder.newClient().target(EmbeddedHttpServer.BASE_URI.toString());
+ public void setUp() {
+ server = EmbeddedHttpServer.startServer(BASE_URI);
+ target = ClientBuilder.newClient().target(BASE_URI.toString());
}
@After
- public void tearDown() throws Exception {
+ public void tearDown() {
server.stop();
}
diff --git a/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java b/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java
index f7bb0df1ed..4f73c9df5b 100644
--- a/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java
+++ b/jersey/src/test/java/com/baeldung/jersey/server/rest/FruitResourceIntegrationTest.java
@@ -5,13 +5,6 @@ import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.Application;
-import javax.ws.rs.core.Form;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.junit.Test;
@@ -20,6 +13,12 @@ import com.baeldung.jersey.server.config.ViewApplicationConfig;
import com.baeldung.jersey.server.model.Fruit;
import com.baeldung.jersey.server.providers.FruitExceptionMapper;
+import jakarta.ws.rs.client.Entity;
+import jakarta.ws.rs.core.Application;
+import jakarta.ws.rs.core.Form;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+
public class FruitResourceIntegrationTest extends JerseyTest {
@Override
@@ -71,7 +70,7 @@ public class FruitResourceIntegrationTest extends JerseyTest {
Response response = target("fruit/created").request()
.post(Entity.json("{\"name\":\"strawberry\",\"weight\":20}"));
- assertEquals("Http Response should be 201 ", Status.CREATED.getStatusCode(), response.getStatus());
+ assertEquals("Http Response should be 201 ", Response.Status.CREATED.getStatusCode(), response.getStatus());
assertThat(response.readEntity(String.class), containsString("Fruit saved : Fruit [name: strawberry colour: null]"));
}
diff --git a/jetbrains/README.md b/jetbrains/README.md
new file mode 100644
index 0000000000..c8872ec46e
--- /dev/null
+++ b/jetbrains/README.md
@@ -0,0 +1,6 @@
+## Jetbrains
+
+This module contains articles about Jetbrains' libraries.
+
+### Relevant articles:
+- [JetBrains @Contract Annotation](https://www.baeldung.com/jetbrains-contract-annotation)
diff --git a/jetbrains/pom.xml b/jetbrains/pom.xml
new file mode 100644
index 0000000000..ec46dc54f0
--- /dev/null
+++ b/jetbrains/pom.xml
@@ -0,0 +1,36 @@
+
+
+ 4.0.0
+ jetbrains
+ 1.0-SNAPSHOT
+ jetbrains
+ jar
+
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../parent-java
+
+
+
+
+ org.apache.commons
+ commons-lang3
+ ${apache.commons.version}
+
+
+ org.jetbrains
+ annotations
+ ${jetbrains.annotations.version}
+
+
+
+
+ 3.12.0
+ 24.0.1
+
+
+
\ No newline at end of file
diff --git a/jetbrains/src/main/java/com/baeldung/annotations/Demo.java b/jetbrains/src/main/java/com/baeldung/annotations/Demo.java
new file mode 100644
index 0000000000..3638d13581
--- /dev/null
+++ b/jetbrains/src/main/java/com/baeldung/annotations/Demo.java
@@ -0,0 +1,112 @@
+package com.baeldung.annotations;
+
+import java.util.List;
+
+import org.apache.commons.lang3.StringUtils;
+import org.jetbrains.annotations.Contract;
+
+public class Demo {
+
+ @Contract("_ -> new")
+ Person fromName(String name) {
+ return new Person().withName(name);
+ }
+
+ @Contract(" -> fail")
+ void alwaysFail() {
+ throw new RuntimeException();
+ }
+
+ @Contract(" -> fail")
+ void doNothingWithWrongContract() {
+
+ }
+
+ @Contract("_, null -> null; null, _ -> param2; _, !null -> !null")
+ String concatenateOnlyIfSecondArgumentIsNotNull(String head, String tail) {
+ if (tail == null) {
+ return null;
+ }
+ if (head == null) {
+ return tail;
+ }
+ return head + tail;
+ }
+
+ void uselessNullCheck() {
+ String head = "1234";
+ String tail = "5678";
+ String concatenation = concatenateOnlyIfSecondArgumentIsNotNull(head, tail);
+ if (concatenation != null) {
+ System.out.println(concatenation);
+ }
+ }
+
+ void uselessNullCheckOnInferredAnnotation() {
+ if (StringUtils.isEmpty(null)) {
+ System.out.println("baeldung");
+ }
+ }
+
+ @Contract(pure = true)
+ String replace(String string, char oldChar, char newChar) {
+ return string.replace(oldChar, newChar);
+ }
+
+ @Contract(value = "true -> false; false -> true", pure = true)
+ boolean not(boolean input) {
+ return !input;
+ }
+
+ @Contract("true -> new")
+ void contractExpectsWrongParameterType(List integers) {
+
+ }
+
+ @Contract("_, _ -> new")
+ void contractExpectsMoreParametersThanMethodHas(String s) {
+
+ }
+
+ @Contract("_ -> _; null -> !null")
+ String secondContractClauseNotReachable(String s) {
+ return "";
+ }
+
+ @Contract("_ -> true")
+ void contractExpectsWrongReturnType(String s) {
+
+ }
+
+ // NB: the following examples demonstrate how to use the mutates attribute of the annotation
+ // This attribute is currently experimental and could be changed or removed in the future
+ @Contract(mutates = "param")
+ void incrementArrayFirstElement(Integer[] integers) {
+ if (integers.length > 0) {
+ integers[0] = integers[0] + 1;
+ }
+ }
+
+ @Contract(pure = true, mutates = "param")
+ void impossibleToMutateParamInPureFunction(List strings) {
+ if (strings != null) {
+ strings.forEach(System.out::println);
+ }
+ }
+
+ @Contract(mutates = "param3")
+ void impossibleToMutateThirdParamWhenMethodHasOnlyTwoParams(int a, int b) {
+
+ }
+
+ @Contract(mutates = "param")
+ void impossibleToMutableImmutableType(String s) {
+
+ }
+
+ @Contract(mutates = "this")
+ static void impossibleToMutateThisInStaticMethod() {
+
+ }
+
+}
diff --git a/jetbrains/src/main/java/com/baeldung/annotations/Person.java b/jetbrains/src/main/java/com/baeldung/annotations/Person.java
new file mode 100644
index 0000000000..086b73b47f
--- /dev/null
+++ b/jetbrains/src/main/java/com/baeldung/annotations/Person.java
@@ -0,0 +1,15 @@
+package com.baeldung.annotations;
+
+import org.jetbrains.annotations.Contract;
+
+public class Person {
+
+ String name;
+
+ @Contract("_ -> this")
+ Person withName(String name) {
+ this.name = name;
+ return this;
+ }
+
+}
diff --git a/jgit/pom.xml b/jgit/pom.xml
index 91881fbec8..1b0d82e4d7 100644
--- a/jgit/pom.xml
+++ b/jgit/pom.xml
@@ -4,10 +4,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jgit
- 1.0-SNAPSHOT
jgit
jar
- http://maven.apache.org
com.baeldung
@@ -15,14 +13,6 @@
1.0.0-SNAPSHOT
-
-
- jgit-repository
- https://repo.eclipse.org/content/groups/releases/
-
-
-
-
org.eclipse.jgit
@@ -36,6 +26,12 @@
+
+
+ jgit-repository
+ https://repo.eclipse.org/content/groups/releases/
+
+
4.5.0.201609210915-r
diff --git a/jhipster-5/bookstore-monolith/.yo-rc.json b/jhipster-5/bookstore-monolith/.yo-rc.json
deleted file mode 100644
index d852aeeddc..0000000000
--- a/jhipster-5/bookstore-monolith/.yo-rc.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "generator-jhipster": {
- "promptValues": {
- "packageName": "com.baeldung.jhipster5"
- },
- "jhipsterVersion": "5.8.2",
- "applicationType": "monolith",
- "baseName": "Bookstore",
- "packageName": "com.baeldung.jhipster5",
- "packageFolder": "com/baeldung/jhipster5",
- "serverPort": "8080",
- "authenticationType": "jwt",
- "cacheProvider": "no",
- "websocket": false,
- "databaseType": "sql",
- "devDatabaseType": "h2Memory",
- "prodDatabaseType": "mysql",
- "searchEngine": false,
- "messageBroker": false,
- "serviceDiscoveryType": false,
- "buildTool": "maven",
- "enableSwaggerCodegen": false,
- "jwtSecretKey": "NDJmOTVlZjI2NzhlZDRjNmVkNTM1NDE2NjkyNDljZDJiNzBlMjI5YmZjMjY3MzdjZmZlMjI3NjE4OTRkNzc5MWYzNDNlYWMzYmJjOWRmMjc5ZWQyZTZmOWZkOTMxZWZhNWE1MTVmM2U2NjFmYjhlNDc2Y2Q3NzliMGY0YzFkNmI=",
- "clientFramework": "angularX",
- "useSass": true,
- "clientPackageManager": "npm",
- "testFrameworks": [],
- "jhiPrefix": "jhi",
- "entitySuffix": "",
- "dtoSuffix": "DTO",
- "otherModules": [],
- "enableTranslation": false
- }
-}
diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/audit/package-info.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/audit/package-info.java
deleted file mode 100644
index 49a2a73a61..0000000000
--- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/config/audit/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Audit specific code.
- */
-package com.baeldung.jhipster5.config.audit;
diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/package-info.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/package-info.java
deleted file mode 100644
index eba92a598e..0000000000
--- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/domain/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * JPA domain objects.
- */
-package com.baeldung.jhipster5.domain;
diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/package-info.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/package-info.java
deleted file mode 100644
index a5002eb201..0000000000
--- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/repository/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Spring Data JPA repositories.
- */
-package com.baeldung.jhipster5.repository;
diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/package-info.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/package-info.java
deleted file mode 100644
index 87951796ea..0000000000
--- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/dto/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Data Transfer Objects.
- */
-package com.baeldung.jhipster5.service.dto;
diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/package-info.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/package-info.java
deleted file mode 100644
index a54ed5cca0..0000000000
--- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/service/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Service layer beans.
- */
-package com.baeldung.jhipster5.service;
diff --git a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/package-info.java b/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/package-info.java
deleted file mode 100644
index 75bf6840f6..0000000000
--- a/jhipster-5/bookstore-monolith/src/main/java/com/baeldung/jhipster5/web/rest/package-info.java
+++ /dev/null
@@ -1,4 +0,0 @@
-/**
- * Spring MVC REST controllers.
- */
-package com.baeldung.jhipster5.web.rest;
diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/logs/logs.component.spec.ts b/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/logs/logs.component.spec.ts
deleted file mode 100644
index def356c0f2..0000000000
--- a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/logs/logs.component.spec.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { ComponentFixture, TestBed, async } from '@angular/core/testing';
-import { of } from 'rxjs';
-import { HttpHeaders, HttpResponse } from '@angular/common/http';
-
-import { BookstoreTestModule } from '../../../test.module';
-import { LogsComponent } from 'app/admin/logs/logs.component';
-import { LogsService } from 'app/admin/logs/logs.service';
-import { ITEMS_PER_PAGE } from 'app/shared';
-import { Log } from 'app/admin';
-
-describe('Component Tests', () => {
- describe('LogsComponent', () => {
- let comp: LogsComponent;
- let fixture: ComponentFixture;
- let service: LogsService;
-
- beforeEach(async(() => {
- TestBed.configureTestingModule({
- imports: [BookstoreTestModule],
- declarations: [LogsComponent],
- providers: [LogsService]
- })
- .overrideTemplate(LogsComponent, '')
- .compileComponents();
- }));
-
- beforeEach(() => {
- fixture = TestBed.createComponent(LogsComponent);
- comp = fixture.componentInstance;
- service = fixture.debugElement.injector.get(LogsService);
- });
-
- describe('OnInit', () => {
- it('should set all default values correctly', () => {
- expect(comp.filter).toBe('');
- expect(comp.orderProp).toBe('name');
- expect(comp.reverse).toBe(false);
- });
- it('Should call load all on init', () => {
- // GIVEN
- const headers = new HttpHeaders().append('link', 'link;link');
- const log = new Log('main', 'WARN');
- spyOn(service, 'findAll').and.returnValue(
- of(
- new HttpResponse({
- body: [log],
- headers
- })
- )
- );
-
- // WHEN
- comp.ngOnInit();
-
- // THEN
- expect(service.findAll).toHaveBeenCalled();
- expect(comp.loggers[0]).toEqual(jasmine.objectContaining(log));
- });
- });
- describe('change log level', () => {
- it('should change log level correctly', () => {
- // GIVEN
- const log = new Log('main', 'ERROR');
- spyOn(service, 'changeLevel').and.returnValue(of(new HttpResponse()));
- spyOn(service, 'findAll').and.returnValue(of(new HttpResponse({ body: [log] })));
-
- // WHEN
- comp.changeLevel('main', 'ERROR');
-
- // THEN
- expect(service.changeLevel).toHaveBeenCalled();
- expect(service.findAll).toHaveBeenCalled();
- expect(comp.loggers[0]).toEqual(jasmine.objectContaining(log));
- });
- });
- });
-});
diff --git a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/logs/logs.service.spec.ts b/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/logs/logs.service.spec.ts
deleted file mode 100644
index c34833922e..0000000000
--- a/jhipster-5/bookstore-monolith/src/test/javascript/spec/app/admin/logs/logs.service.spec.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { TestBed } from '@angular/core/testing';
-
-import { LogsService } from 'app/admin/logs/logs.service';
-import { Log } from 'app/admin/logs/log.model';
-import { SERVER_API_URL } from 'app/app.constants';
-import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
-
-describe('Service Tests', () => {
- describe('Logs Service', () => {
- let service: LogsService;
- let httpMock;
-
- beforeEach(() => {
- TestBed.configureTestingModule({
- imports: [HttpClientTestingModule]
- });
-
- service = TestBed.get(LogsService);
- httpMock = TestBed.get(HttpTestingController);
- });
-
- afterEach(() => {
- httpMock.verify();
- });
-
- describe('Service methods', () => {
- it('should call correct URL', () => {
- service.findAll().subscribe(() => {});
-
- const req = httpMock.expectOne({ method: 'GET' });
- const resourceUrl = SERVER_API_URL + 'management/logs';
- expect(req.request.url).toEqual(resourceUrl);
- });
-
- it('should return Logs', () => {
- const log = new Log('main', 'ERROR');
-
- service.findAll().subscribe(received => {
- expect(received.body[0]).toEqual(log);
- });
-
- const req = httpMock.expectOne({ method: 'GET' });
- req.flush([log]);
- });
-
- it('should change log level', () => {
- const log = new Log('main', 'ERROR');
-
- service.changeLevel(log).subscribe(received => {
- expect(received.body[0]).toEqual(log);
- });
-
- const req = httpMock.expectOne({ method: 'PUT' });
- req.flush([log]);
- });
- });
- });
-});
diff --git a/jhipster-5/README.md b/jhipster-6/README.md
similarity index 89%
rename from jhipster-5/README.md
rename to jhipster-6/README.md
index ba05641af0..9db409a032 100644
--- a/jhipster-5/README.md
+++ b/jhipster-6/README.md
@@ -1,3 +1,3 @@
-## JHipster 5
+## JHipster 6
This module contains articles about JHipster 5. This is an aggregator module, articles are in the relevant submodules.
diff --git a/jhipster-5/bookstore-monolith/.editorconfig b/jhipster-6/bookstore-monolith/.editorconfig
similarity index 100%
rename from jhipster-5/bookstore-monolith/.editorconfig
rename to jhipster-6/bookstore-monolith/.editorconfig
diff --git a/jhipster-5/bookstore-monolith/.gitattributes b/jhipster-6/bookstore-monolith/.gitattributes
similarity index 100%
rename from jhipster-5/bookstore-monolith/.gitattributes
rename to jhipster-6/bookstore-monolith/.gitattributes
diff --git a/jhipster-5/bookstore-monolith/.gitignore b/jhipster-6/bookstore-monolith/.gitignore
similarity index 100%
rename from jhipster-5/bookstore-monolith/.gitignore
rename to jhipster-6/bookstore-monolith/.gitignore
diff --git a/jhipster-5/bookstore-monolith/.huskyrc b/jhipster-6/bookstore-monolith/.huskyrc
similarity index 100%
rename from jhipster-5/bookstore-monolith/.huskyrc
rename to jhipster-6/bookstore-monolith/.huskyrc
diff --git a/jhipster-5/bookstore-monolith/.jhipster/Book.json b/jhipster-6/bookstore-monolith/.jhipster/Book.json
similarity index 100%
rename from jhipster-5/bookstore-monolith/.jhipster/Book.json
rename to jhipster-6/bookstore-monolith/.jhipster/Book.json
diff --git a/jhipster-5/bookstore-monolith/.mvn/wrapper/MavenWrapperDownloader.java b/jhipster-6/bookstore-monolith/.mvn/wrapper/MavenWrapperDownloader.java
similarity index 100%
rename from jhipster-5/bookstore-monolith/.mvn/wrapper/MavenWrapperDownloader.java
rename to jhipster-6/bookstore-monolith/.mvn/wrapper/MavenWrapperDownloader.java
diff --git a/jhipster-5/bookstore-monolith/.mvn/wrapper/maven-wrapper.jar b/jhipster-6/bookstore-monolith/.mvn/wrapper/maven-wrapper.jar
similarity index 100%
rename from jhipster-5/bookstore-monolith/.mvn/wrapper/maven-wrapper.jar
rename to jhipster-6/bookstore-monolith/.mvn/wrapper/maven-wrapper.jar
diff --git a/jhipster-5/bookstore-monolith/.mvn/wrapper/maven-wrapper.properties b/jhipster-6/bookstore-monolith/.mvn/wrapper/maven-wrapper.properties
similarity index 100%
rename from jhipster-5/bookstore-monolith/.mvn/wrapper/maven-wrapper.properties
rename to jhipster-6/bookstore-monolith/.mvn/wrapper/maven-wrapper.properties
diff --git a/jhipster-5/bookstore-monolith/.prettierignore b/jhipster-6/bookstore-monolith/.prettierignore
similarity index 100%
rename from jhipster-5/bookstore-monolith/.prettierignore
rename to jhipster-6/bookstore-monolith/.prettierignore
diff --git a/jhipster-5/bookstore-monolith/.prettierrc b/jhipster-6/bookstore-monolith/.prettierrc
similarity index 100%
rename from jhipster-5/bookstore-monolith/.prettierrc
rename to jhipster-6/bookstore-monolith/.prettierrc
diff --git a/jhipster-6/bookstore-monolith/.yo-rc.json b/jhipster-6/bookstore-monolith/.yo-rc.json
new file mode 100644
index 0000000000..3ec14d8ada
--- /dev/null
+++ b/jhipster-6/bookstore-monolith/.yo-rc.json
@@ -0,0 +1,36 @@
+{
+ "generator-jhipster": {
+ "promptValues": {
+ "packageName": "com.baeldung.jhipster5"
+ },
+ "jhipsterVersion": "6.0.0",
+ "applicationType": "monolith",
+ "baseName": "Bookstore",
+ "packageName": "com.baeldung.jhipster5",
+ "packageFolder": "com/baeldung/jhipster5",
+ "serverPort": "8080",
+ "authenticationType": "jwt",
+ "cacheProvider": "no",
+ "websocket": false,
+ "databaseType": "sql",
+ "devDatabaseType": "h2Memory",
+ "prodDatabaseType": "mysql",
+ "searchEngine": false,
+ "messageBroker": false,
+ "serviceDiscoveryType": false,
+ "buildTool": "maven",
+ "enableSwaggerCodegen": false,
+ "jwtSecretKey": "NDJmOTVlZjI2NzhlZDRjNmVkNTM1NDE2NjkyNDljZDJiNzBlMjI5YmZjMjY3MzdjZmZlMjI3NjE4OTRkNzc5MWYzNDNlYWMzYmJjOWRmMjc5ZWQyZTZmOWZkOTMxZWZhNWE1MTVmM2U2NjFmYjhlNDc2Y2Q3NzliMGY0YzFkNmI=",
+ "clientFramework": "angularX",
+ "useSass": true,
+ "clientPackageManager": "npm",
+ "testFrameworks": [],
+ "jhiPrefix": "jhi",
+ "entitySuffix": "",
+ "dtoSuffix": "DTO",
+ "otherModules": [],
+ "enableTranslation": false,
+ "enableHibernateCache": false,
+ "clientTheme": "none"
+ }
+}
\ No newline at end of file
diff --git a/jhipster-5/bookstore-monolith/README.md b/jhipster-6/bookstore-monolith/README.md
similarity index 100%
rename from jhipster-5/bookstore-monolith/README.md
rename to jhipster-6/bookstore-monolith/README.md
diff --git a/jhipster-5/bookstore-monolith/angular.json b/jhipster-6/bookstore-monolith/angular.json
similarity index 100%
rename from jhipster-5/bookstore-monolith/angular.json
rename to jhipster-6/bookstore-monolith/angular.json
diff --git a/jhipster-5/bookstore-monolith/mvnw b/jhipster-6/bookstore-monolith/mvnw
old mode 100755
new mode 100644
similarity index 100%
rename from jhipster-5/bookstore-monolith/mvnw
rename to jhipster-6/bookstore-monolith/mvnw
diff --git a/jhipster-5/bookstore-monolith/mvnw.cmd b/jhipster-6/bookstore-monolith/mvnw.cmd
similarity index 100%
rename from jhipster-5/bookstore-monolith/mvnw.cmd
rename to jhipster-6/bookstore-monolith/mvnw.cmd
diff --git a/jhipster-5/bookstore-monolith/package.json b/jhipster-6/bookstore-monolith/package.json
similarity index 99%
rename from jhipster-5/bookstore-monolith/package.json
rename to jhipster-6/bookstore-monolith/package.json
index 46b920edb3..76b74a4312 100644
--- a/jhipster-5/bookstore-monolith/package.json
+++ b/jhipster-6/bookstore-monolith/package.json
@@ -51,7 +51,7 @@
"file-loader": "3.0.1",
"fork-ts-checker-webpack-plugin": "0.5.2",
"friendly-errors-webpack-plugin": "1.7.0",
- "generator-jhipster": "5.8.2",
+ "generator-jhipster": "6.0.0",
"html-loader": "0.5.5",
"html-webpack-plugin": "3.2.0",
"husky": "1.3.1",
diff --git a/jhipster-5/bookstore-monolith/pom.xml b/jhipster-6/bookstore-monolith/pom.xml
similarity index 89%
rename from jhipster-5/bookstore-monolith/pom.xml
rename to jhipster-6/bookstore-monolith/pom.xml
index ccaa802a39..f719baab8b 100644
--- a/jhipster-5/bookstore-monolith/pom.xml
+++ b/jhipster-6/bookstore-monolith/pom.xml
@@ -2,14 +2,14 @@
4.0.0
- com.baeldung.jhipster5
+ com.baeldung.jhipster6
bookstore-monolith
0.0.1-SNAPSHOT
war
bookstore-monolith
- jhipster-5
+ jhipster-6
com.baeldung.jhipster
1.0.0-SNAPSHOT
@@ -41,8 +41,25 @@
io.github.jhipster
jhipster-framework
+ 3.0.1
+
+
+ jakarta.xml.bind
+ jakarta.xml.bind-api
+ 4.0.0
+
+
+
+ org.glassfish.jaxb
+ jaxb-runtime
+ 4.0.0
+
+
+
+
+
com.fasterxml.jackson.datatype
jackson-datatype-hibernate5
@@ -78,10 +95,10 @@
io.springfox
springfox-bean-validators
-
- com.mattbertolini
- liquibase-slf4j
-
+
+
+
+
com.zaxxer
HikariCP
@@ -94,6 +111,10 @@
org.apache.commons
commons-lang3
+
+ mysql
+ mysql-connector-java
+
org.assertj
assertj-core
@@ -120,9 +141,13 @@
net.logstash.logback
logstash-logback-encoder
+
+
+
+
org.mapstruct
- mapstruct-jdk8
+ mapstruct
org.mapstruct
@@ -269,6 +294,11 @@
hibernate-jpamodelgen
${hibernate.version}
+
+ org.glassfish.jaxb
+ jaxb-runtime
+ ${jaxb-runtime.version}
+
@@ -492,9 +522,8 @@
[${maven.version},)
-
- You are running an incompatible version of Java. JHipster requires JDK ${java.version}
- [1.8,1.9)
+ You are running an incompatible version of Java. JHipster supports JDK 11.
+ [${java.version},)
@@ -681,6 +710,9 @@
npm
+
+ install --legacy-peer-deps
+
webpack build dev
@@ -1023,135 +1055,12 @@
-
-
- default-first
-
-
-
-
- com.github.eirslett
- frontend-maven-plugin
-
-
-
- install node and npm
- none
-
-
- npm install
- none
-
-
- webpack build dev
- none
-
-
- webpack build test
- none
-
-
-
-
-
-
-
- default-second
-
-
-
-
- com.github.eirslett
- frontend-maven-plugin
-
-
-
- install node and npm
- none
-
-
- npm install
- none
-
-
- webpack build dev
- none
-
-
- webpack build test
- none
-
-
-
-
-
-
-
- integration-lite-first
-
-
-
- com.github.eirslett
- frontend-maven-plugin
-
-
-
- install node and npm
- none
-
-
- npm install
- none
-
-
- webpack build dev
- none
-
-
- webpack build test
- none
-
-
-
-
-
-
-
- integration-lite-second
-
-
-
- com.github.eirslett
- frontend-maven-plugin
-
-
-
- install node and npm
- none
-
-
- npm install
- none
-
-
- webpack build dev
- none
-
-
- webpack build test
- none
-
-
-
-
-
-
3.0.0
- 1.8
+ 11
2.12.6
v10.15.0
6.4.1
@@ -1168,34 +1077,36 @@
- 2.1.1
+ 3.0.1
- 2.7.8
+ 2.7.5
- 5.2.17.Final
+ 5.3.9.Final
- 3.22.0-GA
+ 3.23.1-GA
- 3.5.5
+ 3.6.3
3.6
+ 5.1.5.RELEASE
2.0.1.Final
- 1.2.0.Final
+ 2.3.2
+ 1.3.0.Final
3.1.0
3.8.0
2.10
- 3.0.0-M2
+ 3.0.0-M1
2.2.1
3.1.0
- 2.22.2
+ 3.0.0-M3
3.2.2
0.9.11
- 1.6
+ 1.7.6
0.8.2
1.0.0
3.4.2
diff --git a/jhipster-5/bookstore-monolith/postcss.config.js b/jhipster-6/bookstore-monolith/postcss.config.js
similarity index 100%
rename from jhipster-5/bookstore-monolith/postcss.config.js
rename to jhipster-6/bookstore-monolith/postcss.config.js
diff --git a/jhipster-5/bookstore-monolith/proxy.conf.json b/jhipster-6/bookstore-monolith/proxy.conf.json
similarity index 100%
rename from jhipster-5/bookstore-monolith/proxy.conf.json
rename to jhipster-6/bookstore-monolith/proxy.conf.json
diff --git a/jhipster-5/bookstore-monolith/src/main/docker/.dockerignore b/jhipster-6/bookstore-monolith/src/main/docker/.dockerignore
similarity index 100%
rename from jhipster-5/bookstore-monolith/src/main/docker/.dockerignore
rename to jhipster-6/bookstore-monolith/src/main/docker/.dockerignore
diff --git a/jhipster-5/bookstore-monolith/src/main/docker/Dockerfile b/jhipster-6/bookstore-monolith/src/main/docker/Dockerfile
similarity index 100%
rename from jhipster-5/bookstore-monolith/src/main/docker/Dockerfile
rename to jhipster-6/bookstore-monolith/src/main/docker/Dockerfile
diff --git a/jhipster-5/bookstore-monolith/src/main/docker/app.yml b/jhipster-6/bookstore-monolith/src/main/docker/app.yml
similarity index 100%
rename from jhipster-5/bookstore-monolith/src/main/docker/app.yml
rename to jhipster-6/bookstore-monolith/src/main/docker/app.yml
diff --git a/jhipster-5/bookstore-monolith/src/main/docker/entrypoint.sh b/jhipster-6/bookstore-monolith/src/main/docker/entrypoint.sh
similarity index 100%
rename from jhipster-5/bookstore-monolith/src/main/docker/entrypoint.sh
rename to jhipster-6/bookstore-monolith/src/main/docker/entrypoint.sh
diff --git a/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/dashboards/JVM.json b/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/dashboards/JVM.json
new file mode 100644
index 0000000000..b299032c99
--- /dev/null
+++ b/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/dashboards/JVM.json
@@ -0,0 +1,3778 @@
+{
+ "annotations": {
+ "list": [
+ {
+ "builtIn": 1,
+ "datasource": "-- Grafana --",
+ "enable": true,
+ "hide": true,
+ "iconColor": "rgba(0, 211, 255, 1)",
+ "limit": 100,
+ "name": "Annotations & Alerts",
+ "showIn": 0,
+ "type": "dashboard"
+ },
+ {
+ "datasource": "Prometheus",
+ "enable": true,
+ "expr": "resets(process_uptime_seconds{application=\"$application\", instance=\"$instance\"}[1m]) > 0",
+ "iconColor": "rgba(255, 96, 96, 1)",
+ "name": "Restart Detection",
+ "showIn": 0,
+ "step": "1m",
+ "tagKeys": "restart-tag",
+ "textFormat": "uptime reset",
+ "titleFormat": "Restart"
+ }
+ ]
+ },
+ "description": "Dashboard for Micrometer instrumented applications (Java, Spring Boot, Micronaut)",
+ "editable": true,
+ "gnetId": 4701,
+ "graphTooltip": 1,
+ "iteration": 1553765841423,
+ "links": [],
+ "panels": [
+ {
+ "content": "\n# Acknowledgments\n\nThank you to [Michael Weirauch](https://twitter.com/emwexx) for creating this dashboard: see original JVM (Micrometer) dashboard at [https://grafana.com/dashboards/4701](https://grafana.com/dashboards/4701)\n\n\n\n",
+ "gridPos": {
+ "h": 3,
+ "w": 24,
+ "x": 0,
+ "y": 0
+ },
+ "id": 141,
+ "links": [],
+ "mode": "markdown",
+ "timeFrom": null,
+ "timeShift": null,
+ "title": "Acknowledgments",
+ "type": "text"
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 3
+ },
+ "id": 125,
+ "panels": [],
+ "repeat": null,
+ "title": "Quick Facts",
+ "type": "row"
+ },
+ {
+ "cacheTimeout": null,
+ "colorBackground": false,
+ "colorValue": true,
+ "colors": ["rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)"],
+ "datasource": "Prometheus",
+ "decimals": 1,
+ "editable": true,
+ "error": false,
+ "format": "s",
+ "gauge": {
+ "maxValue": 100,
+ "minValue": 0,
+ "show": false,
+ "thresholdLabels": false,
+ "thresholdMarkers": true
+ },
+ "gridPos": {
+ "h": 3,
+ "w": 6,
+ "x": 0,
+ "y": 4
+ },
+ "height": "",
+ "id": 63,
+ "interval": null,
+ "links": [],
+ "mappingType": 1,
+ "mappingTypes": [
+ {
+ "name": "value to text",
+ "value": 1
+ },
+ {
+ "name": "range to text",
+ "value": 2
+ }
+ ],
+ "maxDataPoints": 100,
+ "nullPointMode": "connected",
+ "nullText": null,
+ "postfix": "",
+ "postfixFontSize": "50%",
+ "prefix": "",
+ "prefixFontSize": "70%",
+ "rangeMaps": [
+ {
+ "from": "null",
+ "text": "N/A",
+ "to": "null"
+ }
+ ],
+ "sparkline": {
+ "fillColor": "rgba(31, 118, 189, 0.18)",
+ "full": false,
+ "lineColor": "rgb(31, 120, 193)",
+ "show": false
+ },
+ "tableColumn": "",
+ "targets": [
+ {
+ "expr": "process_uptime_seconds{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "",
+ "metric": "",
+ "refId": "A",
+ "step": 14400
+ }
+ ],
+ "thresholds": "",
+ "title": "Uptime",
+ "type": "singlestat",
+ "valueFontSize": "80%",
+ "valueMaps": [
+ {
+ "op": "=",
+ "text": "N/A",
+ "value": "null"
+ }
+ ],
+ "valueName": "current"
+ },
+ {
+ "cacheTimeout": null,
+ "colorBackground": false,
+ "colorValue": true,
+ "colors": ["rgba(245, 54, 54, 0.9)", "rgba(237, 129, 40, 0.89)", "rgba(50, 172, 45, 0.97)"],
+ "datasource": "Prometheus",
+ "decimals": null,
+ "editable": true,
+ "error": false,
+ "format": "dateTimeAsIso",
+ "gauge": {
+ "maxValue": 100,
+ "minValue": 0,
+ "show": false,
+ "thresholdLabels": false,
+ "thresholdMarkers": true
+ },
+ "gridPos": {
+ "h": 3,
+ "w": 6,
+ "x": 6,
+ "y": 4
+ },
+ "height": "",
+ "id": 92,
+ "interval": null,
+ "links": [],
+ "mappingType": 1,
+ "mappingTypes": [
+ {
+ "name": "value to text",
+ "value": 1
+ },
+ {
+ "name": "range to text",
+ "value": 2
+ }
+ ],
+ "maxDataPoints": 100,
+ "nullPointMode": "connected",
+ "nullText": null,
+ "postfix": "",
+ "postfixFontSize": "50%",
+ "prefix": "",
+ "prefixFontSize": "70%",
+ "rangeMaps": [
+ {
+ "from": "null",
+ "text": "N/A",
+ "to": "null"
+ }
+ ],
+ "sparkline": {
+ "fillColor": "rgba(31, 118, 189, 0.18)",
+ "full": false,
+ "lineColor": "rgb(31, 120, 193)",
+ "show": false
+ },
+ "tableColumn": "",
+ "targets": [
+ {
+ "expr": "process_start_time_seconds{application=\"$application\", instance=\"$instance\"}*1000",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "",
+ "metric": "",
+ "refId": "A",
+ "step": 14400
+ }
+ ],
+ "thresholds": "",
+ "title": "Start time",
+ "type": "singlestat",
+ "valueFontSize": "70%",
+ "valueMaps": [
+ {
+ "op": "=",
+ "text": "N/A",
+ "value": "null"
+ }
+ ],
+ "valueName": "current"
+ },
+ {
+ "cacheTimeout": null,
+ "colorBackground": false,
+ "colorValue": true,
+ "colors": ["rgba(50, 172, 45, 0.97)", "rgba(237, 129, 40, 0.89)", "rgba(245, 54, 54, 0.9)"],
+ "datasource": "Prometheus",
+ "decimals": 2,
+ "editable": true,
+ "error": false,
+ "format": "percent",
+ "gauge": {
+ "maxValue": 100,
+ "minValue": 0,
+ "show": false,
+ "thresholdLabels": false,
+ "thresholdMarkers": true
+ },
+ "gridPos": {
+ "h": 3,
+ "w": 6,
+ "x": 12,
+ "y": 4
+ },
+ "id": 65,
+ "interval": null,
+ "links": [],
+ "mappingType": 1,
+ "mappingTypes": [
+ {
+ "name": "value to text",
+ "value": 1
+ },
+ {
+ "name": "range to text",
+ "value": 2
+ }
+ ],
+ "maxDataPoints": 100,
+ "nullPointMode": "connected",
+ "nullText": null,
+ "postfix": "",
+ "postfixFontSize": "50%",
+ "prefix": "",
+ "prefixFontSize": "70%",
+ "rangeMaps": [
+ {
+ "from": "null",
+ "text": "N/A",
+ "to": "null"
+ }
+ ],
+ "sparkline": {
+ "fillColor": "rgba(31, 118, 189, 0.18)",
+ "full": false,
+ "lineColor": "rgb(31, 120, 193)",
+ "show": false
+ },
+ "tableColumn": "",
+ "targets": [
+ {
+ "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"})*100/sum(jvm_memory_max_bytes{application=\"$application\",instance=\"$instance\", area=\"heap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "",
+ "refId": "A",
+ "step": 14400
+ }
+ ],
+ "thresholds": "70,90",
+ "title": "Heap used",
+ "type": "singlestat",
+ "valueFontSize": "80%",
+ "valueMaps": [
+ {
+ "op": "=",
+ "text": "N/A",
+ "value": "null"
+ }
+ ],
+ "valueName": "current"
+ },
+ {
+ "cacheTimeout": null,
+ "colorBackground": false,
+ "colorValue": true,
+ "colors": ["rgba(50, 172, 45, 0.97)", "rgba(237, 129, 40, 0.89)", "rgba(245, 54, 54, 0.9)"],
+ "datasource": "Prometheus",
+ "decimals": 2,
+ "editable": true,
+ "error": false,
+ "format": "percent",
+ "gauge": {
+ "maxValue": 100,
+ "minValue": 0,
+ "show": false,
+ "thresholdLabels": false,
+ "thresholdMarkers": true
+ },
+ "gridPos": {
+ "h": 3,
+ "w": 6,
+ "x": 18,
+ "y": 4
+ },
+ "id": 75,
+ "interval": null,
+ "links": [],
+ "mappingType": 2,
+ "mappingTypes": [
+ {
+ "name": "value to text",
+ "value": 1
+ },
+ {
+ "name": "range to text",
+ "value": 2
+ }
+ ],
+ "maxDataPoints": 100,
+ "nullPointMode": "connected",
+ "nullText": null,
+ "postfix": "",
+ "postfixFontSize": "50%",
+ "prefix": "",
+ "prefixFontSize": "70%",
+ "rangeMaps": [
+ {
+ "from": "null",
+ "text": "N/A",
+ "to": "null"
+ },
+ {
+ "from": "-99999999999999999999999999999999",
+ "text": "N/A",
+ "to": "0"
+ }
+ ],
+ "sparkline": {
+ "fillColor": "rgba(31, 118, 189, 0.18)",
+ "full": false,
+ "lineColor": "rgb(31, 120, 193)",
+ "show": false
+ },
+ "tableColumn": "",
+ "targets": [
+ {
+ "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"})*100/sum(jvm_memory_max_bytes{application=\"$application\",instance=\"$instance\", area=\"nonheap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "",
+ "refId": "A",
+ "step": 14400
+ }
+ ],
+ "thresholds": "70,90",
+ "title": "Non-Heap used",
+ "type": "singlestat",
+ "valueFontSize": "80%",
+ "valueMaps": [
+ {
+ "op": "=",
+ "text": "N/A",
+ "value": "null"
+ },
+ {
+ "op": "=",
+ "text": "x",
+ "value": ""
+ }
+ ],
+ "valueName": "current"
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 7
+ },
+ "id": 126,
+ "panels": [],
+ "repeat": null,
+ "title": "I/O Overview",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 0,
+ "y": 8
+ },
+ "id": 111,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "sum(rate(http_server_requests_seconds_count{application=\"$application\", instance=\"$instance\"}[1m]))",
+ "format": "time_series",
+ "intervalFactor": 1,
+ "legendFormat": "HTTP",
+ "refId": "A"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Rate",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "decimals": null,
+ "format": "ops",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {
+ "HTTP": "#890f02",
+ "HTTP - 5xx": "#bf1b00"
+ },
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 8,
+ "y": 8
+ },
+ "id": 112,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "sum(rate(http_server_requests_seconds_count{application=\"$application\", instance=\"$instance\", status=~\"5..\"}[1m]))",
+ "format": "time_series",
+ "intervalFactor": 1,
+ "legendFormat": "HTTP - 5xx",
+ "refId": "A"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Errors",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "decimals": null,
+ "format": "ops",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 16,
+ "y": 8
+ },
+ "id": 113,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "sum(rate(http_server_requests_seconds_sum{application=\"$application\", instance=\"$instance\", status!~\"5..\"}[1m]))/sum(rate(http_server_requests_seconds_count{application=\"$application\", instance=\"$instance\", status!~\"5..\"}[1m]))",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 1,
+ "legendFormat": "HTTP - AVG",
+ "refId": "A"
+ },
+ {
+ "expr": "max(http_server_requests_seconds_max{application=\"$application\", instance=\"$instance\", status!~\"5..\"})",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 1,
+ "legendFormat": "HTTP - MAX",
+ "refId": "B"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Duration",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "format": "s",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 15
+ },
+ "id": 127,
+ "panels": [],
+ "repeat": null,
+ "title": "JVM Memory",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 0,
+ "y": 16
+ },
+ "id": 24,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "sum(jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "committed",
+ "refId": "B",
+ "step": 2400
+ },
+ {
+ "expr": "sum(jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "refId": "C",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "JVM Heap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 8,
+ "y": 16
+ },
+ "id": 25,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"})",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "sum(jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "committed",
+ "refId": "B",
+ "step": 2400
+ },
+ {
+ "expr": "sum(jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "refId": "C",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "JVM Non-Heap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 16,
+ "y": 16
+ },
+ "id": 26,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "sum(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "sum(jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "committed",
+ "refId": "B",
+ "step": 2400
+ },
+ {
+ "expr": "sum(jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\"})",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "refId": "C",
+ "step": 2400
+ },
+ {
+ "expr": "process_memory_vss_bytes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "hide": true,
+ "intervalFactor": 2,
+ "legendFormat": "vss",
+ "metric": "",
+ "refId": "D",
+ "step": 2400
+ },
+ {
+ "expr": "process_memory_rss_bytes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "rss",
+ "refId": "E",
+ "step": 2400
+ },
+ {
+ "expr": "process_memory_pss_bytes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "pss",
+ "refId": "F",
+ "step": 2400
+ },
+ {
+ "expr": "process_memory_swap_bytes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "swap",
+ "refId": "G",
+ "step": 2400
+ },
+ {
+ "expr": "process_memory_swappss_bytes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "swappss",
+ "refId": "H",
+ "step": 2400
+ },
+ {
+ "expr": "process_memory_pss_bytes{application=\"$application\", instance=\"$instance\"} + process_memory_swap_bytes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "phys (pss+swap)",
+ "refId": "I",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "JVM Total",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": "",
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 23
+ },
+ "id": 128,
+ "panels": [],
+ "repeat": null,
+ "title": "JVM Misc",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 0,
+ "y": 24
+ },
+ "id": 106,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "system_cpu_usage{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 1,
+ "legendFormat": "system",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "process_cpu_usage{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 1,
+ "legendFormat": "process",
+ "refId": "B"
+ },
+ {
+ "expr": "avg_over_time(process_cpu_usage{application=\"$application\", instance=\"$instance\"}[1h])",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 1,
+ "legendFormat": "process-1h",
+ "refId": "C"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "CPU",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 1,
+ "format": "percentunit",
+ "label": "",
+ "logBase": 1,
+ "max": "1",
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 6,
+ "y": 24
+ },
+ "id": 93,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "system_load_average_1m{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "system-1m",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "refId": "B"
+ },
+ {
+ "expr": "system_cpu_count{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "cpu",
+ "refId": "C"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Load",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 1,
+ "format": "short",
+ "label": "",
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 12,
+ "y": 24
+ },
+ "id": 32,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_threads_live{application=\"$application\", instance=\"$instance\"} or jvm_threads_live_threads{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "live",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "jvm_threads_daemon{application=\"$application\", instance=\"$instance\"} or jvm_threads_daemon_threads{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "daemon",
+ "metric": "",
+ "refId": "B",
+ "step": 2400
+ },
+ {
+ "expr": "jvm_threads_peak{application=\"$application\", instance=\"$instance\"} or jvm_threads_peak_threads{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "peak",
+ "refId": "C",
+ "step": 2400
+ },
+ {
+ "expr": "process_threads{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "process",
+ "refId": "D",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Threads",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 0,
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {
+ "blocked": "#bf1b00",
+ "new": "#fce2de",
+ "runnable": "#7eb26d",
+ "terminated": "#511749",
+ "timed-waiting": "#c15c17",
+ "waiting": "#eab839"
+ },
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 18,
+ "y": 24
+ },
+ "id": 124,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_threads_states_threads{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "{{state}}",
+ "refId": "A"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Thread States",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {
+ "debug": "#1F78C1",
+ "error": "#BF1B00",
+ "info": "#508642",
+ "trace": "#6ED0E0",
+ "warn": "#EAB839"
+ },
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 18,
+ "x": 0,
+ "y": 31
+ },
+ "height": "",
+ "id": 91,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "hideEmpty": false,
+ "hideZero": false,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": true,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [
+ {
+ "alias": "error",
+ "yaxis": 1
+ },
+ {
+ "alias": "warn",
+ "yaxis": 1
+ }
+ ],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "increase(logback_events_total{application=\"$application\", instance=\"$instance\"}[1m])",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "{{level}}",
+ "metric": "",
+ "refId": "A",
+ "step": 1200
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Log Events (1m)",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 0,
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 18,
+ "y": 31
+ },
+ "id": 61,
+ "legend": {
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "process_open_fds{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 2,
+ "legendFormat": "open",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "process_max_fds{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "B",
+ "step": 2400
+ },
+ {
+ "expr": "process_files_open{application=\"$application\", instance=\"$instance\"} or process_files_open_files{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "open",
+ "refId": "C"
+ },
+ {
+ "expr": "process_files_max{application=\"$application\", instance=\"$instance\"} or process_files_max_files{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "refId": "D"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "File Descriptors",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 0,
+ "format": "short",
+ "label": null,
+ "logBase": 10,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 38
+ },
+ "id": 129,
+ "panels": [],
+ "repeat": "persistence_counts",
+ "title": "JVM Memory Pools (Heap)",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 0,
+ "y": 39
+ },
+ "id": 3,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "maxPerRow": 3,
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "repeat": "jvm_memory_pool_heap",
+ "scopedVars": {
+ "jvm_memory_pool_heap": {
+ "selected": false,
+ "text": "PS Eden Space",
+ "value": "PS Eden Space"
+ }
+ },
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "commited",
+ "metric": "",
+ "refId": "B",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "C",
+ "step": 1800
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "$jvm_memory_pool_heap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 8,
+ "y": 39
+ },
+ "id": 134,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "maxPerRow": 3,
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "repeat": null,
+ "repeatIteration": 1553765841423,
+ "repeatPanelId": 3,
+ "scopedVars": {
+ "jvm_memory_pool_heap": {
+ "selected": false,
+ "text": "PS Old Gen",
+ "value": "PS Old Gen"
+ }
+ },
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "commited",
+ "metric": "",
+ "refId": "B",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "C",
+ "step": 1800
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "$jvm_memory_pool_heap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 16,
+ "y": 39
+ },
+ "id": 135,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "maxPerRow": 3,
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "repeat": null,
+ "repeatIteration": 1553765841423,
+ "repeatPanelId": 3,
+ "scopedVars": {
+ "jvm_memory_pool_heap": {
+ "selected": false,
+ "text": "PS Survivor Space",
+ "value": "PS Survivor Space"
+ }
+ },
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "commited",
+ "metric": "",
+ "refId": "B",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_heap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "C",
+ "step": 1800
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "$jvm_memory_pool_heap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 46
+ },
+ "id": 130,
+ "panels": [],
+ "repeat": null,
+ "title": "JVM Memory Pools (Non-Heap)",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 0,
+ "y": 47
+ },
+ "id": 78,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "maxPerRow": 3,
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "repeat": "jvm_memory_pool_nonheap",
+ "scopedVars": {
+ "jvm_memory_pool_nonheap": {
+ "selected": false,
+ "text": "Metaspace",
+ "value": "Metaspace"
+ }
+ },
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "commited",
+ "metric": "",
+ "refId": "B",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "C",
+ "step": 1800
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "$jvm_memory_pool_nonheap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 8,
+ "y": 47
+ },
+ "id": 136,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "maxPerRow": 3,
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "repeat": null,
+ "repeatIteration": 1553765841423,
+ "repeatPanelId": 78,
+ "scopedVars": {
+ "jvm_memory_pool_nonheap": {
+ "selected": false,
+ "text": "Compressed Class Space",
+ "value": "Compressed Class Space"
+ }
+ },
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "commited",
+ "metric": "",
+ "refId": "B",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "C",
+ "step": 1800
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "$jvm_memory_pool_nonheap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 16,
+ "y": 47
+ },
+ "id": 137,
+ "legend": {
+ "alignAsTable": false,
+ "avg": false,
+ "current": true,
+ "max": true,
+ "min": false,
+ "rightSide": false,
+ "show": true,
+ "total": false,
+ "values": true
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "maxPerRow": 3,
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "repeat": null,
+ "repeatIteration": 1553765841423,
+ "repeatPanelId": 78,
+ "scopedVars": {
+ "jvm_memory_pool_nonheap": {
+ "selected": false,
+ "text": "Code Cache",
+ "value": "Code Cache"
+ }
+ },
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_committed_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "commited",
+ "metric": "",
+ "refId": "B",
+ "step": 1800
+ },
+ {
+ "expr": "jvm_memory_max_bytes{application=\"$application\", instance=\"$instance\", id=\"$jvm_memory_pool_nonheap\"}",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "max",
+ "metric": "",
+ "refId": "C",
+ "step": 1800
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "$jvm_memory_pool_nonheap",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["mbytes", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 54
+ },
+ "id": 131,
+ "panels": [],
+ "repeat": null,
+ "title": "Garbage Collection",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 0,
+ "y": 55
+ },
+ "id": 98,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "rate(jvm_gc_pause_seconds_count{application=\"$application\", instance=\"$instance\"}[1m])",
+ "format": "time_series",
+ "hide": false,
+ "intervalFactor": 2,
+ "legendFormat": "{{action}} ({{cause}})",
+ "refId": "A"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Collections",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "format": "ops",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": "",
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 8,
+ "y": 55
+ },
+ "id": 101,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "rate(jvm_gc_pause_seconds_sum{application=\"$application\", instance=\"$instance\"}[1m])/rate(jvm_gc_pause_seconds_count{application=\"$application\", instance=\"$instance\"}[1m])",
+ "format": "time_series",
+ "hide": false,
+ "instant": false,
+ "intervalFactor": 1,
+ "legendFormat": "avg {{action}} ({{cause}})",
+ "refId": "A"
+ },
+ {
+ "expr": "jvm_gc_pause_seconds_max{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "hide": false,
+ "instant": false,
+ "intervalFactor": 1,
+ "legendFormat": "max {{action}} ({{cause}})",
+ "refId": "B"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Pause Durations",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "format": "s",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": "",
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "fill": 1,
+ "gridPos": {
+ "h": 7,
+ "w": 8,
+ "x": 16,
+ "y": 55
+ },
+ "id": 99,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "rate(jvm_gc_memory_allocated_bytes_total{application=\"$application\", instance=\"$instance\"}[1m])",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 1,
+ "legendFormat": "allocated",
+ "refId": "A"
+ },
+ {
+ "expr": "rate(jvm_gc_memory_promoted_bytes_total{application=\"$application\", instance=\"$instance\"}[1m])",
+ "format": "time_series",
+ "interval": "",
+ "intervalFactor": 1,
+ "legendFormat": "promoted",
+ "refId": "B"
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Allocated/Promoted",
+ "tooltip": {
+ "shared": true,
+ "sort": 0,
+ "value_type": "individual"
+ },
+ "type": "graph",
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": "0",
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 62
+ },
+ "id": 132,
+ "panels": [],
+ "repeat": null,
+ "title": "Classloading",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 12,
+ "x": 0,
+ "y": 63
+ },
+ "id": 37,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_classes_loaded{application=\"$application\", instance=\"$instance\"} or jvm_classes_loaded_classes{application=\"$application\", instance=\"$instance\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "loaded",
+ "metric": "",
+ "refId": "A",
+ "step": 1200
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Classes loaded",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 12,
+ "x": 12,
+ "y": 63
+ },
+ "id": 38,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "delta(jvm_classes_loaded{application=\"$application\",instance=\"$instance\"}[5m]) or delta(jvm_classes_loaded_classes{application=\"$application\",instance=\"$instance\"}[5m])",
+ "format": "time_series",
+ "hide": false,
+ "interval": "",
+ "intervalFactor": 2,
+ "legendFormat": "delta",
+ "metric": "",
+ "refId": "A",
+ "step": 1200
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Class delta (5m)",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["ops", "short"],
+ "yaxes": [
+ {
+ "decimals": null,
+ "format": "short",
+ "label": "",
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "collapsed": false,
+ "gridPos": {
+ "h": 1,
+ "w": 24,
+ "x": 0,
+ "y": 70
+ },
+ "id": 133,
+ "panels": [],
+ "repeat": null,
+ "title": "Buffer Pools",
+ "type": "row"
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 0,
+ "y": 71
+ },
+ "id": 33,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_buffer_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"direct\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "jvm_buffer_total_capacity_bytes{application=\"$application\", instance=\"$instance\", id=\"direct\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "capacity",
+ "metric": "",
+ "refId": "B",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Direct Buffers",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 6,
+ "y": 71
+ },
+ "id": 83,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_buffer_count{application=\"$application\", instance=\"$instance\", id=\"direct\"} or jvm_buffer_count_buffers{application=\"$application\", instance=\"$instance\", id=\"direct\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "count",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Direct Buffers",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 0,
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 12,
+ "y": 71
+ },
+ "id": 85,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_buffer_memory_used_bytes{application=\"$application\", instance=\"$instance\", id=\"mapped\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "used",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ },
+ {
+ "expr": "jvm_buffer_total_capacity_bytes{application=\"$application\", instance=\"$instance\", id=\"mapped\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "capacity",
+ "metric": "",
+ "refId": "B",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Mapped Buffers",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "format": "bytes",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ },
+ {
+ "aliasColors": {},
+ "bars": false,
+ "dashLength": 10,
+ "dashes": false,
+ "datasource": "Prometheus",
+ "editable": true,
+ "error": false,
+ "fill": 1,
+ "grid": {
+ "leftLogBase": 1,
+ "leftMax": null,
+ "leftMin": null,
+ "rightLogBase": 1,
+ "rightMax": null,
+ "rightMin": null
+ },
+ "gridPos": {
+ "h": 7,
+ "w": 6,
+ "x": 18,
+ "y": 71
+ },
+ "id": 84,
+ "legend": {
+ "avg": false,
+ "current": false,
+ "max": false,
+ "min": false,
+ "show": true,
+ "total": false,
+ "values": false
+ },
+ "lines": true,
+ "linewidth": 1,
+ "links": [],
+ "nullPointMode": "null",
+ "paceLength": 10,
+ "percentage": false,
+ "pointradius": 5,
+ "points": false,
+ "renderer": "flot",
+ "seriesOverrides": [],
+ "spaceLength": 10,
+ "stack": false,
+ "steppedLine": false,
+ "targets": [
+ {
+ "expr": "jvm_buffer_count{application=\"$application\", instance=\"$instance\", id=\"mapped\"} or jvm_buffer_count_buffers{application=\"$application\", instance=\"$instance\", id=\"mapped\"}",
+ "format": "time_series",
+ "intervalFactor": 2,
+ "legendFormat": "count",
+ "metric": "",
+ "refId": "A",
+ "step": 2400
+ }
+ ],
+ "thresholds": [],
+ "timeFrom": null,
+ "timeRegions": [],
+ "timeShift": null,
+ "title": "Mapped Buffers",
+ "tooltip": {
+ "msResolution": false,
+ "shared": true,
+ "sort": 0,
+ "value_type": "cumulative"
+ },
+ "type": "graph",
+ "x-axis": true,
+ "xaxis": {
+ "buckets": null,
+ "mode": "time",
+ "name": null,
+ "show": true,
+ "values": []
+ },
+ "y-axis": true,
+ "y_formats": ["short", "short"],
+ "yaxes": [
+ {
+ "decimals": 0,
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": 0,
+ "show": true
+ },
+ {
+ "format": "short",
+ "label": null,
+ "logBase": 1,
+ "max": null,
+ "min": null,
+ "show": true
+ }
+ ],
+ "yaxis": {
+ "align": false,
+ "alignLevel": null
+ }
+ }
+ ],
+ "refresh": "10s",
+ "schemaVersion": 18,
+ "style": "dark",
+ "tags": [],
+ "templating": {
+ "list": [
+ {
+ "allValue": null,
+ "current": {
+ "text": "test",
+ "value": "test"
+ },
+ "datasource": "Prometheus",
+ "definition": "",
+ "hide": 0,
+ "includeAll": false,
+ "label": "Application",
+ "multi": false,
+ "name": "application",
+ "options": [],
+ "query": "label_values(application)",
+ "refresh": 2,
+ "regex": "",
+ "skipUrlSync": false,
+ "sort": 0,
+ "tagValuesQuery": "",
+ "tags": [],
+ "tagsQuery": "",
+ "type": "query",
+ "useTags": false
+ },
+ {
+ "allFormat": "glob",
+ "allValue": null,
+ "current": {
+ "text": "localhost:8080",
+ "value": "localhost:8080"
+ },
+ "datasource": "Prometheus",
+ "definition": "",
+ "hide": 0,
+ "includeAll": false,
+ "label": "Instance",
+ "multi": false,
+ "multiFormat": "glob",
+ "name": "instance",
+ "options": [],
+ "query": "label_values(jvm_memory_used_bytes{application=\"$application\"}, instance)",
+ "refresh": 2,
+ "regex": "",
+ "skipUrlSync": false,
+ "sort": 0,
+ "tagValuesQuery": "",
+ "tags": [],
+ "tagsQuery": "",
+ "type": "query",
+ "useTags": false
+ },
+ {
+ "allFormat": "glob",
+ "allValue": null,
+ "current": {
+ "text": "All",
+ "value": "$__all"
+ },
+ "datasource": "Prometheus",
+ "definition": "",
+ "hide": 0,
+ "includeAll": true,
+ "label": "JVM Memory Pools Heap",
+ "multi": false,
+ "multiFormat": "glob",
+ "name": "jvm_memory_pool_heap",
+ "options": [],
+ "query": "label_values(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"heap\"},id)",
+ "refresh": 1,
+ "regex": "",
+ "skipUrlSync": false,
+ "sort": 1,
+ "tagValuesQuery": "",
+ "tags": [],
+ "tagsQuery": "",
+ "type": "query",
+ "useTags": false
+ },
+ {
+ "allFormat": "glob",
+ "allValue": null,
+ "current": {
+ "text": "All",
+ "value": "$__all"
+ },
+ "datasource": "Prometheus",
+ "definition": "",
+ "hide": 0,
+ "includeAll": true,
+ "label": "JVM Memory Pools Non-Heap",
+ "multi": false,
+ "multiFormat": "glob",
+ "name": "jvm_memory_pool_nonheap",
+ "options": [],
+ "query": "label_values(jvm_memory_used_bytes{application=\"$application\", instance=\"$instance\", area=\"nonheap\"},id)",
+ "refresh": 1,
+ "regex": "",
+ "skipUrlSync": false,
+ "sort": 2,
+ "tagValuesQuery": "",
+ "tags": [],
+ "tagsQuery": "",
+ "type": "query",
+ "useTags": false
+ }
+ ]
+ },
+ "time": {
+ "from": "now-30m",
+ "to": "now"
+ },
+ "timepicker": {
+ "now": true,
+ "refresh_intervals": ["5s", "10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d"],
+ "time_options": ["5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d"]
+ },
+ "timezone": "browser",
+ "title": "JVM (Micrometer)",
+ "uid": "Ud1CFe3iz",
+ "version": 1
+}
diff --git a/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/dashboards/dashboard.yml b/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/dashboards/dashboard.yml
new file mode 100644
index 0000000000..5b46e1f4ca
--- /dev/null
+++ b/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/dashboards/dashboard.yml
@@ -0,0 +1,11 @@
+apiVersion: 1
+
+providers:
+ - name: 'Prometheus'
+ orgId: 1
+ folder: ''
+ type: file
+ disableDeletion: false
+ editable: true
+ options:
+ path: /etc/grafana/provisioning/dashboards
diff --git a/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/datasources/datasource.yml b/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/datasources/datasource.yml
new file mode 100644
index 0000000000..20506dab30
--- /dev/null
+++ b/jhipster-6/bookstore-monolith/src/main/docker/grafana/provisioning/datasources/datasource.yml
@@ -0,0 +1,50 @@
+apiVersion: 1
+
+# list of datasources that should be deleted from the database
+deleteDatasources:
+ - name: Prometheus
+ orgId: 1
+
+# list of datasources to insert/update depending
+# whats available in the database
+datasources:
+ # name of the datasource. Required
+ - name: Prometheus
+ # datasource type. Required
+ type: prometheus
+ # access mode. direct or proxy. Required
+ access: proxy
+ # org id. will default to orgId 1 if not specified
+ orgId: 1
+ # url
+ # On MacOS, replace localhost by host.docker.internal
+ url: http://localhost:9090
+ # database password, if used
+ password:
+ # database user, if used
+ user:
+ # database name, if used
+ database:
+ # enable/disable basic auth
+ basicAuth: false
+ # basic auth username
+ basicAuthUser: admin
+ # basic auth password
+ basicAuthPassword: admin
+ # enable/disable with credentials headers
+ withCredentials:
+ # mark as default datasource. Max one per org
+ isDefault: true
+ #
\ No newline at end of file
diff --git a/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java b/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java
index 71c34a9de3..1cb55f3f4e 100644
--- a/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java
+++ b/jmh/src/main/java/com/baeldung/falsesharing/Striped64.java
@@ -88,7 +88,7 @@ abstract class Striped64 extends Number {
* JVM intrinsics note: It would be possible to use a release-only
* form of CAS here, if it were provided.
*/
- @sun.misc.Contended static final class Cell {
+ @jdk.internal.vm.annotation.Contended static final class Cell {
volatile long value;
Cell(long x) { value = x; }
final boolean cas(long cmp, long val) {
diff --git a/jsf/pom.xml b/jsf/pom.xml
index 88099ef9c4..81030537fb 100644
--- a/jsf/pom.xml
+++ b/jsf/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
jsf
- 0.1-SNAPSHOT
jsf
war
@@ -15,6 +14,13 @@
+
+
+ javax.annotation
+ javax.annotation-api
+ ${javax.annotation-api.version}
+
+
com.sun.faces
@@ -70,6 +76,10 @@
2.2.14
3.0.0
+
+ 3.3.1
+
+ 1.3.1
\ No newline at end of file
diff --git a/json-modules/gson/pom.xml b/json-modules/gson/pom.xml
index faa8a48297..ecfbaa7be4 100644
--- a/json-modules/gson/pom.xml
+++ b/json-modules/gson/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
gson
- 0.1-SNAPSHOT
gson
diff --git a/json-modules/gson/src/test/java/com/baeldung/gson/serialization/GsonSerializeUnitTest.java b/json-modules/gson/src/test/java/com/baeldung/gson/serialization/GsonSerializeUnitTest.java
index d5051060c4..21d2bedd24 100644
--- a/json-modules/gson/src/test/java/com/baeldung/gson/serialization/GsonSerializeUnitTest.java
+++ b/json-modules/gson/src/test/java/com/baeldung/gson/serialization/GsonSerializeUnitTest.java
@@ -23,8 +23,8 @@ public class GsonSerializeUnitTest {
ActorGson rudyYoungblood = new ActorGson("nm2199632", sdf.parse("21-09-1982"), Arrays.asList("Apocalypto", "Beatdown", "Wind Walkers"));
Movie movie = new Movie("tt0472043", "Mel Gibson", Arrays.asList(rudyYoungblood));
- String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"Sep 21, 1982 12:00:00 AM\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
- Assert.assertEquals(new Gson().toJson(movie), expectedOutput);
+ String expectedOutput = "{\"imdbId\":\"tt0472043\",\"director\":\"Mel Gibson\",\"actors\":[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"Sep 21, 1982, 12:00:00 AM\",\"filmography\":[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
+ Assert.assertEquals(expectedOutput, new Gson().toJson(movie));
}
@Test
diff --git a/json-modules/gson/src/test/java/com/baeldung/gson/serialization/test/GsonSerializationUnitTest.java b/json-modules/gson/src/test/java/com/baeldung/gson/serialization/test/GsonSerializationUnitTest.java
index 3b8912d259..13fea27b24 100644
--- a/json-modules/gson/src/test/java/com/baeldung/gson/serialization/test/GsonSerializationUnitTest.java
+++ b/json-modules/gson/src/test/java/com/baeldung/gson/serialization/test/GsonSerializationUnitTest.java
@@ -1,7 +1,7 @@
package com.baeldung.gson.serialization.test;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+
import java.lang.reflect.Type;
import java.util.Collection;
@@ -88,7 +88,7 @@ public class GsonSerializationUnitTest {
String jsonDate = gson.toJson(sourceDate, sourceDateType);
System.out.println("jsonDate:\n" + jsonDate);
- String expectedResult = "\"Jan 1, 2000 12:00:00 AM\"";
+ String expectedResult = "\"Jan 1, 2000, 12:00:00 AM\"";
assertEquals(expectedResult, jsonDate);
}
diff --git a/json-modules/json-2/pom.xml b/json-modules/json-2/pom.xml
index ee58ab8b25..82fe689ebf 100644
--- a/json-modules/json-2/pom.xml
+++ b/json-modules/json-2/pom.xml
@@ -3,7 +3,6 @@
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
json-2
0.0.1-SNAPSHOT
@@ -119,6 +118,11 @@
RELEASE
test
+
+ javax.annotation
+ javax.annotation-api
+ 1.3.2
+
diff --git a/json-modules/json-path/pom.xml b/json-modules/json-path/pom.xml
index e467ee9557..88b81dfc68 100644
--- a/json-modules/json-path/pom.xml
+++ b/json-modules/json-path/pom.xml
@@ -4,7 +4,6 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
json-path
- 0.0.1-SNAPSHOT
json-path
diff --git a/json-modules/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java b/json-modules/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java
index 85e5d3e826..1a84fae3c4 100644
--- a/json-modules/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java
+++ b/json-modules/json-path/src/test/java/com/baeldung/jsonpath/introduction/ServiceIntegrationTest.java
@@ -1,9 +1,11 @@
package com.baeldung.jsonpath.introduction;
import com.jayway.jsonpath.Configuration;
+import com.jayway.jsonpath.Criteria;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
+import com.jayway.jsonpath.Filter;
import org.junit.Test;
import java.io.InputStream;
@@ -98,4 +100,14 @@ public class ServiceIntegrationTest {
assertEquals("Spectre", title);
}
+
+ @Test
+ public void givenJsonPathWithFilterPredicate_whenReadingRootNode_thenCorrect() {
+ Filter expensiveFilter = Filter.filter(Criteria.where("director")
+ .contains("Sam Mendes"));
+ List
+ edge-SNAPSHOT
1.0.0.Final
1.18.20.0
23.0.0
+
+
+ projectlombok.org
+ https://projectlombok.org/edge-releases
+
+
\ No newline at end of file
diff --git a/lombok-modules/pom.xml b/lombok-modules/pom.xml
index 7ca303af9d..f2bfdb51c0 100644
--- a/lombok-modules/pom.xml
+++ b/lombok-modules/pom.xml
@@ -18,10 +18,21 @@
lombok
lombok-2
- lombok-custom
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ ${maven.compiler.target}
+
+
+
@@ -32,4 +43,9 @@
+
+ 11
+ 11
+
+
\ No newline at end of file
diff --git a/mapstruct/README.md b/mapstruct/README.md
index 384bcbaa14..46a9f8b213 100644
--- a/mapstruct/README.md
+++ b/mapstruct/README.md
@@ -9,3 +9,4 @@ This module contains articles about MapStruct.
- [Using Multiple Source Objects with MapStruct](https://www.baeldung.com/mapstruct-multiple-source-objects)
- [Ignoring Unmapped Properties with MapStruct](https://www.baeldung.com/mapstruct-ignore-unmapped-properties)
- [Mapping Collections with MapStruct](https://www.baeldung.com/java-mapstruct-mapping-collections)
+- [Use Mapper in Another Mapper with Mapstruct and Java](https://www.baeldung.com/java-mapstruct-nested-mapping)
diff --git a/mapstruct/src/main/java/com/baeldung/dto/ArticleDTO.java b/mapstruct/src/main/java/com/baeldung/dto/ArticleDTO.java
new file mode 100644
index 0000000000..708167de94
--- /dev/null
+++ b/mapstruct/src/main/java/com/baeldung/dto/ArticleDTO.java
@@ -0,0 +1,12 @@
+package com.baeldung.dto;
+
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+public class ArticleDTO {
+ private int id;
+ private String name;
+ private PersonDTO author;
+}
diff --git a/mapstruct/src/main/java/com/baeldung/entity/Article.java b/mapstruct/src/main/java/com/baeldung/entity/Article.java
new file mode 100644
index 0000000000..4aff8f4166
--- /dev/null
+++ b/mapstruct/src/main/java/com/baeldung/entity/Article.java
@@ -0,0 +1,12 @@
+package com.baeldung.entity;
+
+import lombok.Getter;
+import lombok.Setter;
+
+@Getter
+@Setter
+public class Article {
+ private int id;
+ private String name;
+ private Person author;
+}
diff --git a/mapstruct/src/main/java/com/baeldung/mapper/ArticleMapper.java b/mapstruct/src/main/java/com/baeldung/mapper/ArticleMapper.java
new file mode 100644
index 0000000000..b5b47f6b3b
--- /dev/null
+++ b/mapstruct/src/main/java/com/baeldung/mapper/ArticleMapper.java
@@ -0,0 +1,20 @@
+package com.baeldung.mapper;
+
+import com.baeldung.dto.ArticleDTO;
+import com.baeldung.dto.PersonDTO;
+import com.baeldung.entity.Article;
+import com.baeldung.entity.Person;
+import org.mapstruct.Mapper;
+import org.mapstruct.factory.Mappers;
+
+@Mapper
+public interface ArticleMapper {
+
+ ArticleMapper INSTANCE = Mappers.getMapper(ArticleMapper.class);
+
+ ArticleDTO articleToArticleDto(Article article);
+
+ default PersonDTO personToPersonDto(Person person) {
+ return Mappers.getMapper(PersonMapper.class).personToPersonDTO(person);
+ }
+}
diff --git a/mapstruct/src/main/java/com/baeldung/mapper/ArticleUsingPersonMapper.java b/mapstruct/src/main/java/com/baeldung/mapper/ArticleUsingPersonMapper.java
new file mode 100644
index 0000000000..c1ea0797ed
--- /dev/null
+++ b/mapstruct/src/main/java/com/baeldung/mapper/ArticleUsingPersonMapper.java
@@ -0,0 +1,16 @@
+package com.baeldung.mapper;
+
+import com.baeldung.dto.ArticleDTO;
+import com.baeldung.dto.PersonDTO;
+import com.baeldung.entity.Article;
+import com.baeldung.entity.Person;
+import org.mapstruct.Mapper;
+import org.mapstruct.factory.Mappers;
+
+@Mapper(uses = PersonMapper.class)
+public interface ArticleUsingPersonMapper {
+
+ ArticleUsingPersonMapper INSTANCE = Mappers.getMapper(ArticleUsingPersonMapper.class);
+
+ ArticleDTO articleToArticleDto(Article article);
+}
diff --git a/mapstruct/src/test/java/com/baeldung/mapper/ArticleMapperUnitTest.java b/mapstruct/src/test/java/com/baeldung/mapper/ArticleMapperUnitTest.java
new file mode 100644
index 0000000000..2470915a01
--- /dev/null
+++ b/mapstruct/src/test/java/com/baeldung/mapper/ArticleMapperUnitTest.java
@@ -0,0 +1,49 @@
+package com.baeldung.mapper;
+
+import com.baeldung.dto.ArticleDTO;
+import com.baeldung.dto.CarDTO;
+import com.baeldung.entity.Article;
+import com.baeldung.entity.Car;
+import com.baeldung.entity.Person;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class ArticleMapperUnitTest {
+
+ @Test
+ public void givenArticle_whenMaps_thenProducesCorrectDto() {
+
+ Article entity = new Article();
+ entity.setId(1);
+ entity.setName("Mapstruct Mapping");
+ Person author = new Person();
+ author.setId("1");
+ author.setName("John");
+ entity.setAuthor(author);
+
+ ArticleDTO articleDTO = ArticleMapper.INSTANCE.articleToArticleDto(entity);
+
+ assertEquals(articleDTO.getId(), entity.getId());
+ assertEquals(articleDTO.getName(), entity.getName());
+ assertEquals(articleDTO.getAuthor().getName(), entity.getAuthor().getName());
+ }
+
+ @Test
+ public void givenArticle_whenMapsWithUses_thenProducesCorrectDto() {
+
+ Article entity = new Article();
+ entity.setId(1);
+ entity.setName("Mapstruct Mapping");
+ Person author = new Person();
+ author.setId("1");
+ author.setName("John");
+ entity.setAuthor(author);
+
+ ArticleDTO articleDTO = ArticleUsingPersonMapper.INSTANCE.articleToArticleDto(entity);
+
+ assertEquals(articleDTO.getId(), entity.getId());
+ assertEquals(articleDTO.getName(), entity.getName());
+ assertEquals(articleDTO.getAuthor().getName(), entity.getAuthor().getName());
+ }
+}
diff --git a/maven-modules/animal-sniffer-mvn-plugin/pom.xml b/maven-modules/animal-sniffer-mvn-plugin/pom.xml
index 1756adc27d..0b508651af 100644
--- a/maven-modules/animal-sniffer-mvn-plugin/pom.xml
+++ b/maven-modules/animal-sniffer-mvn-plugin/pom.xml
@@ -42,7 +42,7 @@
- 1.16
+ 1.22
1.0
diff --git a/maven-modules/dependency-exclusion/README.md b/maven-modules/dependency-exclusion/README.md
new file mode 100644
index 0000000000..e9eee1be4d
--- /dev/null
+++ b/maven-modules/dependency-exclusion/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Exclude a Dependency in a Maven Plugin](https://www.baeldung.com/mvn-plugin-dependency-exclusion)
diff --git a/dependeny-exclusion/core-java-exclusions/pom.xml b/maven-modules/dependency-exclusion/core-java-exclusions/pom.xml
similarity index 80%
rename from dependeny-exclusion/core-java-exclusions/pom.xml
rename to maven-modules/dependency-exclusion/core-java-exclusions/pom.xml
index cf1f6d1e1b..9fd09f83e2 100644
--- a/dependeny-exclusion/core-java-exclusions/pom.xml
+++ b/maven-modules/dependency-exclusion/core-java-exclusions/pom.xml
@@ -1,10 +1,9 @@
+ xmlns="http://maven.apache.org/POM/4.0.0"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
core-java-exclusions
- 0.0.0-SNAPSHOT
core-java-exclusions
jar
@@ -14,6 +13,15 @@
0.0.1-SNAPSHOT
+
+
+ junit
+ junit
+ test
+
+
+
+
@@ -30,24 +38,17 @@
-
+
+
+ Deactivate JUnit 4.7 engine by overriding it with an empty dummy
org.apache.maven.surefire
surefire-junit47
dummy
-
+ -->
-
-
- junit
- junit
- test
-
-
-
diff --git a/dependeny-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java b/maven-modules/dependency-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java
similarity index 100%
rename from dependeny-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java
rename to maven-modules/dependency-exclusion/core-java-exclusions/src/test/java/com/sample/project/tests/ExcludeDirectDependencyUnitTest.java
diff --git a/maven-modules/dependency-exclusion/dummy-surefire-junit47/pom.xml b/maven-modules/dependency-exclusion/dummy-surefire-junit47/pom.xml
new file mode 100644
index 0000000000..93c5f7591f
--- /dev/null
+++ b/maven-modules/dependency-exclusion/dummy-surefire-junit47/pom.xml
@@ -0,0 +1,15 @@
+
+
+ 4.0.0
+ org.apache.maven.surefire
+ surefire-junit47
+ dummy
+
+
+ com.baeldung.dependency-exclusion
+ dependency-exclusion
+ 0.0.1-SNAPSHOT
+
+
diff --git a/dependeny-exclusion/pom.xml b/maven-modules/dependency-exclusion/pom.xml
similarity index 96%
rename from dependeny-exclusion/pom.xml
rename to maven-modules/dependency-exclusion/pom.xml
index ac83cc161a..13de16a57c 100644
--- a/dependeny-exclusion/pom.xml
+++ b/maven-modules/dependency-exclusion/pom.xml
@@ -10,9 +10,8 @@
com.baeldung
- parent-java
+ maven-modules
0.0.1-SNAPSHOT
- ../parent-java
diff --git a/maven-modules/maven-integration-test/pom.xml b/maven-modules/maven-integration-test/pom.xml
index 56c243e3c5..4483bb2d55 100644
--- a/maven-modules/maven-integration-test/pom.xml
+++ b/maven-modules/maven-integration-test/pom.xml
@@ -267,6 +267,7 @@
+ 3.3.2
3.0.2
3.8.0
2.22.0
diff --git a/maven-modules/maven-plugins/jaxws/pom.xml b/maven-modules/maven-plugins/jaxws/pom.xml
index 5783907140..a7c4740acb 100644
--- a/maven-modules/maven-plugins/jaxws/pom.xml
+++ b/maven-modules/maven-plugins/jaxws/pom.xml
@@ -11,6 +11,36 @@
0.0.1-SNAPSHOT
+
+
+ javax.xml.bind
+ jaxb-api
+ 2.3.0
+
+
+ org.glassfish.jaxb
+ jaxb-core
+ 2.3.0.1
+
+
+
+ com.sun.xml.bind
+ jaxb-impl
+ 2.3.0
+
+
+ org.glassfish.jaxb
+ jaxb-runtime
+ 2.3.2
+
+
+ com.sun.xml.ws
+ jaxws-ri
+ 2.3.0
+ pom
+
+
+
diff --git a/maven-modules/maven-polyglot/maven-polyglot-json-extension/pom.xml b/maven-modules/maven-polyglot/maven-polyglot-json-extension/pom.xml
index ade8974e0e..280b7a7c7b 100644
--- a/maven-modules/maven-polyglot/maven-polyglot-json-extension/pom.xml
+++ b/maven-modules/maven-polyglot/maven-polyglot-json-extension/pom.xml
@@ -48,7 +48,7 @@
3.5.4
- 1.7.1
+ 2.1.1
\ No newline at end of file
diff --git a/maven-modules/maven-reactor/README.md b/maven-modules/maven-reactor/README.md
new file mode 100644
index 0000000000..745ced5e82
--- /dev/null
+++ b/maven-modules/maven-reactor/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Maven Reactor](https://www.baeldung.com/java-maven-reactor)
diff --git a/maven-modules/maven-reactor/patient-data/pom.xml b/maven-modules/maven-reactor/patient-data/pom.xml
new file mode 100644
index 0000000000..9526549c48
--- /dev/null
+++ b/maven-modules/maven-reactor/patient-data/pom.xml
@@ -0,0 +1,20 @@
+
+
+ 4.0.0
+ patient-data
+ patient-data
+
+ com.baeldung
+ maven-reactor
+ 1.0-SNAPSHOT
+
+
+
+ com.baeldung
+ patient-domain
+ 1.0-SNAPSHOT
+
+
+
\ No newline at end of file
diff --git a/maven-modules/maven-reactor/patient-data/src/Main.java b/maven-modules/maven-reactor/patient-data/src/Main.java
new file mode 100644
index 0000000000..69420efcac
--- /dev/null
+++ b/maven-modules/maven-reactor/patient-data/src/Main.java
@@ -0,0 +1,6 @@
+public class Main {
+
+ public static void main(String[] args) {
+ System.out.println("Hello world!");
+ }
+}
\ No newline at end of file
diff --git a/maven-modules/maven-reactor/patient-domain/pom.xml b/maven-modules/maven-reactor/patient-domain/pom.xml
new file mode 100644
index 0000000000..5cb5abe81e
--- /dev/null
+++ b/maven-modules/maven-reactor/patient-domain/pom.xml
@@ -0,0 +1,13 @@
+
+
+ 4.0.0
+ patient-domain
+ patient-domain
+
+ com.baeldung
+ maven-reactor
+ 1.0-SNAPSHOT
+
+
\ No newline at end of file
diff --git a/maven-modules/maven-reactor/patient-domain/src/Main.java b/maven-modules/maven-reactor/patient-domain/src/Main.java
new file mode 100644
index 0000000000..69420efcac
--- /dev/null
+++ b/maven-modules/maven-reactor/patient-domain/src/Main.java
@@ -0,0 +1,6 @@
+public class Main {
+
+ public static void main(String[] args) {
+ System.out.println("Hello world!");
+ }
+}
\ No newline at end of file
diff --git a/maven-modules/maven-reactor/patient-web/pom.xml b/maven-modules/maven-reactor/patient-web/pom.xml
new file mode 100644
index 0000000000..68d797ec63
--- /dev/null
+++ b/maven-modules/maven-reactor/patient-web/pom.xml
@@ -0,0 +1,27 @@
+
+
+ 4.0.0
+ patient-web
+ 1.0-SNAPSHOT
+ patient-web
+
+ com.baeldung
+ maven-reactor
+ 1.0-SNAPSHOT
+
+
+
+ com.baeldung
+ patient-data
+ 1.0-SNAPSHOT
+
+
+ com.baeldung
+ patient-domain
+ 1.0-SNAPSHOT
+
+
+
+
\ No newline at end of file
diff --git a/maven-modules/maven-reactor/patient-web/src/Main.java b/maven-modules/maven-reactor/patient-web/src/Main.java
new file mode 100644
index 0000000000..69420efcac
--- /dev/null
+++ b/maven-modules/maven-reactor/patient-web/src/Main.java
@@ -0,0 +1,6 @@
+public class Main {
+
+ public static void main(String[] args) {
+ System.out.println("Hello world!");
+ }
+}
\ No newline at end of file
diff --git a/maven-modules/maven-reactor/pom.xml b/maven-modules/maven-reactor/pom.xml
new file mode 100644
index 0000000000..a41fbd7374
--- /dev/null
+++ b/maven-modules/maven-reactor/pom.xml
@@ -0,0 +1,22 @@
+
+
+ 4.0.0
+ maven-reactor
+ 1.0-SNAPSHOT
+ maven-reactor
+ pom
+ Sample multi-module project to explain maven reactor
+
+ com.baeldung
+ maven-modules
+ 0.0.1-SNAPSHOT
+
+
+ patient-web
+ patient-data
+ patient-domain
+
+
+
\ No newline at end of file
diff --git a/maven-modules/pom.xml b/maven-modules/pom.xml
index 412e26f041..f7bba3a8ff 100644
--- a/maven-modules/pom.xml
+++ b/maven-modules/pom.xml
@@ -16,32 +16,35 @@
animal-sniffer-mvn-plugin
+ compiler-plugin-java-9
+ dependency-exclusion
+ host-maven-repo-example
maven-archetype
-
+ maven-builder-plugin
+ maven-classifier
maven-copy-files
maven-custom-plugin
maven-exec-plugin
-
+ maven-generate-war
maven-integration-test
maven-multi-source
+ maven-parent-pom-resolution
maven-plugins
maven-polyglot
+ maven-printing-plugins
maven-properties
+ maven-reactor
+ maven-repositories
+ maven-simple
+ maven-surefire-plugin
maven-unused-dependencies
maven-war-plugin
+ spring-bom
optional-dependencies
version-collision
version-overriding-plugins
versions-maven-plugin
- maven-printing-plugins
- maven-builder-plugin
- host-maven-repo-example
- maven-surefire-plugin
- maven-parent-pom-resolution
- maven-simple
- maven-classifier
- maven-repositories
@@ -61,4 +64,18 @@
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ --add-opens java.base/java.lang=ALL-UNNAMED
+
+
+
+
+
+
\ No newline at end of file
diff --git a/spring-bom/README.md b/maven-modules/spring-bom/README.md
similarity index 100%
rename from spring-bom/README.md
rename to maven-modules/spring-bom/README.md
diff --git a/spring-bom/pom.xml b/maven-modules/spring-bom/pom.xml
similarity index 93%
rename from spring-bom/pom.xml
rename to maven-modules/spring-bom/pom.xml
index 7ba21ee285..93d0bdc458 100644
--- a/spring-bom/pom.xml
+++ b/maven-modules/spring-bom/pom.xml
@@ -10,8 +10,8 @@
com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
+ maven-modules
+ 0.0.1-SNAPSHOT
diff --git a/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldApp.java b/maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldApp.java
similarity index 100%
rename from spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldApp.java
rename to maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldApp.java
diff --git a/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldBean.java b/maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldBean.java
similarity index 100%
rename from spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldBean.java
rename to maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldBean.java
diff --git a/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldConfig.java b/maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldConfig.java
similarity index 100%
rename from spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldConfig.java
rename to maven-modules/spring-bom/src/main/java/com/baeldung/spring/bom/HelloWorldConfig.java
diff --git a/spring-bom/src/main/resources/logback.xml b/maven-modules/spring-bom/src/main/resources/logback.xml
similarity index 100%
rename from spring-bom/src/main/resources/logback.xml
rename to maven-modules/spring-bom/src/main/resources/logback.xml
diff --git a/spring-bom/src/test/java/com/baeldung/SpringContextTest.java b/maven-modules/spring-bom/src/test/java/com/baeldung/SpringContextTest.java
similarity index 100%
rename from spring-bom/src/test/java/com/baeldung/SpringContextTest.java
rename to maven-modules/spring-bom/src/test/java/com/baeldung/SpringContextTest.java
diff --git a/maven-modules/version-collision/dependencyconvergence.xml b/maven-modules/version-collision/dependencyconvergence.xml
new file mode 100644
index 0000000000..8f57cbf1d5
--- /dev/null
+++ b/maven-modules/version-collision/dependencyconvergence.xml
@@ -0,0 +1,22 @@
+
+
+
+ org.apache.maven.plugins
+ maven-enforcer-plugin
+ 3.3.0
+
+
+ enforce
+
+
+
+
+
+
+ enforce
+
+
+
+
+
+
\ No newline at end of file
diff --git a/maven-modules/version-collision/dependencyconvergence_exclude_scenario.xml b/maven-modules/version-collision/dependencyconvergence_exclude_scenario.xml
new file mode 100644
index 0000000000..32b0462a11
--- /dev/null
+++ b/maven-modules/version-collision/dependencyconvergence_exclude_scenario.xml
@@ -0,0 +1,26 @@
+
+
+
+ org.apache.maven.plugins
+ maven-enforcer-plugin
+ 3.3.0
+
+
+ enforce
+
+
+
+
+ com.google.guava:guava
+
+
+
+
+
+ enforce
+
+
+
+
+
+
\ No newline at end of file
diff --git a/maven-modules/version-collision/dependencyconvergence_include_scenario.xml b/maven-modules/version-collision/dependencyconvergence_include_scenario.xml
new file mode 100644
index 0000000000..9e4680fc91
--- /dev/null
+++ b/maven-modules/version-collision/dependencyconvergence_include_scenario.xml
@@ -0,0 +1,26 @@
+
+
+
+ org.apache.maven.plugins
+ maven-enforcer-plugin
+ 3.3.0
+
+
+ enforce
+
+
+
+
+ com.google.guava:guava
+
+
+
+
+
+ enforce
+
+
+
+
+
+
\ No newline at end of file
diff --git a/messaging-modules/apache-camel/README.md b/messaging-modules/apache-camel/README.md
new file mode 100644
index 0000000000..6196893adc
--- /dev/null
+++ b/messaging-modules/apache-camel/README.md
@@ -0,0 +1,9 @@
+## Apache Camel
+
+This module contains articles about Apache Camel
+
+### Relevant Articles
+
+- [Introduction To Apache Camel](http://www.baeldung.com/apache-camel-intro)
+- [Unmarshalling a JSON Array Using camel-jackson](https://www.baeldung.com/java-camel-jackson-json-array)
+
diff --git a/messaging-modules/apache-camel/pom.xml b/messaging-modules/apache-camel/pom.xml
new file mode 100644
index 0000000000..bb20f178aa
--- /dev/null
+++ b/messaging-modules/apache-camel/pom.xml
@@ -0,0 +1,46 @@
+
+
+ 4.0.0
+ org.baeldung.apache.camel
+ apache-camel
+ apache-camel
+ jar
+ http://maven.apache.org
+
+
+ com.baeldung
+ messaging-modules
+ 0.0.1-SNAPSHOT
+
+
+
+
+ org.apache.camel
+ camel-core
+ ${env.camel.version}
+
+
+ org.apache.camel
+ camel-spring-javaconfig
+ ${env.camel.version}
+
+
+ org.apache.camel
+ camel-jackson
+ ${env.camel.version}
+
+
+ org.apache.camel
+ camel-test
+ ${env.camel.version}
+ test
+
+
+
+
+ 3.14.7
+
+
+
\ No newline at end of file
diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileProcessor.java b/messaging-modules/apache-camel/src/main/java/com/baeldung/camel/apache/file/FileProcessor.java
similarity index 100%
rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileProcessor.java
rename to messaging-modules/apache-camel/src/main/java/com/baeldung/camel/apache/file/FileProcessor.java
diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileRouter.java b/messaging-modules/apache-camel/src/main/java/com/baeldung/camel/apache/file/FileRouter.java
similarity index 100%
rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/file/FileRouter.java
rename to messaging-modules/apache-camel/src/main/java/com/baeldung/camel/apache/file/FileRouter.java
diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/Fruit.java b/messaging-modules/apache-camel/src/main/java/com/baeldung/camel/apache/jackson/Fruit.java
similarity index 100%
rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/Fruit.java
rename to messaging-modules/apache-camel/src/main/java/com/baeldung/camel/apache/jackson/Fruit.java
diff --git a/messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/FruitList.java b/messaging-modules/apache-camel/src/main/java/com/baeldung/camel/apache/jackson/FruitList.java
similarity index 100%
rename from messaging-modules/spring-apache-camel/src/main/java/com/baeldung/camel/apache/jackson/FruitList.java
rename to messaging-modules/apache-camel/src/main/java/com/baeldung/camel/apache/jackson/FruitList.java
diff --git a/messaging-modules/spring-apache-camel/src/main/resources/camel-context-test.xml b/messaging-modules/apache-camel/src/main/resources/camel-context-test.xml
similarity index 100%
rename from messaging-modules/spring-apache-camel/src/main/resources/camel-context-test.xml
rename to messaging-modules/apache-camel/src/main/resources/camel-context-test.xml
diff --git a/spring-caching/src/main/resources/logback.xml b/messaging-modules/apache-camel/src/main/resources/logback.xml
similarity index 100%
rename from spring-caching/src/main/resources/logback.xml
rename to messaging-modules/apache-camel/src/main/resources/logback.xml
diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java b/messaging-modules/apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java
similarity index 100%
rename from messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java
rename to messaging-modules/apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitArrayJacksonUnmarshalUnitTest.java
diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java b/messaging-modules/apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java
similarity index 100%
rename from messaging-modules/spring-apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java
rename to messaging-modules/apache-camel/src/test/java/com/apache/baeldung/camel/jackson/FruitListJacksonUnmarshalUnitTest.java
diff --git a/messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/FileProcessorIntegrationTest.java b/messaging-modules/apache-camel/src/test/java/com/apache/camel/file/processor/FileProcessorIntegrationTest.java
similarity index 100%
rename from messaging-modules/spring-apache-camel/src/test/java/com/apache/camel/file/processor/FileProcessorIntegrationTest.java
rename to messaging-modules/apache-camel/src/test/java/com/apache/camel/file/processor/FileProcessorIntegrationTest.java
diff --git a/messaging-modules/spring-apache-camel/src/test/resources/json/fruit-array.json b/messaging-modules/apache-camel/src/test/resources/json/fruit-array.json
similarity index 100%
rename from messaging-modules/spring-apache-camel/src/test/resources/json/fruit-array.json
rename to messaging-modules/apache-camel/src/test/resources/json/fruit-array.json
diff --git a/messaging-modules/spring-apache-camel/src/test/resources/json/fruit-list.json b/messaging-modules/apache-camel/src/test/resources/json/fruit-list.json
similarity index 100%
rename from messaging-modules/spring-apache-camel/src/test/resources/json/fruit-list.json
rename to messaging-modules/apache-camel/src/test/resources/json/fruit-list.json
diff --git a/apache-rocketmq/README.md b/messaging-modules/apache-rocketmq/README.md
similarity index 100%
rename from apache-rocketmq/README.md
rename to messaging-modules/apache-rocketmq/README.md
diff --git a/apache-rocketmq/pom.xml b/messaging-modules/apache-rocketmq/pom.xml
similarity index 90%
rename from apache-rocketmq/pom.xml
rename to messaging-modules/apache-rocketmq/pom.xml
index 48399b6d51..a362644de3 100644
--- a/apache-rocketmq/pom.xml
+++ b/messaging-modules/apache-rocketmq/pom.xml
@@ -9,8 +9,8 @@
com.baeldung
- parent-modules
- 1.0.0-SNAPSHOT
+ messaging-modules
+ 0.0.1-SNAPSHOT
diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java b/messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java
similarity index 100%
rename from apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java
rename to messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/consumer/CartEventConsumer.java
diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java b/messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java
similarity index 100%
rename from apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java
rename to messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/event/CartItemEvent.java
diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java b/messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java
similarity index 100%
rename from apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java
rename to messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/producer/CartEventProducer.java
diff --git a/apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java b/messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java
similarity index 100%
rename from apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java
rename to messaging-modules/apache-rocketmq/src/main/java/com/baeldung/rocketmq/transaction/TransactionListenerImpl.java
diff --git a/apache-rocketmq/src/main/resources/application.properties b/messaging-modules/apache-rocketmq/src/main/resources/application.properties
similarity index 100%
rename from apache-rocketmq/src/main/resources/application.properties
rename to messaging-modules/apache-rocketmq/src/main/resources/application.properties
diff --git a/messaging-modules/pom.xml b/messaging-modules/pom.xml
index 8bda46f5cd..71ff25d71b 100644
--- a/messaging-modules/pom.xml
+++ b/messaging-modules/pom.xml
@@ -15,9 +15,12 @@
+ apache-camel
+ apache-rocketmq
jgroups
rabbitmq
spring-amqp
+ spring-apache-camel
spring-jms
diff --git a/messaging-modules/rabbitmq/README.md b/messaging-modules/rabbitmq/README.md
index 93bb795d7b..8cfcca3378 100644
--- a/messaging-modules/rabbitmq/README.md
+++ b/messaging-modules/rabbitmq/README.md
@@ -9,3 +9,4 @@ This module contains articles about RabbitMQ.
- [Channels and Connections in RabbitMQ](https://www.baeldung.com/java-rabbitmq-channels-connections)
- [Create Dynamic Queues in RabbitMQ](https://www.baeldung.com/rabbitmq-dynamic-queues)
+
diff --git a/messaging-modules/spring-apache-camel/README.md b/messaging-modules/spring-apache-camel/README.md
index 535c61cbef..66079d4e83 100644
--- a/messaging-modules/spring-apache-camel/README.md
+++ b/messaging-modules/spring-apache-camel/README.md
@@ -4,10 +4,8 @@ This module contains articles about Spring with Apache Camel
### Relevant Articles
-- [Introduction To Apache Camel](http://www.baeldung.com/apache-camel-intro)
- [Integration Patterns With Apache Camel](http://www.baeldung.com/camel-integration-patterns)
- [Using Apache Camel with Spring](http://www.baeldung.com/spring-apache-camel-tutorial)
-- [Unmarshalling a JSON Array Using camel-jackson](https://www.baeldung.com/java-camel-jackson-json-array)
- [Apache Camel with Spring Boot](https://www.baeldung.com/apache-camel-spring-boot)
- [Apache Camel Routes Testing in Spring Boot](https://www.baeldung.com/spring-boot-apache-camel-routes-testing)
- [Apache Camel Conditional Routing](https://www.baeldung.com/spring-apache-camel-conditional-routing)
diff --git a/messaging-modules/spring-apache-camel/pom.xml b/messaging-modules/spring-apache-camel/pom.xml
index ec7557666c..65533d7649 100644
--- a/messaging-modules/spring-apache-camel/pom.xml
+++ b/messaging-modules/spring-apache-camel/pom.xml
@@ -47,17 +47,6 @@
camel-spring-javaconfig
${env.camel.version}
-
- org.apache.camel
- camel-jackson
- ${env.camel.version}
-
-
- org.apache.camel
- camel-test
- ${env.camel.version}
- test
-
org.apache.camel.springboot
camel-servlet-starter
diff --git a/messaging-modules/spring-jms/pom.xml b/messaging-modules/spring-jms/pom.xml
index b94a31c0c5..ef1e0cb3a8 100644
--- a/messaging-modules/spring-jms/pom.xml
+++ b/messaging-modules/spring-jms/pom.xml
@@ -44,19 +44,19 @@
org.mockito
mockito-core
- 4.6.1
+ ${mockito-core.version}
test
org.apache.activemq.tooling
activemq-junit
- 5.16.5
+ ${activemq-junit.version}
test
org.testcontainers
testcontainers
- 1.17.3
+ ${testcontainers.version}
test
@@ -67,7 +67,6 @@
org.apache.maven.plugins
maven-war-plugin
- ${maven-war-plugin.version}
src/main/webapp
spring-jms
@@ -83,6 +82,10 @@
4.3.4.RELEASE
5.14.1
1.5.10.RELEASE
+ 3.3.2
+ 4.6.1
+ 5.16.5
+ 1.17.3
\ No newline at end of file
diff --git a/microservices-modules/micronaut/pom.xml b/microservices-modules/micronaut/pom.xml
index 8647d1a3a7..2cc91bc510 100644
--- a/microservices-modules/micronaut/pom.xml
+++ b/microservices-modules/micronaut/pom.xml
@@ -138,7 +138,7 @@
com.baeldung.micronaut.vs.springboot.CompareApplication
1.0.0.RC2
- 1.8
+ 17
1.3.2
3.1.6.RELEASE
3.7.0
diff --git a/microservices-modules/open-liberty/pom.xml b/microservices-modules/open-liberty/pom.xml
index c4b0fd0b82..1c2e948765 100644
--- a/microservices-modules/open-liberty/pom.xml
+++ b/microservices-modules/open-liberty/pom.xml
@@ -95,14 +95,11 @@
org.apache.maven.plugins
maven-war-plugin
- ${version.maven-war-plugin}
- 1.8
- 1.8
UTF-8
UTF-8
false
@@ -111,7 +108,6 @@
3.2
10.14.2.0
3.3-M3
- 3.2.3
1.0.5
3.2.6
1.0.4
diff --git a/microservices-modules/pom.xml b/microservices-modules/pom.xml
index a9cd8d2cd9..2111390481 100644
--- a/microservices-modules/pom.xml
+++ b/microservices-modules/pom.xml
@@ -22,4 +22,8 @@
rest-express
+
+ 3.3.2
+
+
\ No newline at end of file
diff --git a/microservices-modules/rest-express/pom.xml b/microservices-modules/rest-express/pom.xml
index f222998340..eda27ec164 100644
--- a/microservices-modules/rest-express/pom.xml
+++ b/microservices-modules/rest-express/pom.xml
@@ -23,15 +23,6 @@
rest-express
jar
-
- 0.3.3
- 3.1.2
- 2.6
- 0.11.3
- 1.0
- 0.4.8
- 4.11
-
@@ -94,17 +85,11 @@
org.apache.maven.plugins
maven-compiler-plugin
- 3.0
-
-
- 1.8
- UTF-8
-
org.codehaus.mojo
exec-maven-plugin
- 1.2.1
+ ${exec-maven-plugin.version}
com.baeldung.restexpress.Main
@@ -112,7 +97,7 @@
org.apache.maven.plugins
maven-shade-plugin
- 2.4.1
+ ${maven-shade-plugin.version}
false
@@ -146,8 +131,22 @@
org.codehaus.mojo
versions-maven-plugin
- 2.0
+ ${versions-maven-plugin.version}
+
+
+ 0.3.3
+ 3.1.2
+ 2.6
+ 0.11.3
+ 1.0
+ 0.4.8
+ 4.11
+ 1.2.1
+ 2.4.1
+ 2.0
+
+
diff --git a/orika/pom.xml b/orika/pom.xml
index c18bb58a51..5ff898e6bd 100644
--- a/orika/pom.xml
+++ b/orika/pom.xml
@@ -21,6 +21,21 @@
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ --add-opens java.base/java.lang=ALL-UNNAMED
+ --add-opens java.base/java.util=ALL-UNNAMED
+
+
+
+
+
+
1.5.0
diff --git a/osgi/pom.xml b/osgi/pom.xml
index 3fa2dcdf02..ecc8758ef9 100644
--- a/osgi/pom.xml
+++ b/osgi/pom.xml
@@ -67,6 +67,17 @@
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ ${maven-compiler-plugin.version}
+
+
+ ${maven.compiler.target}
+
+
+
@@ -84,6 +95,8 @@
1.1
6.0.0
3.3.0
+ 11
+ 11
\ No newline at end of file
diff --git a/parent-boot-2/pom.xml b/parent-boot-2/pom.xml
index a1f16c4a64..3f6ad8ef8a 100644
--- a/parent-boot-2/pom.xml
+++ b/parent-boot-2/pom.xml
@@ -94,7 +94,7 @@
3.3.0
1.0.22.RELEASE
- 2.7.8
+ 2.7.11
1.9.1
8.0.31
diff --git a/parent-spring-5/pom.xml b/parent-spring-5/pom.xml
index 80a8c7d77d..fd3cd734c6 100644
--- a/parent-spring-5/pom.xml
+++ b/parent-spring-5/pom.xml
@@ -24,7 +24,7 @@
- 5.3.24
+ 5.3.25
5.7.3
1.5.10.RELEASE
diff --git a/patterns-modules/clean-architecture/README.md b/patterns-modules/clean-architecture/README.md
index aad8608447..4ff1e4c93e 100644
--- a/patterns-modules/clean-architecture/README.md
+++ b/patterns-modules/clean-architecture/README.md
@@ -1,3 +1,4 @@
### Relevant Articles:
- [Clean Architecture with Spring Boot](https://www.baeldung.com/spring-boot-clean-architecture)
+- [Anemic vs. Rich Domain Objects](https://www.baeldung.com/java-anemic-vs-rich-domain-objects)
diff --git a/patterns-modules/clean-architecture/src/main/java/com/baeldung/pattern/richdomainmodel/Player.java b/patterns-modules/clean-architecture/src/main/java/com/baeldung/pattern/richdomainmodel/Player.java
new file mode 100644
index 0000000000..f683b1158d
--- /dev/null
+++ b/patterns-modules/clean-architecture/src/main/java/com/baeldung/pattern/richdomainmodel/Player.java
@@ -0,0 +1,35 @@
+package com.baeldung.pattern.richdomainmodel;
+
+public class Player {
+ private int points ;
+ final String name;
+
+ public Player(String name) {
+ this(name, 0);
+ }
+
+ private Player(String name, int points) {
+ this.name = name;
+ this.points = 0;
+ }
+
+ public void gainPoint() {
+ points++;
+ }
+
+ public boolean hasScoreBiggerThan(Score score) {
+ return this.points > score.points();
+ }
+
+ public int pointsDifference(Player other) {
+ return points - other.points;
+ }
+
+ public String name() {
+ return name;
+ }
+
+ public String score() {
+ return Score.from(points).label();
+ }
+}
\ No newline at end of file
diff --git a/patterns-modules/clean-architecture/src/main/java/com/baeldung/pattern/richdomainmodel/Score.java b/patterns-modules/clean-architecture/src/main/java/com/baeldung/pattern/richdomainmodel/Score.java
new file mode 100644
index 0000000000..da5823763c
--- /dev/null
+++ b/patterns-modules/clean-architecture/src/main/java/com/baeldung/pattern/richdomainmodel/Score.java
@@ -0,0 +1,29 @@
+package com.baeldung.pattern.richdomainmodel;
+
+import java.util.Arrays;
+
+public enum Score {
+ LOVE(0, "Love"), FIFTEEN(1, "Fifteen"), THIRTY(2, "Thirty"), FORTY(3, "Forty");
+
+ private final int points;
+ private final String label;
+
+ Score(int points, String label) {
+ this.points = points;
+ this.label = label;
+ }
+
+ public static Score from(int value) {
+ return Arrays.stream(values())
+ .filter(v -> v.points == value)
+ .findFirst()
+ .orElseThrow(() -> new IllegalArgumentException("no such element: " + value));
+ }
+
+ public int points() {
+ return points;
+ }
+ public String label() {
+ return label;
+ }
+}
\ No newline at end of file
diff --git a/patterns-modules/clean-architecture/src/main/java/com/baeldung/pattern/richdomainmodel/TennisGame.java b/patterns-modules/clean-architecture/src/main/java/com/baeldung/pattern/richdomainmodel/TennisGame.java
new file mode 100644
index 0000000000..30811a2eb9
--- /dev/null
+++ b/patterns-modules/clean-architecture/src/main/java/com/baeldung/pattern/richdomainmodel/TennisGame.java
@@ -0,0 +1,71 @@
+package com.baeldung.pattern.richdomainmodel;
+
+public class TennisGame {
+ private final Player server;
+ private final Player receiver;
+
+ public TennisGame(String server, String receiver) {
+ this.server = new Player(server);
+ this.receiver = new Player(receiver);
+ }
+
+ public void wonPoint(String playerName) {
+ if(server.name().equals(playerName)) {
+ server.gainPoint();
+ } else {
+ receiver.gainPoint();
+ }
+ }
+
+ public String getScore() {
+ if (gameContinues()) {
+ return getGameScore();
+ }
+ return "Win for " + leadingPlayer().name();
+ }
+
+ private String getGameScore() {
+ if (isScoreEqual()) {
+ return getEqualScore();
+ }
+ if (isAdvantage()) {
+ return "Advantage " + leadingPlayer().name();
+ }
+ return getSimpleScore();
+ }
+
+ private boolean isScoreEqual() {
+ return server.pointsDifference(receiver) == 0;
+ }
+
+ private boolean isAdvantage() {
+ return leadingPlayer().hasScoreBiggerThan(Score.FORTY)
+ && Math.abs(server.pointsDifference(receiver)) == 1;
+ }
+
+ private boolean isGameFinished() {
+ return leadingPlayer().hasScoreBiggerThan(Score.FORTY)
+ && Math.abs(server.pointsDifference(receiver)) >= 2;
+ }
+
+ private Player leadingPlayer() {
+ if (server.pointsDifference(receiver) > 0) {
+ return server;
+ }
+ return receiver;
+ }
+
+ private boolean gameContinues() {
+ return !isGameFinished();
+ }
+ private String getSimpleScore() {
+ return String.format("%s-%s", server.score(), receiver.score());
+ }
+
+ private String getEqualScore() {
+ if (server.hasScoreBiggerThan(Score.THIRTY)) {
+ return "Deuce";
+ }
+ return String.format("%s-All", server.score());
+ }
+}
diff --git a/patterns-modules/clean-architecture/src/test/java/com/baeldung/pattern/cleanarchitecture/usercreation/UserUnitTest.java b/patterns-modules/clean-architecture/src/test/java/com/baeldung/pattern/cleanarchitecture/usercreation/UserUnitTest.java
index 505ea47e3f..e2a9cd9d14 100644
--- a/patterns-modules/clean-architecture/src/test/java/com/baeldung/pattern/cleanarchitecture/usercreation/UserUnitTest.java
+++ b/patterns-modules/clean-architecture/src/test/java/com/baeldung/pattern/cleanarchitecture/usercreation/UserUnitTest.java
@@ -1,15 +1,36 @@
package com.baeldung.pattern.cleanarchitecture.usercreation;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.*;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.any;
import org.junit.jupiter.api.Test;
class UserUnitTest {
+ UserRegisterDsGateway userDsGateway = mock(UserRegisterDsGateway.class);
+ UserPresenter userPresenter = mock(UserPresenter.class);
+ UserFactory userFactory = mock(UserFactory.class);
+ UserInputBoundary interactor = new UserRegisterInteractor(userDsGateway, userPresenter, userFactory);
+
@Test
void given123Password_whenPasswordIsNotValid_thenIsFalse() {
User user = new CommonUser("Baeldung", "123");
assertThat(user.passwordIsValid()).isFalse();
}
+
+ @Test
+ void givenBaeldungUserAnd123456Password_whenCreate_thenSaveItAndPrepareSuccessView() {
+
+ User user = new CommonUser("baeldung", "123456");
+ UserRequestModel userRequestModel = new UserRequestModel(user.getName(), user.getPassword());
+ when(userFactory.create(anyString(), anyString())).thenReturn(new CommonUser(user.getName(), user.getPassword()));
+
+ interactor.create(userRequestModel);
+
+ verify(userDsGateway, times(1)).save(any(UserDsRequestModel.class));
+ verify(userPresenter, times(1)).prepareSuccessView(any(UserResponseModel.class));
+ }
}
diff --git a/patterns-modules/clean-architecture/src/test/java/com/baeldung/pattern/richdomainmodel/RichDomainModelUnitTest.java b/patterns-modules/clean-architecture/src/test/java/com/baeldung/pattern/richdomainmodel/RichDomainModelUnitTest.java
new file mode 100644
index 0000000000..b620c7e0e2
--- /dev/null
+++ b/patterns-modules/clean-architecture/src/test/java/com/baeldung/pattern/richdomainmodel/RichDomainModelUnitTest.java
@@ -0,0 +1,33 @@
+package com.baeldung.pattern.richdomainmodel;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+public class RichDomainModelUnitTest {
+
+ @Test
+ public void givenATennisGame_whenReceiverWinsThreePoints_thenScoreIsFortyLove() {
+ TennisGame game = new TennisGame("server", "receiver");
+
+ game.wonPoint("server");
+ game.wonPoint("server");
+ game.wonPoint("server");
+
+ assertThat(game.getScore())
+ .isEqualTo("Forty-Love");
+ }
+
+ @Test
+ public void givenATennisGame_whenEachPlayerWonTwoPoints_thenScoreIsThirtyAll() {
+ TennisGame game = new TennisGame("server", "receiver");
+
+ game.wonPoint("server");
+ game.wonPoint("server");
+ game.wonPoint("receiver");
+ game.wonPoint("receiver");
+
+ assertThat(game.getScore())
+ .isEqualTo("Thirty-All");
+ }
+}
\ No newline at end of file
diff --git a/patterns-modules/cqrs-es/pom.xml b/patterns-modules/cqrs-es/pom.xml
index 737eb00b9b..ee5820ff96 100644
--- a/patterns-modules/cqrs-es/pom.xml
+++ b/patterns-modules/cqrs-es/pom.xml
@@ -18,11 +18,7 @@
lombok
${lombok.version}
-
- org.junit.vintage
- junit-vintage-engine
- test
-
+
\ No newline at end of file
diff --git a/patterns-modules/design-patterns-behavioral-2/README.md b/patterns-modules/design-patterns-behavioral-2/README.md
index 9618a9c458..db4dd8d719 100644
--- a/patterns-modules/design-patterns-behavioral-2/README.md
+++ b/patterns-modules/design-patterns-behavioral-2/README.md
@@ -1,2 +1,3 @@
### Relevant Articles:
- [Memento Design Pattern in Java](https://www.baeldung.com/java-memento-design-pattern)
+- [Difference Between Fluent Interface and Builder Pattern in Java](https://www.baeldung.com/java-fluent-interface-vs-builder-pattern)
diff --git a/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/HtmlDocument.java b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/HtmlDocument.java
new file mode 100644
index 0000000000..db0f988908
--- /dev/null
+++ b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/HtmlDocument.java
@@ -0,0 +1,46 @@
+package com.baeldung.fluentinterface;
+
+import static java.util.Arrays.stream;
+import static java.util.stream.Collectors.joining;
+
+public class HtmlDocument {
+ private final String content;
+
+ private HtmlDocument(String html) {
+ this.content = html;
+ }
+
+ public HtmlDocument() {
+ this("");
+ }
+
+ public String html() {
+ return String.format("%s", content);
+ }
+
+ public HtmlDocument header(String header) {
+ return new HtmlDocument(String.format("%s
%s
", content, header));
+ }
+
+ public HtmlDocument secondaryHeader(String header) {
+ return new HtmlDocument(String.format("%s %s
", content, header));
+ }
+
+ public HtmlDocument paragraph(String paragraph) {
+ return new HtmlDocument(String.format("%s %s
", content, paragraph));
+ }
+
+ public HtmlDocument horizontalLine() {
+ return new HtmlDocument(String.format("%s
", content));
+ }
+
+ public HtmlDocument orderedList(String... items) {
+ String listItems = stream(items).map(el -> String.format("%s", el)).collect(joining());
+ return new HtmlDocument(String.format("%s %s
", content, listItems));
+ }
+
+ public HtmlDocument unorderedList(String... items) {
+ String listItems = stream(items).map(el -> String.format("%s", el)).collect(joining());
+ return new HtmlDocument(String.format("%s ", content, listItems));
+ }
+}
\ No newline at end of file
diff --git a/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/LargeHtmlDocument.java b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/LargeHtmlDocument.java
new file mode 100644
index 0000000000..fff8c97b5b
--- /dev/null
+++ b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/LargeHtmlDocument.java
@@ -0,0 +1,40 @@
+package com.baeldung.fluentinterface;
+
+import com.baeldung.fluentinterface.components.HtmlElement;
+import com.baeldung.fluentinterface.components.HtmlHeader;
+import com.baeldung.fluentinterface.components.HtmlList;
+
+import static java.lang.String.format;
+import static java.util.Arrays.stream;
+import static java.util.stream.Collectors.joining;
+
+public class LargeHtmlDocument {
+ private final String content;
+
+ private LargeHtmlDocument(String html) {
+ this.content = html;
+ }
+
+ public LargeHtmlDocument() {
+ this("");
+ }
+
+ public String html() {
+ return format("%s", content);
+ }
+
+ public LargeHtmlDocument head(HtmlElement head) {
+ return new LargeHtmlDocument(format("%s %s", content, head.html()));
+ }
+ public LargeHtmlDocument body(HtmlElement body) {
+ return new LargeHtmlDocument(format("%s %s", content, body.html()));
+ }
+ public LargeHtmlDocument footer(HtmlElement footer) {
+ return new LargeHtmlDocument(format("%s ", content, footer.html()));
+ }
+
+ private LargeHtmlDocument append(String html) {
+ return new LargeHtmlDocument(format("%s %s", content, html));
+ }
+
+}
\ No newline at end of file
diff --git a/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/User.java b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/User.java
new file mode 100644
index 0000000000..1606369c26
--- /dev/null
+++ b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/User.java
@@ -0,0 +1,65 @@
+package com.baeldung.fluentinterface;
+
+public class User {
+ private String firstName;
+ private String lastName;
+ private String email;
+ private String username;
+ private Long id;
+
+ public String name() {
+ return firstName + " " + lastName;
+ }
+
+ public User(String firstName, String lastName, String email, String username, Long id) {
+ this.firstName = firstName;
+ this.lastName = lastName;
+ this.email = email;
+ this.username = username;
+ this.id = id;
+ }
+
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static class Builder {
+ private String firstName;
+ private String lastName;
+ private String email;
+ private String username;
+ private Long id;
+
+ private Builder() {
+ }
+
+ public Builder firstName(String firstName) {
+ this.firstName = firstName;
+ return this;
+ }
+
+ public Builder lastName(String lastName) {
+ this.lastName = lastName;
+ return this;
+ }
+
+ public Builder email(String email) {
+ this.email = email;
+ return this;
+ }
+
+ public Builder username(String username) {
+ this.username = username;
+ return this;
+ }
+
+ public Builder id(Long id) {
+ this.id = id;
+ return this;
+ }
+
+ public User build() {
+ return new User(firstName, lastName, email, username, id);
+ }
+ }
+}
diff --git a/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HorizontalLine.java b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HorizontalLine.java
new file mode 100644
index 0000000000..66979b98f9
--- /dev/null
+++ b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HorizontalLine.java
@@ -0,0 +1,8 @@
+package com.baeldung.fluentinterface.components;
+
+public class HorizontalLine implements HtmlElement {
+ @Override
+ public String html() {
+ return "
";
+ }
+}
diff --git a/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlDiv.java b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlDiv.java
new file mode 100644
index 0000000000..7625401444
--- /dev/null
+++ b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlDiv.java
@@ -0,0 +1,29 @@
+package com.baeldung.fluentinterface.components;
+
+public class HtmlDiv implements HtmlElement {
+
+ private final String content;
+
+ public HtmlDiv(String content) {
+ this.content = content;
+ }
+
+ public HtmlDiv() {
+ this.content = "";
+ }
+
+ public HtmlDiv append(HtmlElement element) {
+ return new HtmlDiv(content + element.html());
+ }
+ public HtmlDiv text(String text) {
+ return new HtmlDiv(content + text);
+ }
+ public HtmlDiv paragraph(String text) {
+ return new HtmlDiv(content + text);
+ }
+
+ @Override
+ public String html() {
+ return String.format("%s
", content);
+ }
+}
diff --git a/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlElement.java b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlElement.java
new file mode 100644
index 0000000000..ff46dc0029
--- /dev/null
+++ b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlElement.java
@@ -0,0 +1,5 @@
+package com.baeldung.fluentinterface.components;
+
+public interface HtmlElement {
+ String html();
+}
diff --git a/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlHeader.java b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlHeader.java
new file mode 100644
index 0000000000..12c400014d
--- /dev/null
+++ b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlHeader.java
@@ -0,0 +1,34 @@
+package com.baeldung.fluentinterface.components;
+
+public class HtmlHeader implements HtmlElement {
+
+ private final Type type;
+ private final String value;
+
+ public HtmlHeader(Type type, String value) {
+ this.type = type;
+ this.value = value;
+ }
+
+ @Override
+ public String html() {
+ return String.format("<%s>%s%s>", type.tag(), value, type.tag());
+ }
+
+ public enum Type {
+ PRIMARY("h1"),
+ SECONDARY("h2"),
+ THIRD("h3"),
+ FOURTH("h4");
+
+ private final String tag;
+
+ Type(String tag) {
+ this.tag = tag;
+ }
+
+ public String tag() {
+ return tag;
+ }
+ }
+}
diff --git a/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlList.java b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlList.java
new file mode 100644
index 0000000000..030c9aaa5c
--- /dev/null
+++ b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlList.java
@@ -0,0 +1,39 @@
+package com.baeldung.fluentinterface.components;
+
+import java.util.Arrays;
+import java.util.List;
+
+import static java.lang.String.format;
+import static java.util.stream.Collectors.joining;
+
+public class HtmlList implements HtmlElement {
+
+ private final Type type;
+ private final List items;
+
+ public HtmlList(Type type, String... items) {
+ this.type = type;
+ this.items = Arrays.asList(items);
+ }
+
+ @Override
+ public String html() {
+ String listItems = items.stream().map(el -> format("%s", el)).collect(joining());
+ return String.format("<%s>%s%s>", type.tag(), listItems, type.tag());
+ }
+
+ public enum Type {
+ ORDERED("ol"),
+ UNORDERED("ul");
+
+ private final String tag;
+
+ Type(String tag) {
+ this.tag = tag;
+ }
+
+ public String tag() {
+ return tag;
+ }
+ }
+}
diff --git a/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlSpan.java b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlSpan.java
new file mode 100644
index 0000000000..2bdf55eb72
--- /dev/null
+++ b/patterns-modules/design-patterns-behavioral-2/src/main/java/com/baeldung/fluentinterface/components/HtmlSpan.java
@@ -0,0 +1,27 @@
+package com.baeldung.fluentinterface.components;
+
+public class HtmlSpan implements HtmlElement {
+
+ private final String content;
+
+ public HtmlSpan(String content) {
+ this.content = content;
+ }
+
+ public HtmlSpan() {
+ this.content = "";
+ }
+
+ public HtmlSpan append(HtmlElement element) {
+ return new HtmlSpan(content + element.html());
+ }
+
+ public HtmlSpan paragraph(String text) {
+ return new HtmlSpan(content + text);
+ }
+
+ @Override
+ public String html() {
+ return String.format("%s", content);
+ }
+}
diff --git a/patterns-modules/design-patterns-behavioral-2/src/test/java/com/baeldung/fluentinterface/FluentInterfaceUnitTest.java b/patterns-modules/design-patterns-behavioral-2/src/test/java/com/baeldung/fluentinterface/FluentInterfaceUnitTest.java
new file mode 100644
index 0000000000..bf5aadcf13
--- /dev/null
+++ b/patterns-modules/design-patterns-behavioral-2/src/test/java/com/baeldung/fluentinterface/FluentInterfaceUnitTest.java
@@ -0,0 +1,101 @@
+package com.baeldung.fluentinterface;
+
+import com.baeldung.fluentinterface.components.*;
+import com.baeldung.fluentinterface.components.HtmlHeader.Type;
+import org.junit.jupiter.api.Test;
+
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static com.baeldung.fluentinterface.components.HtmlList.Type.ORDERED;
+import static org.assertj.core.api.Assertions.assertThat;
+
+class FluentInterfaceUnitTest {
+
+ @Test
+ void givenTenNumbers_thenStreamIsProcessedCorrectly() {
+ Stream numbers = Stream.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+ Stream processedNumbers = numbers.distinct()
+ .filter(nr -> nr % 2 == 0)
+ .skip(1)
+ .limit(4)
+ .map(nr -> "#" + nr)
+ .peek(nr -> System.out.println(nr));
+ String result = processedNumbers.collect(Collectors.joining(", "));
+
+ assertThat(result).isEqualTo("#2, #4, #6, #8");
+ }
+
+ @Test
+ void givenUserBuilder_thenCreateUserCorrectly() {
+ User.Builder userBuilder = User.builder();
+ userBuilder = userBuilder
+ .firstName("John")
+ .lastName("Doe")
+ .email("jd@gmail.com")
+ .username("jd_2000")
+ .id(1234L);
+
+ User user = userBuilder.build();
+
+ assertThat(user.name()).isEqualTo("John Doe");
+ }
+
+ @Test
+ void givenHtmlDocument_thenGenerateHtmlCorrectly() {
+ HtmlDocument document = new HtmlDocument()
+ .header("Principles of O.O.P.")
+ .paragraph("OOP in Java.")
+ .horizontalLine()
+ .paragraph("The main pillars of OOP are:")
+ .orderedList("Encapsulation", "Inheritance", "Abstraction", "Polymorphism");
+ String html = document.html();
+
+ assertThat(html).isEqualToIgnoringWhitespace(
+ ""
+ + "Principles of O.O.P.
"
+ + "OOP in Java.
"
+ + "
"
+ + "The main pillars of OOP are:
"
+ + ""
+ + "- Encapsulation
"
+ + "- Inheritance
"
+ + "- Abstraction
"
+ + "- Polymorphism
"
+ + "
"
+ + ""
+ );
+ }
+
+ @Test
+ void givenHtmlDocument_thenInstanceIsImmutable() {
+ HtmlDocument document = new HtmlDocument()
+ .header("Principles of O.O.P.");
+ HtmlDocument updatedDocument = document
+ .paragraph("OOP in Java.");
+
+ assertThat(document).isNotEqualTo(updatedDocument);
+ }
+
+
+ @Test
+ void givenLargeHtmlDocument_thenGenerateHtmlCorrectly() {
+ String html = new LargeHtmlDocument()
+ .head(new HtmlHeader(Type.PRIMARY, "title"))
+ .body(new HtmlDiv()
+ .append(new HtmlSpan()
+ .paragraph("learning OOP from John Doe")
+ .append(new HorizontalLine())
+ .paragraph("The pillars of OOP:")
+ )
+ .append(new HtmlList(ORDERED, "Encapsulation", "Inheritance", "Abstraction", "Polymorphism"))
+ )
+ .footer(new HtmlDiv()
+ .paragraph("trademark John Doe")
+ )
+ .html();
+
+ String expectedHtml = " title
learning OOP from John Doe
The pillars of OOP:- Encapsulation
- Inheritance
- Abstraction
- Polymorphism
";
+ assertThat(html).isEqualToIgnoringWhitespace(expectedHtml);
+ }
+}
\ No newline at end of file
diff --git a/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java b/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java
index 2ee6f93f9b..e06f1291a6 100644
--- a/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java
+++ b/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/HighEndComputerBuilder.java
@@ -1,5 +1,8 @@
package com.baeldung.templatemethod.model;
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
public class HighEndComputerBuilder extends ComputerBuilder {
@Override
@@ -11,7 +14,7 @@ public class HighEndComputerBuilder extends ComputerBuilder {
public void setupMotherboard() {
motherboardSetupStatus.add("Screwing the high-end motherboard to the case.");
motherboardSetupStatus.add("Pluging in the power supply connectors.");
- motherboardSetupStatus.forEach(step -> System.out.println(step));
+ motherboardSetupStatus.forEach(step -> log.debug(step));
}
@Override
diff --git a/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java b/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java
index da2c2e9b2d..f5b953c830 100644
--- a/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java
+++ b/patterns-modules/design-patterns-behavioral/src/main/java/com/baeldung/templatemethod/model/StandardComputerBuilder.java
@@ -1,5 +1,8 @@
package com.baeldung.templatemethod.model;
-
+
+import lombok.extern.slf4j.Slf4j;
+
+@Slf4j
public class StandardComputerBuilder extends ComputerBuilder {
@Override
@@ -11,7 +14,7 @@ public class StandardComputerBuilder extends ComputerBuilder {
public void setupMotherboard() {
motherboardSetupStatus.add("Screwing the standard motherboard to the case.");
motherboardSetupStatus.add("Pluging in the power supply connectors.");
- motherboardSetupStatus.forEach(step -> System.out.println(step));
+ motherboardSetupStatus.forEach(step -> log.debug(step));
}
@Override
diff --git a/patterns-modules/design-patterns-behavioral/src/test/resources/logback-test.xml b/patterns-modules/design-patterns-behavioral/src/test/resources/logback-test.xml
new file mode 100644
index 0000000000..499cc828a2
--- /dev/null
+++ b/patterns-modules/design-patterns-behavioral/src/test/resources/logback-test.xml
@@ -0,0 +1,12 @@
+
+
+
+
+ %d{yyyy-MM-dd HH:mm:ss} | %-5p | [%thread] %logger{5}:%L - %msg%n
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/patterns-modules/design-patterns-structural/README.md b/patterns-modules/design-patterns-structural/README.md
index d2102868b2..996b500842 100644
--- a/patterns-modules/design-patterns-structural/README.md
+++ b/patterns-modules/design-patterns-structural/README.md
@@ -6,3 +6,4 @@
- [The Adapter Pattern in Java](https://www.baeldung.com/java-adapter-pattern)
- [The Proxy Pattern in Java](https://www.baeldung.com/java-proxy-pattern)
- [The Bridge Pattern in Java](https://www.baeldung.com/java-bridge-pattern)
+- [Pipeline Design Pattern in Java](https://www.baeldung.com/java-pipeline-design-pattern)
diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/AdapterPatternDriver.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/AdapterPatternDriver.java
deleted file mode 100644
index 9f696a5f40..0000000000
--- a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/AdapterPatternDriver.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.baeldung.adapter;
-
-import static com.baeldung.util.LoggerUtil.LOG;
-
-public class AdapterPatternDriver {
-
- public static void main(String args[]) {
- Movable bugattiVeyron = new BugattiVeyron();
- MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron);
- LOG.info("Bugatti Veyron Super Sport's top speed is " + bugattiVeyronAdapter.getSpeed() + " Kmph.");
-
- Movable mcLaren = new McLaren();
- MovableAdapter mcLarenAdapter = new MovableAdapterImpl(mcLaren);
- LOG.info("McLaren F1 top speed is " + mcLarenAdapter.getSpeed() + " Kmph.");
-
- Movable astonMartin = new AstonMartin();
- MovableAdapter astonMartinAdapter = new MovableAdapterImpl(astonMartin);
- LOG.info("McLaren F1 top speed is " + astonMartinAdapter.getSpeed() + " Kmph.");
- }
-}
diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/AstonMartin.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/AstonMartin.java
deleted file mode 100644
index c6aa0c525a..0000000000
--- a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/AstonMartin.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.baeldung.adapter;
-
-public class AstonMartin implements Movable {
- @Override
- public double getSpeed() {
- return 220;
- }
-}
diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/BugattiVeyron.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/BugattiVeyron.java
deleted file mode 100644
index e7d47d138a..0000000000
--- a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/BugattiVeyron.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.baeldung.adapter;
-
-public class BugattiVeyron implements Movable {
- @Override
- public double getSpeed() {
- return 268;
- }
-}
diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/IteratorAdapter.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/IteratorAdapter.java
new file mode 100644
index 0000000000..0abf333068
--- /dev/null
+++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/IteratorAdapter.java
@@ -0,0 +1,24 @@
+package com.baeldung.adapter;
+
+import java.util.Enumeration;
+import java.util.Iterator;
+
+public class IteratorAdapter implements Iterator {
+
+ private Enumeration enumeration;
+
+ public IteratorAdapter(Enumeration enumeration) {
+ this.enumeration = enumeration;
+ }
+
+ @Override
+ public boolean hasNext() {
+ return enumeration.hasMoreElements();
+ }
+
+ @Override
+ public E next() {
+ return enumeration.nextElement();
+ }
+
+}
diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/McLaren.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/McLaren.java
deleted file mode 100644
index 4ca1cde856..0000000000
--- a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/McLaren.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.baeldung.adapter;
-
-public class McLaren implements Movable {
- @Override
- public double getSpeed() {
- return 241;
- }
-}
diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/Movable.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/Movable.java
deleted file mode 100644
index bec0bee568..0000000000
--- a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/Movable.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package com.baeldung.adapter;
-
-public interface Movable {
- // returns speed in MPH
- double getSpeed();
-}
\ No newline at end of file
diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/MovableAdapter.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/MovableAdapter.java
deleted file mode 100644
index 8d529e7b13..0000000000
--- a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/MovableAdapter.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package com.baeldung.adapter;
-
-public interface MovableAdapter {
- // returns speed in KMPH
- double getSpeed();
-}
diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/MovableAdapterImpl.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/MovableAdapterImpl.java
deleted file mode 100644
index 8f18cc9942..0000000000
--- a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/MovableAdapterImpl.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.baeldung.adapter;
-
-public class MovableAdapterImpl implements MovableAdapter {
- private Movable luxuryCars;
-
- public MovableAdapterImpl(Movable luxuryCars) {
- this.luxuryCars = luxuryCars;
- }
-
- @Override
- public double getSpeed() {
- double mph = luxuryCars.getSpeed();
- return convertMPHtoKMPH(mph);
- }
-
- private double convertMPHtoKMPH(double mph) {
- return mph * 1.60934;
- }
-}
diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/StringTokenizerIteratorAdapter.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/StringTokenizerIteratorAdapter.java
new file mode 100644
index 0000000000..36c17b2609
--- /dev/null
+++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/adapter/StringTokenizerIteratorAdapter.java
@@ -0,0 +1,29 @@
+package com.baeldung.adapter;
+
+import java.util.Iterator;
+import java.util.StringTokenizer;
+
+public class StringTokenizerIteratorAdapter extends StringTokenizer implements Iterator {
+
+ public StringTokenizerIteratorAdapter(final String str, final String delim, final boolean returnDelims) {
+ super(str, delim, returnDelims);
+ }
+
+ public StringTokenizerIteratorAdapter(final String str, final String delim) {
+ super(str, delim);
+ }
+
+ public StringTokenizerIteratorAdapter(final String str) {
+ super(str);
+ }
+
+ @Override
+ public boolean hasNext() {
+ return hasMoreTokens();
+ }
+
+ @Override
+ public String next() {
+ return nextToken();
+ }
+}
diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/immutable/Pipe.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/immutable/Pipe.java
new file mode 100644
index 0000000000..6fdb4c71c3
--- /dev/null
+++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/immutable/Pipe.java
@@ -0,0 +1,5 @@
+package com.baeldung.pipeline.immutable;
+
+public interface Pipe {
+ OUT process(IN input);
+}
diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/immutable/Pipeline.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/immutable/Pipeline.java
new file mode 100644
index 0000000000..db46a26d7e
--- /dev/null
+++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/immutable/Pipeline.java
@@ -0,0 +1,37 @@
+package com.baeldung.pipeline.immutable;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+
+public class Pipeline {
+
+ private Collection> pipes;
+
+ private Pipeline(Pipe pipe) {
+ pipes = Collections.singletonList(pipe);
+ }
+
+ private Pipeline(Collection> pipes) {
+ this.pipes = new ArrayList<>(pipes);
+ }
+
+ public static Pipeline of(Pipe pipe) {
+ return new Pipeline<>(pipe);
+ }
+
+
+ public Pipeline withNextPipe(Pipe pipe) {
+ final ArrayList> newPipes = new ArrayList<>(pipes);
+ newPipes.add(pipe);
+ return new Pipeline<>(newPipes);
+ }
+
+ public OUT process(IN input) {
+ Object output = input;
+ for (final Pipe pipe : pipes) {
+ output = pipe.process(output);
+ }
+ return (OUT) output;
+ }
+}
diff --git a/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/pipes/Pipe.java b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/pipes/Pipe.java
new file mode 100644
index 0000000000..93f005fdd2
--- /dev/null
+++ b/patterns-modules/design-patterns-structural/src/main/java/com/baeldung/pipeline/pipes/Pipe.java
@@ -0,0 +1,9 @@
+package com.baeldung.pipeline.pipes;
+
+public interface Pipe {
+ OUT process(IN input);
+
+ default Pipe add(Pipe pipe) {
+ return input -> pipe.process(process(input));
+ }
+}
diff --git a/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/adapter/AdapterPatternIntegrationTest.java b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/adapter/AdapterPatternIntegrationTest.java
deleted file mode 100644
index 536caf7341..0000000000
--- a/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/adapter/AdapterPatternIntegrationTest.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.baeldung.adapter;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-public class AdapterPatternIntegrationTest {
- @Test
- public void givenMovableAdapter_WhenConvertingMPHToKMPH_thenSuccessfullyConverted() {
- Movable bugattiVeyron = new BugattiVeyron();
- MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron);
- assertEquals(bugattiVeyronAdapter.getSpeed(), 431.30312, 0.00001);
-
- Movable mcLaren = new McLaren();
- MovableAdapter mcLarenAdapter = new MovableAdapterImpl(mcLaren);
- assertEquals(mcLarenAdapter.getSpeed(), 387.85094, 0.00001);
-
- Movable astonMartin = new AstonMartin();
- MovableAdapter astonMartinAdapter = new MovableAdapterImpl(astonMartin);
- assertEquals(astonMartinAdapter.getSpeed(), 354.0548, 0.00001);
- }
-}
-
diff --git a/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/adapter/IteratorAdapterUnitTest.java b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/adapter/IteratorAdapterUnitTest.java
new file mode 100644
index 0000000000..19de6c92ba
--- /dev/null
+++ b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/adapter/IteratorAdapterUnitTest.java
@@ -0,0 +1,34 @@
+package com.baeldung.adapter;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.StringTokenizer;
+import org.junit.jupiter.api.Test;
+
+class IteratorAdapterUnitTest {
+
+ public static final String STRING_DATA = "Welcome to baeldung.com";
+ private final StringTokenizer tokenizer = new StringTokenizer(STRING_DATA);
+ private final Iterator tokenizerAdapter = new StringTokenizerIteratorAdapter(STRING_DATA);
+ private final List expectedTokensForString = Arrays.asList("Welcome", "to", "baeldung.com");
+
+ @Test
+ void givenTokenizer_thenAdapterProducesCorrectResult() {
+ List actualTokens = new ArrayList<>();
+ new IteratorAdapter(tokenizer).forEachRemaining(s -> actualTokens.add((String) s));
+ assertEquals(expectedTokensForString, actualTokens);
+ }
+
+ @Test
+ void givenTokenizerAdapter_thenIteratorProducesCorrectResult() {
+ List actualTokens = new ArrayList<>();
+ tokenizerAdapter.forEachRemaining(actualTokens::add);
+ assertEquals(expectedTokensForString, actualTokens);
+ }
+
+
+}
\ No newline at end of file
diff --git a/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/BiFunctionPipelineUnitTest.java b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/BiFunctionPipelineUnitTest.java
new file mode 100644
index 0000000000..5f094ad6e8
--- /dev/null
+++ b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/BiFunctionPipelineUnitTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.pipeline;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.function.BiFunction;
+import java.util.function.Function;
+import org.junit.jupiter.api.Test;
+
+class BiFunctionPipelineUnitTest {
+
+ @Test
+ void whenCombiningFunctionAndBiFunctions_andInitializingPipeline_thenResultIsCorrect() {
+ BiFunction add = Integer::sum;
+ BiFunction mul = (a, b) -> a * b;
+ Function toString = Object::toString;
+ BiFunction pipeline = add.andThen(a -> mul.apply(a, 2))
+ .andThen(toString);
+ String result = pipeline.apply(1, 2);
+ String expected = "6";
+ assertEquals(expected, result);
+ }
+}
\ No newline at end of file
diff --git a/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/FunctionPipelineUnitTest.java b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/FunctionPipelineUnitTest.java
new file mode 100644
index 0000000000..71bc14a5eb
--- /dev/null
+++ b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/FunctionPipelineUnitTest.java
@@ -0,0 +1,21 @@
+package com.baeldung.pipeline;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.util.function.Function;
+import org.junit.jupiter.api.Test;
+
+class FunctionPipelineUnitTest {
+
+ @Test
+ void whenCombiningThreeFunctions_andInitializingPipeline_thenResultIsCorrect() {
+ Function square = s -> s * s;
+ Function half = s -> s / 2;
+ Function toString = Object::toString;
+ Function pipeline = square.andThen(half)
+ .andThen(toString);
+ String result = pipeline.apply(5);
+ String expected = "12";
+ assertEquals(expected, result);
+ }
+}
\ No newline at end of file
diff --git a/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/PipeUnitTest.java b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/PipeUnitTest.java
new file mode 100644
index 0000000000..6a3a988f89
--- /dev/null
+++ b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/PipeUnitTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.pipeline;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.baeldung.pipeline.pipes.Pipe;
+import org.junit.jupiter.api.Test;
+
+class PipeUnitTest {
+
+ @Test
+ void whenCombiningThreePipes_andInitializingPipeline_thenResultIsCorrect() {
+ Pipe square = s -> s * s;
+ Pipe half = s -> s / 2;
+ Pipe toString = Object::toString;
+ Pipe pipeline = square.add(half).add(toString);
+ String result = pipeline.process(5);
+ String expected = "12";
+ assertThat(result).isEqualTo(expected);
+ }
+}
\ No newline at end of file
diff --git a/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/PipelineUnitTest.java b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/PipelineUnitTest.java
new file mode 100644
index 0000000000..2cbafc6213
--- /dev/null
+++ b/patterns-modules/design-patterns-structural/src/test/java/com/baeldung/pipeline/PipelineUnitTest.java
@@ -0,0 +1,24 @@
+package com.baeldung.pipeline;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.baeldung.pipeline.immutable.Pipe;
+import com.baeldung.pipeline.immutable.Pipeline;
+import org.junit.jupiter.api.Test;
+
+class PipelineUnitTest {
+
+ @Test
+ void whenCombiningThreePipes_andInitializingPipeline_thenResultIsCorrect() {
+ Pipe square = s -> s * s;
+ Pipe half = s -> s / 2;
+ Pipe toString = Object::toString;
+ Pipeline squarePipeline = Pipeline.of(square);
+ Pipeline squareAndHalfPipeline = squarePipeline.withNextPipe(half);
+ Pipeline squareHalfAndStringPipeline = squareAndHalfPipeline.withNextPipe(toString);
+
+ String result = squareHalfAndStringPipeline.process(5);
+ String expected = "12";
+ assertThat(result).isEqualTo(expected);
+ }
+}
\ No newline at end of file
diff --git a/patterns-modules/enterprise-patterns/pom.xml b/patterns-modules/enterprise-patterns/pom.xml
index 2c59ae2536..0e9edbff67 100644
--- a/patterns-modules/enterprise-patterns/pom.xml
+++ b/patterns-modules/enterprise-patterns/pom.xml
@@ -65,7 +65,7 @@
3.7.4
- 2.2.2.RELEASE
+ 2.7.8
2.17.1
diff --git a/patterns-modules/front-controller/pom.xml b/patterns-modules/front-controller/pom.xml
index 84de94cee3..567f3fb793 100644
--- a/patterns-modules/front-controller/pom.xml
+++ b/patterns-modules/front-controller/pom.xml
@@ -17,6 +17,7 @@
javax.servlet
javax.servlet-api
+ ${javax.servlet-api.version}
@@ -25,10 +26,12 @@
org.apache.maven.plugins
maven-war-plugin
+ ${maven-war-plugin.version}
org.eclipse.jetty
jetty-maven-plugin
+ ${jetty-maven-plugin.version}
/front-controller
@@ -38,4 +41,10 @@
+
+ 3.3.2
+ 11.0.13
+
+
+
\ No newline at end of file
diff --git a/patterns-modules/idd/README.md b/patterns-modules/idd/README.md
new file mode 100644
index 0000000000..7d843af9ea
--- /dev/null
+++ b/patterns-modules/idd/README.md
@@ -0,0 +1 @@
+### Relevant Articles:
diff --git a/patterns-modules/idd/pom.xml b/patterns-modules/idd/pom.xml
new file mode 100644
index 0000000000..e08e058b92
--- /dev/null
+++ b/patterns-modules/idd/pom.xml
@@ -0,0 +1,20 @@
+
+
+ 4.0.0
+ idd
+ 1.0
+ idd
+
+
+
+ jar
+
+
+ com.baeldung
+ patterns-modules
+ 1.0.0-SNAPSHOT
+
+
+
\ No newline at end of file
diff --git a/patterns-modules/idd/src/main/java/com/baeldung/idd/CreateHelpRequestDTO.java b/patterns-modules/idd/src/main/java/com/baeldung/idd/CreateHelpRequestDTO.java
new file mode 100644
index 0000000000..87084474db
--- /dev/null
+++ b/patterns-modules/idd/src/main/java/com/baeldung/idd/CreateHelpRequestDTO.java
@@ -0,0 +1,15 @@
+package com.baeldung.idd;
+
+public class CreateHelpRequestDTO {
+
+ private final HelpRequestStatus status;
+
+ public CreateHelpRequestDTO(HelpRequestStatus status) {
+ this.status = status;
+ }
+
+ public HelpRequestStatus getStatus() {
+ return status;
+ }
+
+}
diff --git a/patterns-modules/idd/src/main/java/com/baeldung/idd/HelpRequestDTO.java b/patterns-modules/idd/src/main/java/com/baeldung/idd/HelpRequestDTO.java
new file mode 100644
index 0000000000..2ad0c5f100
--- /dev/null
+++ b/patterns-modules/idd/src/main/java/com/baeldung/idd/HelpRequestDTO.java
@@ -0,0 +1,13 @@
+package com.baeldung.idd;
+
+public class HelpRequestDTO {
+ private HelpRequestStatus status;
+
+ public HelpRequestStatus getStatus() {
+ return status;
+ }
+
+ public HelpRequestDTO(HelpRequestStatus status) {
+ this.status = status;
+ }
+}
diff --git a/patterns-modules/idd/src/main/java/com/baeldung/idd/HelpRequestService.java b/patterns-modules/idd/src/main/java/com/baeldung/idd/HelpRequestService.java
new file mode 100644
index 0000000000..02c0b2531c
--- /dev/null
+++ b/patterns-modules/idd/src/main/java/com/baeldung/idd/HelpRequestService.java
@@ -0,0 +1,11 @@
+package com.baeldung.idd;
+
+import java.util.List;
+
+public interface HelpRequestService {
+ HelpRequestDTO createHelpRequest(CreateHelpRequestDTO createHelpRequestDTO);
+
+ List findAllByStatus(HelpRequestStatus status);
+
+ HelpRequestDTO updateHelpRequest(UpdateHelpRequestDTO updateHelpRequestDTO);
+}
diff --git a/patterns-modules/idd/src/main/java/com/baeldung/idd/HelpRequestServiceImpl.java b/patterns-modules/idd/src/main/java/com/baeldung/idd/HelpRequestServiceImpl.java
new file mode 100644
index 0000000000..8ffed62078
--- /dev/null
+++ b/patterns-modules/idd/src/main/java/com/baeldung/idd/HelpRequestServiceImpl.java
@@ -0,0 +1,24 @@
+package com.baeldung.idd;
+
+import java.util.List;
+
+public class HelpRequestServiceImpl implements HelpRequestService {
+
+ @Override
+ public HelpRequestDTO createHelpRequest(CreateHelpRequestDTO createHelpRequestDTO) {
+ // here goes the implementation
+ return new HelpRequestDTO(createHelpRequestDTO.getStatus());
+ }
+
+ @Override
+ public List findAllByStatus(HelpRequestStatus status) {
+ // here goes the implementation
+ return List.of(new HelpRequestDTO(status), new HelpRequestDTO(status));
+ }
+
+ @Override
+ public HelpRequestDTO updateHelpRequest(UpdateHelpRequestDTO updateHelpRequestDTO) {
+ // here goes the implementation
+ return new HelpRequestDTO(updateHelpRequestDTO.getStatus());
+ }
+}
diff --git a/patterns-modules/idd/src/main/java/com/baeldung/idd/HelpRequestStatus.java b/patterns-modules/idd/src/main/java/com/baeldung/idd/HelpRequestStatus.java
new file mode 100644
index 0000000000..adb2fb5cc3
--- /dev/null
+++ b/patterns-modules/idd/src/main/java/com/baeldung/idd/HelpRequestStatus.java
@@ -0,0 +1,6 @@
+package com.baeldung.idd;
+
+public enum HelpRequestStatus {
+ OPEN, IN_PROGRESS, CLOSED
+}
+
diff --git a/patterns-modules/idd/src/main/java/com/baeldung/idd/UpdateHelpRequestDTO.java b/patterns-modules/idd/src/main/java/com/baeldung/idd/UpdateHelpRequestDTO.java
new file mode 100644
index 0000000000..04a46e3d27
--- /dev/null
+++ b/patterns-modules/idd/src/main/java/com/baeldung/idd/UpdateHelpRequestDTO.java
@@ -0,0 +1,14 @@
+package com.baeldung.idd;
+
+public class UpdateHelpRequestDTO {
+
+ private final HelpRequestStatus status;
+
+ public UpdateHelpRequestDTO(HelpRequestStatus status) {
+ this.status = status;
+ }
+
+ public HelpRequestStatus getStatus() {
+ return status;
+ }
+}
diff --git a/patterns-modules/idd/src/test/java/com/baeldung/idd/HelpRequestServiceUnitTest.java b/patterns-modules/idd/src/test/java/com/baeldung/idd/HelpRequestServiceUnitTest.java
new file mode 100644
index 0000000000..52cbcaba57
--- /dev/null
+++ b/patterns-modules/idd/src/test/java/com/baeldung/idd/HelpRequestServiceUnitTest.java
@@ -0,0 +1,47 @@
+package com.baeldung.idd;
+
+import org.assertj.core.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+public class HelpRequestServiceUnitTest {
+
+ HelpRequestService testHelpRequestService = new HelpRequestService() {
+ @Override
+ public HelpRequestDTO createHelpRequest(CreateHelpRequestDTO createHelpRequestDTO) {
+ return new HelpRequestDTO(HelpRequestStatus.OPEN);
+ }
+
+ @Override
+ public List findAllByStatus(HelpRequestStatus status) {
+ return List.of(new HelpRequestDTO(HelpRequestStatus.OPEN));
+ }
+
+ @Override
+ public HelpRequestDTO updateHelpRequest(UpdateHelpRequestDTO updateHelpRequestDTO) {
+ return new HelpRequestDTO(HelpRequestStatus.OPEN);
+ }
+ };
+
+ @Test
+ public void givenHelpRequest_whenCreateHelpRequest_thenHelpRequestIsCreated() {
+ // given
+ CreateHelpRequestDTO createHelpRequestDTO = new CreateHelpRequestDTO(HelpRequestStatus.OPEN);
+
+ // when
+ HelpRequestDTO helpRequestDTO = testHelpRequestService.createHelpRequest(createHelpRequestDTO);
+
+ // then
+ Assertions.assertThat(helpRequestDTO).isNotNull();
+ Assertions.assertThat(helpRequestDTO.getStatus()).isEqualTo(HelpRequestStatus.OPEN);
+ }
+
+ @Test
+ public void givenHelpRequestList_whenFindAllByStatus_shouldContainOnlyStatus() {
+ HelpRequestService helpRequestService = new HelpRequestServiceImpl();
+ List allByStatusOpen = helpRequestService.findAllByStatus(HelpRequestStatus.OPEN);
+ Assertions.assertThat(allByStatusOpen).extracting(HelpRequestDTO::getStatus).containsOnly(HelpRequestStatus.OPEN);
+ }
+
+}
diff --git a/patterns-modules/intercepting-filter/pom.xml b/patterns-modules/intercepting-filter/pom.xml
index 8028454ee2..60246e7838 100644
--- a/patterns-modules/intercepting-filter/pom.xml
+++ b/patterns-modules/intercepting-filter/pom.xml
@@ -17,6 +17,7 @@
javax.servlet
javax.servlet-api
+ ${javax.servlet-api.version}
org.slf4j
@@ -30,6 +31,7 @@
org.apache.maven.plugins
maven-war-plugin
+ ${maven-war-plugin.version}
false
@@ -46,4 +48,8 @@
+
+ 3.3.2
+
+
\ No newline at end of file
diff --git a/patterns-modules/pom.xml b/patterns-modules/pom.xml
index 26d9a76aee..add2b0475b 100644
--- a/patterns-modules/pom.xml
+++ b/patterns-modules/pom.xml
@@ -31,44 +31,7 @@
clean-architecture
enterprise-patterns
coupling
+ idd
-
-
-
- org.junit.vintage
- junit-vintage-engine
- ${junit-jupiter.version}
- test
-
-
- javax.servlet
- javax.servlet-api
- ${javax.servlet-api.version}
- provided
-
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-war-plugin
- ${maven-war-plugin.version}
-
-
- org.eclipse.jetty
- jetty-maven-plugin
- ${jetty-maven-plugin.version}
-
-
-
-
-
-
- 9.4.0.v20161208
-
-
-
\ No newline at end of file
+
diff --git a/pdf-2/pom.xml b/pdf-2/pom.xml
index 653b55a206..ccbb5c9693 100644
--- a/pdf-2/pom.xml
+++ b/pdf-2/pom.xml
@@ -28,12 +28,12 @@
com.itextpdf
itextpdf
- 5.5.13.3
+ ${itextpdf.version}
org.apache.pdfbox
pdfbox
- 3.0.0-RC1
+ ${pdfbox.version}
@@ -48,8 +48,10 @@
+ 5.5.13.3
7.2.3
3.0.1
+ 3.0.0-RC1
\ No newline at end of file
diff --git a/pdf/pom.xml b/pdf/pom.xml
index 4bfc7cb621..cead1b2ded 100644
--- a/pdf/pom.xml
+++ b/pdf/pom.xml
@@ -106,7 +106,7 @@
2.0.25
2.0.1
- 5.5.10
+ 5.5.13.3
5.5.10
3.15
1.8
diff --git a/persistence-modules/activejdbc/pom.xml b/persistence-modules/activejdbc/pom.xml
index 5fdf27a679..a661fc3abb 100644
--- a/persistence-modules/activejdbc/pom.xml
+++ b/persistence-modules/activejdbc/pom.xml
@@ -74,9 +74,9 @@
- 2.0
+ 3.4-j11
development.test,development
- 5.1.34
+ 8.0.32
\ No newline at end of file
diff --git a/persistence-modules/activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java b/persistence-modules/activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java
index 8906d3e759..ea600b9721 100644
--- a/persistence-modules/activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java
+++ b/persistence-modules/activejdbc/src/main/java/com/baeldung/ActiveJDBCApp.java
@@ -4,6 +4,7 @@ package com.baeldung;
import com.baeldung.model.Employee;
import com.baeldung.model.Role;
import org.javalite.activejdbc.Base;
+import org.javalite.activejdbc.DB;
import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.Model;
@@ -11,8 +12,7 @@ public class ActiveJDBCApp
{
public static void main( String[] args )
{
- try {
- Base.open();
+ try(final DB open = Base.open()) {
ActiveJDBCApp app = new ActiveJDBCApp();
app.create();
app.update();
diff --git a/persistence-modules/core-java-persistence/pom.xml b/persistence-modules/core-java-persistence/pom.xml
index 5cc1df483f..e8add07fbf 100644
--- a/persistence-modules/core-java-persistence/pom.xml
+++ b/persistence-modules/core-java-persistence/pom.xml
@@ -52,14 +52,21 @@
spring-boot-starter
${springframework.boot.spring-boot-starter.version}
+
+ mysql
+ mysql-connector-java
+ ${mysql-connector.version}
+ runtime
+
- 2.4.0
- 3.2.0
- 0.9.5.2
- 1.5.8.RELEASE
- 4.3.4.RELEASE
+ 2.9.0
+ 5.0.1
+ 0.9.5.5
+ 3.0.4
+ 6.0.6
+ 8.0.32
\ No newline at end of file
diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/DatabaseConfig.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/DatabaseConfig.java
index 8ad689041e..44cfc75a2b 100644
--- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/DatabaseConfig.java
+++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/DatabaseConfig.java
@@ -1,13 +1,14 @@
package com.baeldung.jdbcmetadata;
-import org.apache.log4j.Logger;
-
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
public class DatabaseConfig {
- private static final Logger LOG = Logger.getLogger(DatabaseConfig.class);
+ private static final Logger LOG = LoggerFactory.getLogger(DatabaseConfig.class);
private Connection connection;
@@ -17,7 +18,7 @@ public class DatabaseConfig {
String url = "jdbc:h2:mem:testdb";
connection = DriverManager.getConnection(url, "sa", "");
} catch (ClassNotFoundException | SQLException e) {
- LOG.error(e);
+ LOG.error(e.getMessage());
}
}
@@ -35,7 +36,7 @@ public class DatabaseConfig {
connection.createStatement().executeUpdate("create table CUSTOMER (ID int primary key auto_increment, NAME VARCHAR(45))");
connection.createStatement().executeUpdate("create table CUST_ADDRESS (ID VARCHAR(36), CUST_ID int, ADDRESS VARCHAR(45), FOREIGN KEY (CUST_ID) REFERENCES CUSTOMER(ID))");
} catch (SQLException e) {
- LOG.error(e);
+ LOG.error(e.getMessage());
}
}
@@ -43,7 +44,7 @@ public class DatabaseConfig {
try {
connection.createStatement().executeUpdate("CREATE VIEW CUSTOMER_VIEW AS SELECT * FROM CUSTOMER");
} catch (SQLException e) {
- LOG.error(e);
+ LOG.error(e.getMessage());
}
}
}
diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/JdbcMetadataApplication.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/JdbcMetadataApplication.java
index 591a14f3b5..f85f227381 100644
--- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/JdbcMetadataApplication.java
+++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcmetadata/JdbcMetadataApplication.java
@@ -1,12 +1,13 @@
package com.baeldung.jdbcmetadata;
-import org.apache.log4j.Logger;
-
import java.sql.SQLException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
public class JdbcMetadataApplication {
- private static final Logger LOG = Logger.getLogger(JdbcMetadataApplication.class);
+ private static final Logger LOG = LoggerFactory.getLogger(JdbcMetadataApplication.class);
public static void main(String[] args) {
DatabaseConfig databaseConfig = new DatabaseConfig();
diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java
index 9cfcff468e..a53c82d3da 100644
--- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java
+++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/DatabaseConfiguration.java
@@ -5,10 +5,6 @@ import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
-import javax.sql.rowset.JdbcRowSet;
-import javax.sql.rowset.RowSetFactory;
-import javax.sql.rowset.RowSetProvider;
-
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
diff --git a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java
index 72c462ac42..163b3a3b58 100644
--- a/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java
+++ b/persistence-modules/core-java-persistence/src/main/java/com/baeldung/jdbcrowset/JdbcRowsetApplication.java
@@ -7,8 +7,6 @@ import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
-import com.sun.rowset.*;
-
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.FilteredRowSet;
import javax.sql.rowset.JdbcRowSet;
@@ -25,7 +23,7 @@ public class JdbcRowsetApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(JdbcRowsetApplication.class, args);
- Statement stmt = null;
+ Statement stmt;
try {
Connection conn = DatabaseConfiguration.geth2Connection();
@@ -41,8 +39,7 @@ public class JdbcRowsetApplication {
DatabaseConfiguration.initDatabase(stmt);
// JdbcRowSet Example
String sql = "SELECT * FROM customers";
- JdbcRowSet jdbcRS;
- jdbcRS = new JdbcRowSetImpl(conn);
+ JdbcRowSet jdbcRS = RowSetProvider.newFactory().createJdbcRowSet();
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
jdbcRS.setCommand(sql);
jdbcRS.execute();
@@ -58,7 +55,8 @@ public class JdbcRowsetApplication {
String username = "sa";
String password = "";
String url = "jdbc:h2:mem:testdb";
- CachedRowSet crs = new CachedRowSetImpl();
+ RowSetFactory aFactory = RowSetProvider.newFactory();
+ CachedRowSet crs = aFactory.createCachedRowSet();
crs.setUsername(username);
crs.setPassword(password);
crs.setUrl(url);
@@ -74,7 +72,7 @@ public class JdbcRowsetApplication {
}
// WebRowSet example
- WebRowSet wrs = new WebRowSetImpl();
+ WebRowSet wrs = RowSetProvider.newFactory().createWebRowSet();
wrs.setUsername(username);
wrs.setPassword(password);
wrs.setUrl(url);
@@ -84,14 +82,14 @@ public class JdbcRowsetApplication {
wrs.writeXml(ostream);
// JoinRowSet example
- CachedRowSetImpl customers = new CachedRowSetImpl();
+ CachedRowSet customers = aFactory.createCachedRowSet();
customers.setUsername(username);
customers.setPassword(password);
customers.setUrl(url);
customers.setCommand(sql);
customers.execute();
- CachedRowSetImpl associates = new CachedRowSetImpl();
+ CachedRowSet associates = aFactory.createCachedRowSet();
associates.setUsername(username);
associates.setPassword(password);
associates.setUrl(url);
@@ -99,7 +97,7 @@ public class JdbcRowsetApplication {
associates.setCommand(associatesSQL);
associates.execute();
- JoinRowSet jrs = new JoinRowSetImpl();
+ JoinRowSet jrs = RowSetProvider.newFactory().createJoinRowSet();
final String ID = "id";
final String NAME = "name";
jrs.addRowSet(customers, ID);
diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java
index ebfb4df102..2b2b35c423 100644
--- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java
+++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/jdbcrowset/JdbcRowSetLiveTest.java
@@ -19,11 +19,6 @@ import javax.sql.rowset.WebRowSet;
import org.junit.Before;
import org.junit.Test;
-import com.sun.rowset.CachedRowSetImpl;
-import com.sun.rowset.JdbcRowSetImpl;
-import com.sun.rowset.JoinRowSetImpl;
-import com.sun.rowset.WebRowSetImpl;
-
public class JdbcRowSetLiveTest {
Statement stmt = null;
String username = "sa";
@@ -51,9 +46,10 @@ public class JdbcRowSetLiveTest {
public void createJdbcRowSet_SelectCustomers_ThenCorrect() throws Exception {
String sql = "SELECT * FROM customers";
- JdbcRowSet jdbcRS;
- Connection conn = DatabaseConfiguration.geth2Connection();
- jdbcRS = new JdbcRowSetImpl(conn);
+ JdbcRowSet jdbcRS = RowSetProvider.newFactory().createJdbcRowSet();
+ jdbcRS.setUrl("jdbc:h2:mem:testdb");
+ jdbcRS.setUsername("sa");
+ jdbcRS.setPassword("");
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
jdbcRS.setCommand(sql);
jdbcRS.execute();
@@ -71,7 +67,7 @@ public class JdbcRowSetLiveTest {
@Test
public void createCachedRowSet_DeleteRecord_ThenCorrect() throws Exception {
- CachedRowSet crs = new CachedRowSetImpl();
+ CachedRowSet crs = RowSetProvider.newFactory().createCachedRowSet();
crs.setUsername(username);
crs.setPassword(password);
crs.setUrl(url);
@@ -91,7 +87,7 @@ public class JdbcRowSetLiveTest {
@Test
public void createWebRowSet_SelectCustomers_WritetoXML_ThenCorrect() throws SQLException, IOException {
- WebRowSet wrs = new WebRowSetImpl();
+ WebRowSet wrs = RowSetProvider.newFactory().createWebRowSet();
wrs.setUsername(username);
wrs.setPassword(password);
wrs.setUrl(url);
@@ -105,14 +101,14 @@ public class JdbcRowSetLiveTest {
@Test
public void createCachedRowSets_DoJoinRowSet_ThenCorrect() throws Exception {
- CachedRowSetImpl customers = new CachedRowSetImpl();
+ CachedRowSet customers = RowSetProvider.newFactory().createCachedRowSet();
customers.setUsername(username);
customers.setPassword(password);
customers.setUrl(url);
customers.setCommand(sql);
customers.execute();
- CachedRowSetImpl associates = new CachedRowSetImpl();
+ CachedRowSet associates = RowSetProvider.newFactory().createCachedRowSet();
associates.setUsername(username);
associates.setPassword(password);
associates.setUrl(url);
@@ -120,7 +116,7 @@ public class JdbcRowSetLiveTest {
associates.setCommand(associatesSQL);
associates.execute();
- JoinRowSet jrs = new JoinRowSetImpl();
+ JoinRowSet jrs = RowSetProvider.newFactory().createJoinRowSet();
final String ID = "id";
final String NAME = "name";
jrs.addRowSet(customers, ID);
diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java
index c13f94f12a..fe00ca28dc 100644
--- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java
+++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/JdbcLiveTest.java
@@ -1,9 +1,10 @@
package com.baeldung.spring.jdbc;
-import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.sql.CallableStatement;
import java.sql.Connection;
@@ -24,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class JdbcLiveTest {
- private static final Logger LOG = Logger.getLogger(JdbcLiveTest.class);
+ private static final Logger LOG = LoggerFactory.getLogger(JdbcLiveTest.class);
private Connection con;
diff --git a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java
index 853e78a68d..c77e314141 100644
--- a/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java
+++ b/persistence-modules/core-java-persistence/src/test/java/com/baeldung/spring/jdbc/ResultSetLiveTest.java
@@ -13,7 +13,6 @@ import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
-import org.apache.log4j.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
@@ -25,8 +24,6 @@ import junit.framework.Assert;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ResultSetLiveTest {
- private static final Logger logger = Logger.getLogger(ResultSetLiveTest.class);
-
private final Employee expectedEmployee1 = new Employee(1, "John", 1000.0, "Developer");
private final Employee updatedEmployee1 = new Employee(1, "John", 1100.0, "Developer");
diff --git a/persistence-modules/hbase/pom.xml b/persistence-modules/hbase/pom.xml
index e38b73e137..3e6cfe27be 100644
--- a/persistence-modules/hbase/pom.xml
+++ b/persistence-modules/hbase/pom.xml
@@ -33,7 +33,7 @@
- 1.3.1
+ 2.5.3
\ No newline at end of file
diff --git a/persistence-modules/hbase/src/main/java/com/baeldung/hbase/HbaseClientExample.java b/persistence-modules/hbase/src/main/java/com/baeldung/hbase/HbaseClientExample.java
index 5546f15e36..3a137a6019 100644
--- a/persistence-modules/hbase/src/main/java/com/baeldung/hbase/HbaseClientExample.java
+++ b/persistence-modules/hbase/src/main/java/com/baeldung/hbase/HbaseClientExample.java
@@ -1,7 +1,5 @@
package com.baeldung.hbase;
-
-import com.google.protobuf.ServiceException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
@@ -13,11 +11,11 @@ import java.io.IOException;
//install hbase locally & hbase master start
public class HbaseClientExample {
- public static void main(String[] args) throws IOException, ServiceException {
+ public static void main(String[] args) throws IOException {
new HbaseClientExample().connect();
}
- private void connect() throws IOException, ServiceException {
+ private void connect() throws IOException {
Configuration config = HBaseConfiguration.create();
String path = this.getClass().getClassLoader().getResource("hbase-site.xml").getPath();
@@ -25,7 +23,7 @@ public class HbaseClientExample {
config.addResource(new Path(path));
try {
- HBaseAdmin.checkHBaseAvailable(config);
+ HBaseAdmin.available(config);
} catch (MasterNotRunningException e) {
System.out.println("HBase is not running." + e.getMessage());
return;
diff --git a/persistence-modules/hibernate-annotations/README.md b/persistence-modules/hibernate-annotations/README.md
index 9b68579151..a03fb7e8e3 100644
--- a/persistence-modules/hibernate-annotations/README.md
+++ b/persistence-modules/hibernate-annotations/README.md
@@ -10,3 +10,4 @@ This module contains articles about Annotations used in Hibernate.
- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable)
- [Usage of the Hibernate @LazyCollection Annotation](https://www.baeldung.com/hibernate-lazycollection)
- [@Immutable in Hibernate](https://www.baeldung.com/hibernate-immutable)
+- [Hibernate @CreationTimestamp and @UpdateTimestamp](https://www.baeldung.com/hibernate-creationtimestamp-updatetimestamp)
diff --git a/persistence-modules/hibernate-annotations/pom.xml b/persistence-modules/hibernate-annotations/pom.xml
index 310b409a00..6417421fed 100644
--- a/persistence-modules/hibernate-annotations/pom.xml
+++ b/persistence-modules/hibernate-annotations/pom.xml
@@ -76,13 +76,18 @@
${org.springframework.version}
test
+
+ io.hypersistence
+ hypersistence-utils-hibernate-60
+ 3.3.1
+
- 5.0.2.RELEASE
- 1.10.6.RELEASE
- 5.6.7.Final
+ 6.0.6
+ 3.0.3
+ 6.1.7.Final
true
9.0.0.M26
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/creationupdatetimestamp/model/Book.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/creationupdatetimestamp/model/Book.java
new file mode 100644
index 0000000000..0484c31ced
--- /dev/null
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/creationupdatetimestamp/model/Book.java
@@ -0,0 +1,57 @@
+package com.baeldung.hibernate.creationupdatetimestamp.model;
+
+import java.time.Instant;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+
+import org.hibernate.annotations.CreationTimestamp;
+import org.hibernate.annotations.UpdateTimestamp;
+
+@Entity
+public class Book {
+ @Id
+ @GeneratedValue
+ private Long id;
+ private String title;
+ @CreationTimestamp
+ private Instant createdOn;
+ @UpdateTimestamp
+ private Instant lastUpdatedOn;
+
+ public Book() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public Instant getCreatedOn() {
+ return createdOn;
+ }
+
+ public void setCreatedOn(Instant createdOn) {
+ this.createdOn = createdOn;
+ }
+
+ public Instant getLastUpdatedOn() {
+ return lastUpdatedOn;
+ }
+
+ public void setLastUpdatedOn(Instant lastUpdatedOn) {
+ this.lastUpdatedOn = lastUpdatedOn;
+ }
+}
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java
index c10c67df9a..f50d8fd7cc 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/AddressType.java
@@ -1,11 +1,11 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
+import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
-import org.hibernate.type.IntegerType;
-import org.hibernate.type.StringType;
-import org.hibernate.type.Type;
+import org.hibernate.metamodel.spi.ValueAccess;
import org.hibernate.usertype.CompositeUserType;
+import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
@@ -14,74 +14,51 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.Objects;
-public class AddressType implements CompositeUserType {
+public class AddressType implements CompositeUserType, UserType {
@Override
- public String[] getPropertyNames() {
- return new String[]{"addressLine1", "addressLine2",
- "city", "country", "zipcode"};
- }
-
- @Override
- public Type[] getPropertyTypes() {
- return new Type[]{StringType.INSTANCE, StringType.INSTANCE,
- StringType.INSTANCE, StringType.INSTANCE, IntegerType.INSTANCE};
- }
-
- @Override
- public Object getPropertyValue(Object component, int property) throws HibernateException {
-
- Address empAdd = (Address) component;
+ public Object getPropertyValue(Address component, int property) throws HibernateException {
switch (property) {
case 0:
- return empAdd.getAddressLine1();
+ return component.getAddressLine1();
case 1:
- return empAdd.getAddressLine2();
+ return component.getAddressLine2();
case 2:
- return empAdd.getCity();
+ return component.getCity();
case 3:
- return empAdd.getCountry();
+ return component.getCountry();
case 4:
- return Integer.valueOf(empAdd.getZipCode());
+ return component.getZipCode();
+ default:
+ throw new IllegalArgumentException(property +
+ " is an invalid property index for class type " +
+ component.getClass().getName());
}
-
- throw new IllegalArgumentException(property +
- " is an invalid property index for class type " +
- component.getClass().getName());
}
@Override
- public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
-
- Address empAdd = (Address) component;
-
- switch (property) {
- case 0:
- empAdd.setAddressLine1((String) value);
- case 1:
- empAdd.setAddressLine2((String) value);
- case 2:
- empAdd.setCity((String) value);
- case 3:
- empAdd.setCountry((String) value);
- case 4:
- empAdd.setZipCode((Integer) value);
- }
-
- throw new IllegalArgumentException(property +
- " is an invalid property index for class type " +
- component.getClass().getName());
-
+ public Address instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) {
+ return null;
}
@Override
- public Class returnedClass() {
+ public Class> embeddable() {
return Address.class;
}
@Override
- public boolean equals(Object x, Object y) throws HibernateException {
+ public int getSqlType() {
+ return Types.VARCHAR;
+ }
+
+ @Override
+ public Class returnedClass() {
+ return Address.class;
+ }
+
+ @Override
+ public boolean equals(Address x, Address y) {
if (x == y)
return true;
@@ -92,57 +69,52 @@ public class AddressType implements CompositeUserType {
}
@Override
- public int hashCode(Object x) throws HibernateException {
+ public int hashCode(Address x) {
return x.hashCode();
}
@Override
- public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
-
+ public Address nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Address empAdd = new Address();
- empAdd.setAddressLine1(rs.getString(names[0]));
+ empAdd.setAddressLine1(rs.getString(position));
if (rs.wasNull())
return null;
- empAdd.setAddressLine2(rs.getString(names[1]));
- empAdd.setCity(rs.getString(names[2]));
- empAdd.setCountry(rs.getString(names[3]));
- empAdd.setZipCode(rs.getInt(names[4]));
+ empAdd.setAddressLine2(rs.getString(position));
+ empAdd.setCity(rs.getString(position));
+ empAdd.setCountry(rs.getString(position));
+ empAdd.setZipCode(rs.getInt(position));
return empAdd;
}
@Override
- public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
-
+ public void nullSafeSet(PreparedStatement st, Address value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.VARCHAR);
else {
- Address empAdd = (Address) value;
- st.setString(index, empAdd.getAddressLine1());
- st.setString(index + 1, empAdd.getAddressLine2());
- st.setString(index + 2, empAdd.getCity());
- st.setString(index + 3, empAdd.getCountry());
- st.setInt(index + 4, empAdd.getZipCode());
+ st.setString(index, value.getAddressLine1());
+ st.setString(index + 1, value.getAddressLine2());
+ st.setString(index + 2, value.getCity());
+ st.setString(index + 3, value.getCountry());
+ st.setInt(index + 4, value.getZipCode());
}
}
@Override
- public Object deepCopy(Object value) throws HibernateException {
-
+ public Address deepCopy(Address value) {
if (Objects.isNull(value))
return null;
- Address oldEmpAdd = (Address) value;
Address newEmpAdd = new Address();
- newEmpAdd.setAddressLine1(oldEmpAdd.getAddressLine1());
- newEmpAdd.setAddressLine2(oldEmpAdd.getAddressLine2());
- newEmpAdd.setCity(oldEmpAdd.getCity());
- newEmpAdd.setCountry(oldEmpAdd.getCountry());
- newEmpAdd.setZipCode(oldEmpAdd.getZipCode());
+ newEmpAdd.setAddressLine1(value.getAddressLine1());
+ newEmpAdd.setAddressLine2(value.getAddressLine2());
+ newEmpAdd.setCity(value.getCity());
+ newEmpAdd.setCountry(value.getCountry());
+ newEmpAdd.setZipCode(value.getZipCode());
return newEmpAdd;
}
@@ -153,17 +125,27 @@ public class AddressType implements CompositeUserType {
}
@Override
- public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
+ public Serializable disassemble(Address value) {
return (Serializable) deepCopy(value);
}
@Override
- public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
- return deepCopy(cached);
+ public Address assemble(Serializable cached, Object owner) {
+ return deepCopy((Address) cached);
}
@Override
- public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
- return original;
+ public Address replace(Address detached, Address managed, Object owner) {
+ return detached;
+ }
+
+ @Override
+ public boolean isInstance(Object object, SessionFactoryImplementor sessionFactory) {
+ return CompositeUserType.super.isInstance(object, sessionFactory);
+ }
+
+ @Override
+ public boolean isSameClass(Object object, SessionFactoryImplementor sessionFactory) {
+ return CompositeUserType.super.isSameClass(object, sessionFactory);
}
}
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java
index 56be9e693f..8f1794b979 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java
@@ -1,14 +1,14 @@
package com.baeldung.hibernate.customtypes;
-import org.hibernate.type.LocalDateType;
import org.hibernate.type.descriptor.WrapperOptions;
-import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan;
-import org.hibernate.type.descriptor.java.MutabilityPlan;
import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
-public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor {
+import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayTypeDescriptor;
+
+public class LocalDateStringJavaDescriptor extends AbstractArrayTypeDescriptor {
public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor();
@@ -18,12 +18,12 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor implements DiscriminatorType {
+public class LocalDateStringType extends AbstractSingleColumnStandardBasicType {
public static final LocalDateStringType INSTANCE = new LocalDateStringType();
public LocalDateStringType() {
- super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
+ super(VarcharJdbcType.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
}
@Override
@@ -21,14 +19,12 @@ public class LocalDateStringType extends AbstractSingleColumnStandardBasicType {
-public class PhoneNumberType implements UserType {
@Override
- public int[] sqlTypes() {
- return new int[]{Types.INTEGER, Types.INTEGER, Types.INTEGER};
+ public int getSqlType() {
+ return Types.INTEGER;
}
@Override
@@ -24,7 +23,7 @@ public class PhoneNumberType implements UserType {
}
@Override
- public boolean equals(Object x, Object y) throws HibernateException {
+ public boolean equals(PhoneNumber x, PhoneNumber y) {
if (x == y)
return true;
if (Objects.isNull(x) || Objects.isNull(y))
@@ -34,48 +33,42 @@ public class PhoneNumberType implements UserType {
}
@Override
- public int hashCode(Object x) throws HibernateException {
+ public int hashCode(PhoneNumber x) {
return x.hashCode();
}
@Override
- public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
- int countryCode = rs.getInt(names[0]);
+ public PhoneNumber nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
+ int countryCode = rs.getInt(position);
if (rs.wasNull())
return null;
- int cityCode = rs.getInt(names[1]);
- int number = rs.getInt(names[2]);
- PhoneNumber employeeNumber = new PhoneNumber(countryCode, cityCode, number);
+ int cityCode = rs.getInt(position);
+ int number = rs.getInt(position);
- return employeeNumber;
+ return new PhoneNumber(countryCode, cityCode, number);
}
@Override
- public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
-
+ public void nullSafeSet(PreparedStatement st, PhoneNumber value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value)) {
st.setNull(index, Types.INTEGER);
st.setNull(index+1, Types.INTEGER);
st.setNull(index+2, Types.INTEGER);
} else {
- PhoneNumber employeeNumber = (PhoneNumber) value;
- st.setInt(index,employeeNumber.getCountryCode());
- st.setInt(index+1,employeeNumber.getCityCode());
- st.setInt(index+2,employeeNumber.getNumber());
+ st.setInt(index, value.getCountryCode());
+ st.setInt(index+1, value.getCityCode());
+ st.setInt(index+2, value.getNumber());
}
}
@Override
- public Object deepCopy(Object value) throws HibernateException {
+ public PhoneNumber deepCopy(PhoneNumber value) {
if (Objects.isNull(value))
return null;
- PhoneNumber empNumber = (PhoneNumber) value;
- PhoneNumber newEmpNumber = new PhoneNumber(empNumber.getCountryCode(),empNumber.getCityCode(),empNumber.getNumber());
-
- return newEmpNumber;
+ return new PhoneNumber(value.getCountryCode(), value.getCityCode(), value.getNumber());
}
@Override
@@ -84,17 +77,17 @@ public class PhoneNumberType implements UserType {
}
@Override
- public Serializable disassemble(Object value) throws HibernateException {
+ public Serializable disassemble(PhoneNumber value) {
return (Serializable) value;
}
@Override
- public Object assemble(Serializable cached, Object owner) throws HibernateException {
- return cached;
+ public PhoneNumber assemble(Serializable cached, Object owner) {
+ return (PhoneNumber) cached;
}
@Override
- public Object replace(Object original, Object target, Object owner) throws HibernateException {
- return original;
+ public PhoneNumber replace(PhoneNumber detached, PhoneNumber managed, Object owner) {
+ return detached;
}
}
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java
index 266b85140b..69e34c1363 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/customtypes/SalaryType.java
@@ -1,12 +1,12 @@
package com.baeldung.hibernate.customtypes;
import org.hibernate.HibernateException;
+import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
-import org.hibernate.type.LongType;
-import org.hibernate.type.StringType;
-import org.hibernate.type.Type;
+import org.hibernate.metamodel.spi.ValueAccess;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.usertype.DynamicParameterizedType;
+import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.PreparedStatement;
@@ -16,65 +16,47 @@ import java.sql.Types;
import java.util.Objects;
import java.util.Properties;
-public class SalaryType implements CompositeUserType, DynamicParameterizedType {
+public class SalaryType implements UserType, CompositeUserType, DynamicParameterizedType {
private String localCurrency;
@Override
- public String[] getPropertyNames() {
- return new String[]{"amount", "currency"};
- }
-
- @Override
- public Type[] getPropertyTypes() {
- return new Type[]{LongType.INSTANCE, StringType.INSTANCE};
- }
-
- @Override
- public Object getPropertyValue(Object component, int property) throws HibernateException {
-
- Salary salary = (Salary) component;
+ public Object getPropertyValue(Salary component, int property) throws HibernateException {
switch (property) {
case 0:
- return salary.getAmount();
+ return component.getAmount();
case 1:
- return salary.getCurrency();
+ return component.getCurrency();
+ default:
+ throw new IllegalArgumentException(property +
+ " is an invalid property index for class type " +
+ component.getClass().getName());
}
-
- throw new IllegalArgumentException(property +
- " is an invalid property index for class type " +
- component.getClass().getName());
-
- }
-
-
- @Override
- public void setPropertyValue(Object component, int property, Object value) throws HibernateException {
-
- Salary salary = (Salary) component;
-
- switch (property) {
- case 0:
- salary.setAmount((Long) value);
- case 1:
- salary.setCurrency((String) value);
- }
-
- throw new IllegalArgumentException(property +
- " is an invalid property index for class type " +
- component.getClass().getName());
-
}
@Override
- public Class returnedClass() {
+ public Salary instantiate(ValueAccess values, SessionFactoryImplementor sessionFactory) {
+ return null;
+ }
+
+ @Override
+ public Class> embeddable() {
return Salary.class;
}
@Override
- public boolean equals(Object x, Object y) throws HibernateException {
+ public int getSqlType() {
+ return Types.BIGINT;
+ }
+ @Override
+ public Class returnedClass() {
+ return Salary.class;
+ }
+
+ @Override
+ public boolean equals(Salary x, Salary y) {
if (x == y)
return true;
@@ -82,54 +64,48 @@ public class SalaryType implements CompositeUserType, DynamicParameterizedType {
return false;
return x.equals(y);
-
}
@Override
- public int hashCode(Object x) throws HibernateException {
+ public int hashCode(Salary x) {
return x.hashCode();
}
@Override
- public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
-
+ public Salary nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
Salary salary = new Salary();
- salary.setAmount(rs.getLong(names[0]));
+ salary.setAmount(rs.getLong(position));
if (rs.wasNull())
return null;
- salary.setCurrency(rs.getString(names[1]));
+ salary.setCurrency(rs.getString(position));
return salary;
}
@Override
- public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
-
-
+ public void nullSafeSet(PreparedStatement st, Salary value, int index, SharedSessionContractImplementor session) throws SQLException {
if (Objects.isNull(value))
st.setNull(index, Types.BIGINT);
else {
- Salary salary = (Salary) value;
- st.setLong(index, SalaryCurrencyConvertor.convert(salary.getAmount(),
- salary.getCurrency(), localCurrency));
- st.setString(index + 1, salary.getCurrency());
+ st.setLong(index, SalaryCurrencyConvertor.convert(
+ value.getAmount(),
+ value.getCurrency(), localCurrency));
+ st.setString(index + 1, value.getCurrency());
}
}
@Override
- public Object deepCopy(Object value) throws HibernateException {
-
+ public Salary deepCopy(Salary value) {
if (Objects.isNull(value))
return null;
- Salary oldSal = (Salary) value;
Salary newSal = new Salary();
- newSal.setAmount(oldSal.getAmount());
- newSal.setCurrency(oldSal.getCurrency());
+ newSal.setAmount(value.getAmount());
+ newSal.setCurrency(value.getCurrency());
return newSal;
}
@@ -140,18 +116,18 @@ public class SalaryType implements CompositeUserType, DynamicParameterizedType {
}
@Override
- public Serializable disassemble(Object value, SharedSessionContractImplementor session) throws HibernateException {
+ public Serializable disassemble(Salary value) {
return (Serializable) deepCopy(value);
}
@Override
- public Object assemble(Serializable cached, SharedSessionContractImplementor session, Object owner) throws HibernateException {
- return deepCopy(cached);
+ public Salary assemble(Serializable cached, Object owner) {
+ return deepCopy((Salary) cached);
}
@Override
- public Object replace(Object original, Object target, SharedSessionContractImplementor session, Object owner) throws HibernateException {
- return original;
+ public Salary replace(Salary detached, Salary managed, Object owner) {
+ return detached;
}
@Override
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java
index ec88d629a6..f16aa68475 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/Event.java
@@ -4,7 +4,7 @@ import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Immutable;
-import javax.persistence.*;
+import jakarta.persistence.*;
import java.util.Set;
@Entity
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java
index 33af9313ae..6bf4006550 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/immutable/entities/EventGeneratedId.java
@@ -3,7 +3,7 @@ package com.baeldung.hibernate.immutable.entities;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Immutable;
-import javax.persistence.*;
+import jakarta.persistence.*;
@Entity
@Immutable
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java
index df07c3cf69..096faf7984 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Email.java
@@ -1,12 +1,12 @@
package com.baeldung.hibernate.joincolumn;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
+import jakarta.persistence.Entity;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
@Entity
public class Email {
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java
index 9940577761..3c6e5f4642 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/Office.java
@@ -1,13 +1,13 @@
package com.baeldung.hibernate.joincolumn;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinColumns;
-import javax.persistence.ManyToOne;
+import jakarta.persistence.Entity;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.JoinColumns;
+import jakarta.persistence.ManyToOne;
@Entity
public class Office {
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java
index cc723db6a2..d80a8be026 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficeAddress.java
@@ -1,10 +1,10 @@
package com.baeldung.hibernate.joincolumn;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
@Entity
public class OfficeAddress {
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java
index 49c63c7578..551b522700 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/joincolumn/OfficialEmployee.java
@@ -1,12 +1,12 @@
package com.baeldung.hibernate.joincolumn;
import java.util.List;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.OneToMany;
+import jakarta.persistence.Entity;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToMany;
@Entity
public class OfficialEmployee {
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Branch.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Branch.java
index de88647546..9957e2ce75 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Branch.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Branch.java
@@ -3,12 +3,12 @@ package com.baeldung.hibernate.lazycollection.model;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.OrderColumn;
-import javax.persistence.OneToMany;
-import javax.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OrderColumn;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Entity;
import java.util.ArrayList;
import java.util.List;
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Employee.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Employee.java
index 831518a365..edf89696f5 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Employee.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/lazycollection/model/Employee.java
@@ -1,11 +1,10 @@
package com.baeldung.hibernate.lazycollection.model;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.OrderColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Entity;
@Entity
public class Employee {
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java
index ef82c1c9ad..99410e1f76 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java
@@ -43,8 +43,8 @@ public class HibernateAnnotationUtil {
return metadata.buildSessionFactory();
}
- private static Map dbSettings() {
- Map dbSettings = new HashMap<>();
+ private static Map dbSettings() {
+ Map dbSettings = new HashMap<>();
dbSettings.put(Environment.URL, "jdbc:h2:mem:spring_hibernate_one_to_many");
dbSettings.put(Environment.USER, "sa");
dbSettings.put(Environment.PASS, "");
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java
index 53878af445..f07f3d3887 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java
@@ -2,13 +2,13 @@ package com.baeldung.hibernate.oneToMany.model;
import java.util.Set;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Table;
@Entity
@Table(name = "CART")
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java
index 27b28a6753..f279cc4ea6 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java
@@ -1,13 +1,13 @@
package com.baeldung.hibernate.oneToMany.model;
import java.util.Set;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Table;
@Entity
@Table(name = "CARTOIO")
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java
index a055682d0d..5babe9c545 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Item.java
@@ -1,13 +1,13 @@
package com.baeldung.hibernate.oneToMany.model;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "ITEMS")
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java
index baaf57b106..78139da19e 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemOIO.java
@@ -1,12 +1,12 @@
package com.baeldung.hibernate.oneToMany.model;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.Table;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "ITEMSOIO")
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java
index d923bda5de..e173aa8b47 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/pojo/Phone.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.pojo;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
import java.io.Serializable;
@Entity
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java
index 04684eceac..2b17c9218d 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java
@@ -3,10 +3,10 @@ package com.baeldung.hibernate.wherejointable;
import java.util.ArrayList;
import java.util.List;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.ManyToMany;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.ManyToMany;
@Entity(name = "e_group")
public class Group {
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java
index 3029aae640..a517de3cca 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java
@@ -3,12 +3,12 @@ package com.baeldung.hibernate.wherejointable;
import java.util.ArrayList;
import java.util.List;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.ManyToMany;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.JoinTable;
+import jakarta.persistence.ManyToMany;
import org.hibernate.annotations.WhereJoinTable;
diff --git a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java
index 00dd19699c..21a0a443c6 100644
--- a/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java
+++ b/persistence-modules/hibernate-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java
@@ -2,11 +2,11 @@ package com.baeldung.hibernate.wherejointable;
import java.io.Serializable;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.EnumType;
-import javax.persistence.Enumerated;
-import javax.persistence.Id;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EnumType;
+import jakarta.persistence.Enumerated;
+import jakarta.persistence.Id;
@Entity(name = "r_user_group")
public class UserGroupRelation implements Serializable {
diff --git a/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml
index 474eeb7a44..2915125295 100644
--- a/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml
+++ b/persistence-modules/hibernate-annotations/src/main/resources/META-INF/persistence.xml
@@ -7,12 +7,12 @@
Hibernate EntityManager Demo
true
-
+
-
-
-
-
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/creationupdatetimestamp/HibernateCreationUpdateTimestampIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/creationupdatetimestamp/HibernateCreationUpdateTimestampIntegrationTest.java
new file mode 100644
index 0000000000..bab51dab72
--- /dev/null
+++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/creationupdatetimestamp/HibernateCreationUpdateTimestampIntegrationTest.java
@@ -0,0 +1,118 @@
+package com.baeldung.hibernate.creationupdatetimestamp;
+
+import static org.hibernate.FlushMode.MANUAL;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+import java.time.Instant;
+
+import org.h2.Driver;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.dialect.H2Dialect;
+import org.hibernate.service.ServiceRegistry;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import com.baeldung.hibernate.creationupdatetimestamp.model.Book;
+
+class HibernateCreationUpdateTimestampIntegrationTest {
+
+ private static SessionFactory sessionFactory;
+
+ private Session session;
+
+ @BeforeAll
+ public static void beforeTests() {
+ Configuration configuration = new Configuration().addAnnotatedClass(Book.class)
+ .setProperty("hibernate.dialect", H2Dialect.class.getName())
+ .setProperty("hibernate.connection.driver_class", Driver.class.getName())
+ .setProperty("hibernate.connection.url", "jdbc:h2:mem:test")
+ .setProperty("hibernate.connection.username", "sa")
+ .setProperty("hibernate.connection.password", "")
+ .setProperty("hibernate.hbm2ddl.auto", "update");
+
+ ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
+ .build();
+
+ sessionFactory = configuration.buildSessionFactory(serviceRegistry);
+ }
+
+ @Test
+ void whenCreatingEntity_ThenCreatedOnIsSet() {
+ session = sessionFactory.openSession();
+ session.beginTransaction();
+ Book book = new Book();
+
+ session.save(book);
+ session.getTransaction()
+ .commit();
+ session.close();
+
+ assertNotNull(book.getCreatedOn());
+ }
+
+ @Test
+ void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreBothSet() {
+ session = sessionFactory.openSession();
+ session.beginTransaction();
+ Book book = new Book();
+
+ session.save(book);
+ session.getTransaction()
+ .commit();
+ session.close();
+
+ assertNotNull(book.getCreatedOn());
+ assertNotNull(book.getLastUpdatedOn());
+ }
+
+ @Test
+ void whenCreatingEntity_ThenCreatedOnAndLastUpdatedOnAreEqual() {
+ session = sessionFactory.openSession();
+ session.beginTransaction();
+ Book book = new Book();
+
+ session.save(book);
+ session.getTransaction().commit();
+ session.close();
+
+ assertEquals(book.getCreatedOn(), book.getLastUpdatedOn());
+ }
+
+ @Test
+ void whenUpdatingEntity_ThenLastUpdatedOnIsUpdatedAndCreatedOnStaysTheSame() {
+ session = sessionFactory.openSession();
+ session.setHibernateFlushMode(MANUAL);
+ session.beginTransaction();
+ Book book = new Book();
+ session.save(book);
+ session.flush();
+ Instant createdOnAfterCreation = book.getCreatedOn();
+ Instant lastUpdatedOnAfterCreation = book.getLastUpdatedOn();
+
+ String newName = "newName";
+ book.setTitle(newName);
+ session.save(book);
+ session.flush();
+ session.getTransaction().commit();
+ session.close();
+ Instant createdOnAfterUpdate = book.getCreatedOn();
+ Instant lastUpdatedOnAfterUpdate = book.getLastUpdatedOn();
+
+ assertEquals(newName, book.getTitle());
+ assertNotNull(createdOnAfterUpdate);
+ assertNotNull(lastUpdatedOnAfterUpdate);
+ assertEquals(createdOnAfterCreation, createdOnAfterUpdate);
+ assertNotEquals(lastUpdatedOnAfterCreation, lastUpdatedOnAfterUpdate);
+ }
+
+ @AfterAll
+ static void afterTests() {
+ sessionFactory.close();
+ }
+}
diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java
index 460b65ee12..9da3a90034 100644
--- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java
+++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/customtypes/HibernateCustomTypesIntegrationTest.java
@@ -6,10 +6,9 @@ import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;
-import org.junit.Assert;
import org.junit.Test;
-import javax.persistence.TypedQuery;
+import jakarta.persistence.TypedQuery;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
@@ -76,7 +75,7 @@ public class HibernateCustomTypesIntegrationTest {
doInHibernate(this::sessionFactory, session -> {
session.save(e);
- TypedQuery query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipcode = :pinCode", OfficeEmployee.class);
+ TypedQuery query = session.createQuery("FROM OfficeEmployee OE WHERE OE.empAddress.zipCode = :pinCode", OfficeEmployee.class);
query.setParameter("pinCode",100);
int size = query.getResultList().size();
@@ -100,8 +99,8 @@ public class HibernateCustomTypesIntegrationTest {
return metadata.buildSessionFactory();
}
- private static Map getProperties() {
- Map dbSettings = new HashMap<>();
+ private static Map getProperties() {
+ Map dbSettings = new HashMap<>();
dbSettings.put(Environment.URL, "jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1");
dbSettings.put(Environment.USER, "sa");
dbSettings.put(Environment.PASS, "");
diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java
index 270a235ef0..f038d2b16d 100644
--- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java
+++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/immutable/HibernateImmutableIntegrationTest.java
@@ -8,7 +8,7 @@ import org.hibernate.Session;
import org.junit.*;
import org.junit.rules.ExpectedException;
-import javax.persistence.PersistenceException;
+import jakarta.persistence.PersistenceException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
diff --git a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java
index 37125e8b15..04f0613811 100644
--- a/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java
+++ b/persistence-modules/hibernate-annotations/src/test/java/com/baeldung/hibernate/joincolumn/JoinColumnIntegrationTest.java
@@ -78,8 +78,8 @@ public class JoinColumnIntegrationTest {
return metadata.buildSessionFactory();
}
- private static Map getProperties() {
- Map dbSettings = new HashMap<>();
+ private static Map getProperties() {
+ Map dbSettings = new HashMap<>();
dbSettings.put(Environment.URL, "jdbc:h2:mem:mydbJoinColumn;DB_CLOSE_DELAY=-1");
dbSettings.put(Environment.USER, "sa");
dbSettings.put(Environment.PASS, "");
diff --git a/persistence-modules/hibernate-enterprise/pom.xml b/persistence-modules/hibernate-enterprise/pom.xml
index 833f19c673..eaa7b0e765 100644
--- a/persistence-modules/hibernate-enterprise/pom.xml
+++ b/persistence-modules/hibernate-enterprise/pom.xml
@@ -78,10 +78,11 @@
- 5.3.7.Final
- 6.0.6
- 2.2.3
+ 6.1.7.Final
+ 8.0.32
+ 2.6.0
0.9
+ 1.14.2
\ No newline at end of file
diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java
index 989fa1281a..8ef7487804 100644
--- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java
+++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/EntityWithNoId.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.exception;
-import javax.persistence.Entity;
+import jakarta.persistence.Entity;
@Entity
public class EntityWithNoId {
diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java
index 0724ced56b..b7e80511e6 100644
--- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java
+++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/Product.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.exception;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
@Entity
@Table(name = "PRODUCT")
diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductEntity.java
index b9c5f5010d..a2dcec61e9 100644
--- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductEntity.java
+++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductEntity.java
@@ -1,8 +1,8 @@
package com.baeldung.hibernate.exception;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
@Entity
@Table(name = "PRODUCT")
diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductNotMapped.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductNotMapped.java
new file mode 100644
index 0000000000..827ad15e5b
--- /dev/null
+++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/exception/ProductNotMapped.java
@@ -0,0 +1,32 @@
+package com.baeldung.hibernate.exception;
+
+public class ProductNotMapped {
+
+ private int id;
+ private String name;
+ private String description;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+}
diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java
index 9dcf4058a7..bc50c11d81 100644
--- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java
+++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/logging/Employee.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.logging;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
@Entity
public class Employee {
diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java
index 736abde866..23b9a87eef 100644
--- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java
+++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PointEntity.java
@@ -1,11 +1,11 @@
package com.baeldung.hibernate.pojo;
-import com.vividsolutions.jts.geom.Point;
+import org.locationtech.jts.geom.Point;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
@Entity
public class PointEntity {
diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java
index 69208c8cd4..32cb146f23 100644
--- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java
+++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/PolygonEntity.java
@@ -1,10 +1,10 @@
package com.baeldung.hibernate.pojo;
-import com.vividsolutions.jts.geom.Polygon;
+import org.locationtech.jts.geom.Polygon;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
@Entity
public class PolygonEntity {
diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java
index 9b26c117eb..263908a5fc 100644
--- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java
+++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/hibernate/pojo/Student.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.pojo;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
@Entity
public class Student {
diff --git a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java
index 6a95a7acf5..3766639975 100644
--- a/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java
+++ b/persistence-modules/hibernate-enterprise/src/main/java/com/baeldung/persistence/model/Person.java
@@ -1,8 +1,8 @@
package com.baeldung.persistence.model;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
@Entity
public class Person {
diff --git a/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml
index 474eeb7a44..2915125295 100644
--- a/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml
+++ b/persistence-modules/hibernate-enterprise/src/main/resources/META-INF/persistence.xml
@@ -7,12 +7,12 @@
Hibernate EntityManager Demo
true
-
+
-
-
-
-
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java
index 74f752ab8c..e0f13582ab 100644
--- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java
+++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/HibernateSpatialIntegrationTest.java
@@ -9,23 +9,23 @@ import java.io.IOException;
import java.net.URL;
import java.util.Properties;
-import javax.persistence.Query;
+import jakarta.persistence.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.locationtech.jts.geom.Coordinate;
+import org.locationtech.jts.io.ParseException;
+import org.locationtech.jts.io.WKTReader;
+import org.locationtech.jts.geom.Geometry;
+import org.locationtech.jts.geom.Point;
+import org.locationtech.jts.geom.Polygon;
+import org.locationtech.jts.util.GeometricShapeFactory;
import com.baeldung.hibernate.pojo.PointEntity;
import com.baeldung.hibernate.pojo.PolygonEntity;
-import com.vividsolutions.jts.geom.Coordinate;
-import com.vividsolutions.jts.geom.Geometry;
-import com.vividsolutions.jts.geom.Point;
-import com.vividsolutions.jts.geom.Polygon;
-import com.vividsolutions.jts.io.ParseException;
-import com.vividsolutions.jts.io.WKTReader;
-import com.vividsolutions.jts.util.GeometricShapeFactory;
import geodb.GeoDB;
@@ -39,7 +39,7 @@ public class HibernateSpatialIntegrationTest {
session = HibernateUtil.getSessionFactory("hibernate-spatial.properties")
.openSession();
transaction = session.beginTransaction();
- session.doWork(conn -> { GeoDB.InitGeoDB(conn); });
+ session.doWork(GeoDB::InitGeoDB);
}
@After
@@ -135,9 +135,7 @@ public class HibernateSpatialIntegrationTest {
private Geometry wktToGeometry(String wellKnownText) throws ParseException {
WKTReader fromText = new WKTReader();
- Geometry geom = null;
- geom = fromText.read(wellKnownText);
- return geom;
+ return fromText.read(wellKnownText);
}
private static Geometry createCircle(double x, double y, double radius) {
diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java
index 891352843d..37c21d1899 100644
--- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java
+++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/exception/HibernateExceptionUnitTest.java
@@ -6,28 +6,25 @@ import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.util.List;
-import javax.persistence.OptimisticLockException;
-import javax.persistence.PersistenceException;
+import jakarta.persistence.OptimisticLockException;
+import jakarta.persistence.PersistenceException;
-import org.hibernate.AnnotationException;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.PropertyValueException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
-import org.hibernate.StaleObjectStateException;
import org.hibernate.StaleStateException;
import org.hibernate.Transaction;
-import org.hibernate.TransactionException;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.cfg.Configuration;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.DataException;
import org.hibernate.exception.SQLGrammarException;
-import org.hibernate.hql.internal.ast.QuerySyntaxException;
import org.hibernate.id.IdentifierGenerationException;
import org.hibernate.query.NativeQuery;
+import org.hibernate.query.sqm.UnknownEntityException;
import org.hibernate.tool.schema.spi.CommandAcceptanceException;
import org.hibernate.tool.schema.spi.SchemaManagementException;
import org.junit.Before;
@@ -63,12 +60,15 @@ public class HibernateExceptionUnitTest {
@Test
public void whenQueryExecutedWithUnmappedEntity_thenMappingException() {
- thrown.expectCause(isA(MappingException.class));
- thrown.expectMessage("Unknown entity: java.lang.String");
+ thrown.expect(isA(MappingException.class));
+ thrown.expectMessage("Unable to locate persister: com.baeldung.hibernate.exception.ProductNotMapped");
+
+ ProductNotMapped product = new ProductNotMapped();
+ product.setId(1);
+ product.setName("test");
Session session = sessionFactory.openSession();
- NativeQuery query = session.createNativeQuery("select name from PRODUCT", String.class);
- query.getResultList();
+ session.save(product);
}
@Test
@@ -82,8 +82,8 @@ public class HibernateExceptionUnitTest {
@Test
public void whenQueryExecutedWithInvalidClassName_thenQuerySyntaxException() {
- thrown.expectCause(isA(QuerySyntaxException.class));
- thrown.expectMessage("PRODUCT is not mapped [from PRODUCT]");
+ thrown.expectCause(isA(UnknownEntityException.class));
+ thrown.expectMessage("Could not resolve root entity 'PRODUCT");
Session session = sessionFactory.openSession();
List results = session.createQuery("from PRODUCT", Product.class)
@@ -92,8 +92,8 @@ public class HibernateExceptionUnitTest {
@Test
public void givenEntityWithoutId_whenSessionFactoryCreated_thenAnnotationException() {
- thrown.expect(AnnotationException.class);
- thrown.expectMessage("No identifier specified for entity");
+ thrown.expect(isA(HibernateException.class));
+ thrown.expectMessage("Entity 'com.baeldung.hibernate.exception.EntityWithNoId' has no identifier (every '@Entity' class must declare or inherit at least one '@Id' or '@EmbeddedId' property)");
Configuration cfg = getConfiguration();
cfg.addAnnotatedClass(EntityWithNoId.class);
@@ -132,9 +132,8 @@ public class HibernateExceptionUnitTest {
@Test
public void givenMissingTable_whenEntitySaved_thenSQLGrammarException() {
- thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(SQLGrammarException.class));
- thrown.expectMessage("SQLGrammarException: could not prepare statement");
+ thrown.expectMessage("could not prepare statement");
Configuration cfg = getConfiguration();
cfg.addAnnotatedClass(Product.class);
@@ -162,9 +161,8 @@ public class HibernateExceptionUnitTest {
@Test
public void givenMissingTable_whenQueryExecuted_thenSQLGrammarException() {
- thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(SQLGrammarException.class));
- thrown.expectMessage("SQLGrammarException: could not prepare statement");
+ thrown.expectMessage("could not prepare statement");
Session session = sessionFactory.openSession();
NativeQuery query = session.createNativeQuery("select * from NON_EXISTING_TABLE", Product.class);
@@ -173,9 +171,8 @@ public class HibernateExceptionUnitTest {
@Test
public void whenDuplicateIdSaved_thenConstraintViolationException() {
- thrown.expect(isA(PersistenceException.class));
thrown.expectCause(isA(ConstraintViolationException.class));
- thrown.expectMessage("ConstraintViolationException: could not execute statement");
+ thrown.expectMessage("could not execute statement");
Session session = null;
Transaction transaction = null;
@@ -253,7 +250,7 @@ public class HibernateExceptionUnitTest {
@Test
public void givenQueryWithDataTypeMismatch_WhenQueryExecuted_thenDataException() {
thrown.expectCause(isA(DataException.class));
- thrown.expectMessage("org.hibernate.exception.DataException: could not prepare statement");
+ thrown.expectMessage("could not prepare statement");
Session session = sessionFactory.openSession();
NativeQuery query = session.createNativeQuery("select * from PRODUCT where id='wrongTypeId'", Product.class);
@@ -330,9 +327,8 @@ public class HibernateExceptionUnitTest {
@Test
public void whenUpdatingNonExistingObject_thenStaleStateException() {
- thrown.expect(isA(OptimisticLockException.class));
- thrown.expectMessage("Row was updated or deleted by another transaction");
- thrown.expectCause(isA(StaleObjectStateException.class));
+ thrown.expectCause(isA(StaleStateException.class));
+ thrown.expectMessage("Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; statement executed: update PRODUCT set description=?, name=? where id=?");
Session session = null;
Transaction transaction = null;
@@ -356,7 +352,8 @@ public class HibernateExceptionUnitTest {
@Test
public void givenTxnMarkedRollbackOnly_whenCommitted_thenTransactionException() {
- thrown.expect(isA(TransactionException.class));
+ thrown.expect(isA(IllegalStateException.class));
+ thrown.expectMessage("Transaction already active");
Session session = null;
Transaction transaction = null;
@@ -368,6 +365,7 @@ public class HibernateExceptionUnitTest {
product1.setId(15);
product1.setName("Product1");
session.save(product1);
+ transaction = session.beginTransaction();
transaction.setRollbackOnly();
transaction.commit();
diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java
index 1b6cee7e67..3e4895e5e6 100644
--- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java
+++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/Car.java
@@ -2,9 +2,9 @@ package com.baeldung.hibernate.multitenancy;
import java.io.Serializable;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
@Entity(name = "Car")
@Table(name = "Car")
diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java
index fdc3f9fa81..2dc94172b1 100644
--- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java
+++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/MultitenancyIntegrationTest.java
@@ -79,9 +79,9 @@ public abstract class MultitenancyIntegrationTest {
private void createCarTable() {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
- session.createSQLQuery("drop table Car if exists")
+ session.createNativeQuery("drop table Car if exists")
.executeUpdate();
- session.createSQLQuery("create table Car (brand varchar(255) primary key)")
+ session.createNativeQuery("create table Car (brand varchar(255) primary key)")
.executeUpdate();
tx.commit();
}
diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java
index 92f477a646..904805f2ce 100644
--- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java
+++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/DatabaseApproachMultitenancyIntegrationTest.java
@@ -1,7 +1,5 @@
package com.baeldung.hibernate.multitenancy.database;
-import java.io.IOException;
-
import org.junit.Test;
import com.baeldung.hibernate.multitenancy.MultitenancyIntegrationTest;
@@ -14,7 +12,7 @@ public class DatabaseApproachMultitenancyIntegrationTest extends MultitenancyInt
}
@Test
- public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() throws IOException {
+ public void givenDatabaseApproach_whenAddingEntries_thenOnlyAddedToConcreteDatabase() {
whenCurrentTenantIs(TenantIdNames.MYDB1);
whenAddCar("myCar");
thenCarFound("myCar");
diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java
index eb1f410622..47abf6ff85 100644
--- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java
+++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/database/MapMultiTenantConnectionProvider.java
@@ -34,8 +34,13 @@ public class MapMultiTenantConnectionProvider extends AbstractMultiTenantConnect
private void initConnectionProviderForTenant(String tenantId) throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream(String.format("/hibernate-database-%s.properties", tenantId)));
+ Map configProperties = new HashMap<>();
+ for (String key : properties.stringPropertyNames()) {
+ String value = properties.getProperty(key);
+ configProperties.put(key, value);
+ }
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
- connectionProvider.configure(properties);
+ connectionProvider.configure(configProperties);
this.connectionProviderMap.put(tenantId, connectionProvider);
}
diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java
index 601eba651c..67b838fdf1 100644
--- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java
+++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/hibernate/multitenancy/schema/SchemaMultiTenantConnectionProvider.java
@@ -3,6 +3,8 @@ package com.baeldung.hibernate.multitenancy.schema;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Map;
import java.util.Properties;
import org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
@@ -39,9 +41,14 @@ public class SchemaMultiTenantConnectionProvider extends AbstractMultiTenantConn
private ConnectionProvider initConnectionProvider() throws IOException {
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("/hibernate-schema-multitenancy.properties"));
+ Map configProperties = new HashMap<>();
+ for (String key : properties.stringPropertyNames()) {
+ String value = properties.getProperty(key);
+ configProperties.put(key, value);
+ }
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
- connectionProvider.configure(properties);
+ connectionProvider.configure(configProperties);
return connectionProvider;
}
diff --git a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java
index 8c571428b4..c3d2362339 100644
--- a/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java
+++ b/persistence-modules/hibernate-enterprise/src/test/java/com/baeldung/persistence/save/SaveMethodsIntegrationTest.java
@@ -7,7 +7,7 @@ import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
-import javax.persistence.PersistenceException;
+import jakarta.persistence.PersistenceException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties
index e08a23166d..1e086f60d4 100644
--- a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties
+++ b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-exception.properties
@@ -12,5 +12,3 @@ hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.acquire_increment=5
hibernate.c3p0.timeout=1800
-
-hibernate.transaction.factory_class=org.hibernate.transaction.JTATransactionFactory
diff --git a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties
index c16666cbf5..e156965ce7 100644
--- a/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties
+++ b/persistence-modules/hibernate-enterprise/src/test/resources/hibernate-spatial.properties
@@ -4,7 +4,7 @@ hibernate.connection.username=sa
hibernate.connection.autocommit=true
jdbc.password=
-hibernate.dialect=org.hibernate.spatial.dialect.h2geodb.GeoDBDialect
+hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
diff --git a/persistence-modules/hibernate-exceptions/pom.xml b/persistence-modules/hibernate-exceptions/pom.xml
index 4bef688715..670ff4cdb8 100644
--- a/persistence-modules/hibernate-exceptions/pom.xml
+++ b/persistence-modules/hibernate-exceptions/pom.xml
@@ -24,11 +24,6 @@
hibernate-core
${hibernate.version}
-
- javax.xml.bind
- jaxb-api
- ${jaxb.version}
-
com.h2database
h2
@@ -37,8 +32,7 @@
- 2.4.0
- 2.3.0
+ 2.7.1
2.1.214
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Category.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Category.java
index 25d31d50c7..cab06ae9cf 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Category.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Category.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.entitynotfoundexception;
-import javax.persistence.*;
+import jakarta.persistence.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Item.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Item.java
index 3abed00eb8..2d07178aaf 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Item.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/Item.java
@@ -1,9 +1,6 @@
package com.baeldung.hibernate.entitynotfoundexception;
-import org.hibernate.annotations.NotFound;
-import org.hibernate.annotations.NotFoundAction;
-
-import javax.persistence.*;
+import jakarta.persistence.*;
import java.io.Serializable;
@Entity
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/User.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/User.java
index d89047195c..8351c5df96 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/User.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/entitynotfoundexception/User.java
@@ -1,7 +1,7 @@
package com.baeldung.hibernate.entitynotfoundexception;
-import javax.persistence.Entity;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
@Entity
public class User {
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Comment.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Comment.java
index 4a3e9739e2..e73adfef6b 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Comment.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Comment.java
@@ -1,10 +1,10 @@
package com.baeldung.hibernate.exception.detachedentity.entity;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.ManyToOne;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.ManyToOne;
@Entity
public class Comment {
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Post.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Post.java
index 7d95b41948..155a1bfe69 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Post.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Post.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.exception.detachedentity.entity;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
@Entity
public class Post {
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/Role.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/Role.java
index c15e674c52..5e613004a3 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/Role.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/Role.java
@@ -1,11 +1,11 @@
package com.baeldung.hibernate.exception.lazyinitialization.entity;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
@Entity
@Table(name = "role")
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/User.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/User.java
index 5bd7e00801..ffae05c0a0 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/User.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/lazyinitialization/entity/User.java
@@ -3,14 +3,14 @@ package com.baeldung.hibernate.exception.lazyinitialization.entity;
import java.util.HashSet;
import java.util.Set;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Table;
@Entity
@Table(name = "user")
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java
index 3c9c7c5b31..eb697334ae 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Article.java
@@ -1,10 +1,10 @@
package com.baeldung.hibernate.exception.persistentobject.entity;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.ManyToOne;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.ManyToOne;
@Entity
public class Article {
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java
index fa6aaa9abe..f8dcb82b7e 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Author.java
@@ -2,12 +2,11 @@ package com.baeldung.hibernate.exception.persistentobject.entity;
import java.util.List;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.OneToMany;
-import javax.persistence.OneToOne;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToMany;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java
index 342da27c77..986c7f061f 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/persistentobject/entity/Book.java
@@ -1,11 +1,10 @@
package com.baeldung.hibernate.exception.persistentobject.entity;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
@Entity
public class Book {
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Address.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Address.java
index e450fc3c18..8d1208e036 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Address.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Address.java
@@ -1,18 +1,12 @@
package com.baeldung.hibernate.exception.transientobject.entity;
-import java.io.Serializable;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.OneToMany;
-import javax.persistence.OneToOne;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "address")
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Author.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Author.java
index f1a88daa36..271e810002 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Author.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Author.java
@@ -3,15 +3,14 @@ package com.baeldung.hibernate.exception.transientobject.entity;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToMany;
-import javax.persistence.ManyToOne;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToMany;
+import jakarta.persistence.Table;
import java.util.HashSet;
import java.util.Set;
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Book.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Book.java
index 91728430ea..0734cccff1 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Book.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Book.java
@@ -4,15 +4,14 @@ package com.baeldung.hibernate.exception.transientobject.entity;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToMany;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToMany;
+import jakarta.persistence.Table;
import java.util.HashSet;
import java.util.Set;
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Department.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Department.java
index 4b8fa69964..5bd9a109ab 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Department.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Department.java
@@ -1,13 +1,13 @@
package com.baeldung.hibernate.exception.transientobject.entity;
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Table;
import java.util.HashSet;
import java.util.Set;
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Employee.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Employee.java
index 56443cce70..6a2ec8b938 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Employee.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/Employee.java
@@ -4,15 +4,14 @@ package com.baeldung.hibernate.exception.transientobject.entity;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "employee")
diff --git a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/User.java b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/User.java
index eff1a88b51..cf56afd8b9 100644
--- a/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/User.java
+++ b/persistence-modules/hibernate-exceptions/src/main/java/com/baeldung/hibernate/exception/transientobject/entity/User.java
@@ -1,19 +1,14 @@
package com.baeldung.hibernate.exception.transientobject.entity;
-import java.io.Serializable;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.OneToMany;
-import javax.persistence.OneToOne;
-import javax.persistence.Table;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.OneToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "user")
diff --git a/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java
index bcb4e3eb95..f339afd536 100644
--- a/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java
+++ b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/entitynotfoundexception/EntityNotFoundExceptionIntegrationTest.java
@@ -4,10 +4,10 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.EntityNotFoundException;
-import javax.persistence.Persistence;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
+import jakarta.persistence.EntityNotFoundException;
+import jakarta.persistence.Persistence;
import java.io.IOException;
public class EntityNotFoundExceptionIntegrationTest {
diff --git a/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/detachedentity/DetachedEntityUnitTest.java b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/detachedentity/DetachedEntityUnitTest.java
index afb0efae77..cb4313c537 100644
--- a/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/detachedentity/DetachedEntityUnitTest.java
+++ b/persistence-modules/hibernate-exceptions/src/test/java/com/baeldung/hibernate/exception/detachedentity/DetachedEntityUnitTest.java
@@ -3,13 +3,12 @@ package com.baeldung.hibernate.exception.detachedentity;
import com.baeldung.hibernate.exception.detachedentity.entity.Comment;
import com.baeldung.hibernate.exception.detachedentity.entity.Post;
-import org.assertj.core.api.Assertions;
import org.hibernate.Session;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import javax.persistence.PersistenceException;
+import jakarta.persistence.PersistenceException;
import java.util.List;
@@ -43,7 +42,7 @@ public class DetachedEntityUnitTest {
assertThatThrownBy(() -> session.persist(detachedPost))
.isInstanceOf(PersistenceException.class)
- .hasMessageContaining("org.hibernate.PersistentObjectException: detached entity passed to persist");
+ .hasMessageContaining("detached entity passed to persist: com.baeldung.hibernate.exception.detachedentity.entity.Post");
}
@Test
@@ -72,13 +71,13 @@ public class DetachedEntityUnitTest {
assertThatThrownBy(() -> session.persist(detachedPost))
.isInstanceOf(PersistenceException.class)
- .hasMessageContaining("org.hibernate.PersistentObjectException: detached entity passed to persist");
+ .hasMessageContaining("detached entity passed to persist: com.baeldung.hibernate.exception.detachedentity.entity.Post");
}
@Test
public void givenDetachedPost_whenMergeAndPersistComment_thenNoExceptionIsThrown() {
Comment comment = new Comment("nice article!");
- Post mergedPost = (Post) session.merge(detachedPost);
+ Post mergedPost = session.merge(detachedPost);
comment.setPost(mergedPost);
session.persist(comment);
diff --git a/persistence-modules/hibernate-jpa/pom.xml b/persistence-modules/hibernate-jpa/pom.xml
index f742290884..5a99c1c4d0 100644
--- a/persistence-modules/hibernate-jpa/pom.xml
+++ b/persistence-modules/hibernate-jpa/pom.xml
@@ -83,11 +83,12 @@
- 5.3.7.Final
- 8.0.13
- 2.2.3
- 2.1.7.RELEASE
- 1.4.200
+ 8.0.32
+ 2.6.0
+ 3.0.4
+ 2.1.214
+ 2.0.7
+ 1.4.6
-
\ No newline at end of file
+
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java
index 506e674984..ec0e2f2e2c 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/converters/PersonNameConverter.java
@@ -1,7 +1,7 @@
package com.baeldung.hibernate.converters;
-import javax.persistence.AttributeConverter;
-import javax.persistence.Converter;
+import jakarta.persistence.AttributeConverter;
+import jakarta.persistence.Converter;
import com.baeldung.hibernate.pojo.PersonName;
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java
index ff94f4f849..39e69a2b1c 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/Department.java
@@ -2,7 +2,7 @@ package com.baeldung.hibernate.entities;
import java.util.List;
-import javax.persistence.*;
+import jakarta.persistence.*;
@Entity
public class Department {
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java
index 6510e70650..38519644c5 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java
@@ -1,13 +1,13 @@
package com.baeldung.hibernate.entities;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.ManyToOne;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.ManyToOne;
@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"),
- @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"),
+ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where employeeNumber = :employeeNumber"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) })
@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class),
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java
index 1de8de0327..5a6f9c7c6c 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Game.java
@@ -1,7 +1,7 @@
package com.baeldung.hibernate.entitymanager.getreference;
-import javax.persistence.Entity;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
@Entity
public class Game {
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java
index 459a3a00ad..6e62aeda45 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/entitymanager/getreference/Player.java
@@ -1,8 +1,8 @@
package com.baeldung.hibernate.entitymanager.getreference;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.ManyToOne;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.ManyToOne;
@Entity
public class Player {
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java
index b547a60b06..6263df4237 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/application/Application.java
@@ -2,7 +2,7 @@ package com.baeldung.hibernate.jpabootstrap.application;
import com.baeldung.hibernate.jpabootstrap.config.JpaEntityManagerFactory;
import com.baeldung.hibernate.jpabootstrap.entities.User;
-import javax.persistence.EntityManager;
+import jakarta.persistence.EntityManager;
public class Application {
@@ -24,8 +24,7 @@ public class Application {
}
private static class EntityManagerHolder {
- private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory(
- new Class[]{User.class}).getEntityManager();
+ private static final EntityManager ENTITY_MANAGER = new JpaEntityManagerFactory(new Class[]{User.class}).getEntityManager();
}
public static EntityManager getJpaEntityManager() {
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java
index 3852b44b64..af01ea630c 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/HibernatePersistenceUnitInfo.java
@@ -6,11 +6,11 @@ import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.sql.DataSource;
-import javax.persistence.SharedCacheMode;
-import javax.persistence.ValidationMode;
-import javax.persistence.spi.ClassTransformer;
-import javax.persistence.spi.PersistenceUnitInfo;
-import javax.persistence.spi.PersistenceUnitTransactionType;
+import jakarta.persistence.SharedCacheMode;
+import jakarta.persistence.ValidationMode;
+import jakarta.persistence.spi.ClassTransformer;
+import jakarta.persistence.spi.PersistenceUnitInfo;
+import jakarta.persistence.spi.PersistenceUnitTransactionType;
import org.hibernate.jpa.HibernatePersistenceProvider;
public class HibernatePersistenceUnitInfo implements PersistenceUnitInfo {
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java
index bc1932af6f..e115727d67 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/config/JpaEntityManagerFactory.java
@@ -7,10 +7,10 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
-import javax.persistence.EntityManager;
+import jakarta.persistence.EntityManager;
import javax.sql.DataSource;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.spi.PersistenceUnitInfo;
+import jakarta.persistence.EntityManagerFactory;
+import jakarta.persistence.spi.PersistenceUnitInfo;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java
index 86ca1dfa19..43c99f8d96 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpabootstrap/entities/User.java
@@ -1,10 +1,10 @@
package com.baeldung.hibernate.jpabootstrap.entities;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
@Entity
@Table(name = "users")
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java
index e79168a451..9a3216b5eb 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/jpacriteriabuilder/service/EmployeeSearchServiceImpl.java
@@ -2,13 +2,13 @@ package com.baeldung.hibernate.jpacriteriabuilder.service;
import java.util.List;
-import javax.persistence.EntityManager;
-import javax.persistence.TypedQuery;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaBuilder.In;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.Root;
-import javax.persistence.criteria.Subquery;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.TypedQuery;
+import jakarta.persistence.criteria.CriteriaBuilder;
+import jakarta.persistence.criteria.CriteriaBuilder.In;
+import jakarta.persistence.criteria.CriteriaQuery;
+import jakarta.persistence.criteria.Root;
+import jakarta.persistence.criteria.Subquery;
import com.baeldung.hibernate.entities.Department;
import com.baeldung.hibernate.entities.DeptEmployee;
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java
index e05eb46030..0c3238cf98 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/Address.java
@@ -1,12 +1,12 @@
package com.baeldung.hibernate.onetoone.foreignkeybased;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.OneToOne;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "address")
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java
index dda972f29c..14c2a0a28c 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/foreignkeybased/User.java
@@ -1,14 +1,14 @@
package com.baeldung.hibernate.onetoone.foreignkeybased;
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.OneToOne;
-import javax.persistence.Table;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.OneToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "users")
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java
index a0bc101b9f..fc8b9eefec 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/Employee.java
@@ -1,15 +1,15 @@
package com.baeldung.hibernate.onetoone.jointablebased;
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.OneToOne;
-import javax.persistence.Table;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.JoinTable;
+import jakarta.persistence.OneToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "employee")
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java
index f530611f6e..0834b9f9d7 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/jointablebased/WorkStation.java
@@ -1,13 +1,13 @@
package com.baeldung.hibernate.onetoone.jointablebased;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.OneToOne;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "workstation")
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java
index e70c62e77b..d738b900bc 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/Address.java
@@ -1,12 +1,12 @@
package com.baeldung.hibernate.onetoone.sharedkeybased;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.MapsId;
-import javax.persistence.OneToOne;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.MapsId;
+import jakarta.persistence.OneToOne;
+import jakarta.persistence.Table;
@Entity
@Table(name = "address")
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java
index 605671a149..8ce767eaf7 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/onetoone/sharedkeybased/User.java
@@ -1,15 +1,15 @@
package com.baeldung.hibernate.onetoone.sharedkeybased;
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.OneToOne;
-import javax.persistence.PrimaryKeyJoinColumn;
-import javax.persistence.Table;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToOne;
+import jakarta.persistence.PrimaryKeyJoinColumn;
+import jakarta.persistence.Table;
@Entity
@Table(name = "users")
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java
index 1af3e3e21b..b8212a049d 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingCourse.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.optimisticlocking;
-import javax.persistence.*;
+import jakarta.persistence.*;
@Entity
public class OptimisticLockingCourse {
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java
index b79212ae8d..22f11e37fb 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingStudent.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.optimisticlocking;
-import javax.persistence.*;
+import jakarta.persistence.*;
import java.util.List;
@Entity
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java
index c889cb6127..7c6d20df40 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Address.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.pessimisticlocking;
-import javax.persistence.Embeddable;
+import jakarta.persistence.Embeddable;
@Embeddable
public class Address {
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java
index cb73cbc958..9f36e3b308 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Customer.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.pessimisticlocking;
-import javax.persistence.*;
+import jakarta.persistence.*;
import java.util.List;
@Entity
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java
index e491c09eb5..b954c9fdb2 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/Individual.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.pessimisticlocking;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Inheritance;
-import javax.persistence.InheritanceType;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Inheritance;
+import jakarta.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java
index aea7d5fc87..012f3d1d39 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingCourse.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.pessimisticlocking;
-import javax.persistence.*;
+import jakarta.persistence.*;
@Entity
public class PessimisticLockingCourse {
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java
index a1328cbdad..e5b00f3800 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingEmployee.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.pessimisticlocking;
-import javax.persistence.Entity;
+import jakarta.persistence.Entity;
import java.math.BigDecimal;
@Entity
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java
index e6c5f476b4..c5634ebc24 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockingStudent.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.pessimisticlocking;
-import javax.persistence.*;
+import jakarta.persistence.*;
import java.util.List;
@Entity
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java
index 5fae7f6a97..7aeadd4501 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Movie.java
@@ -1,8 +1,8 @@
package com.baeldung.hibernate.pojo;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
@Entity
@Table(name = "MOVIE")
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java
index 390a5954ed..d0c8b8aa2f 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Person.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.pojo;
-import javax.persistence.Convert;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
+import jakarta.persistence.Convert;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
import com.baeldung.hibernate.converters.PersonNameConverter;
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java
index 25e51e35d0..66a68367d7 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Post.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.pojo;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
@Entity
@Table(name = "posts")
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java
index 9b26c117eb..263908a5fc 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/pojo/Student.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.pojo;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
@Entity
public class Student {
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Account.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Account.java
index b051809ee5..7070f21c45 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Account.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Account.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.serializable;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
@Entity
public class Account {
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Email.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Email.java
index 11e7c6f159..4ba902281a 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Email.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/Email.java
@@ -1,7 +1,7 @@
package com.baeldung.hibernate.serializable;
-import javax.persistence.Entity;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
import java.io.Serializable;
@Entity
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/User.java
index e7820fe52f..267155b4db 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/User.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/User.java
@@ -1,7 +1,7 @@
package com.baeldung.hibernate.serializable;
-import javax.persistence.EmbeddedId;
-import javax.persistence.Entity;
+import jakarta.persistence.EmbeddedId;
+import jakarta.persistence.Entity;
@Entity
public class User {
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/UserId.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/UserId.java
index 7d3d382f67..6fcbeafdd0 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/UserId.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/hibernate/serializable/UserId.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.serializable;
-import javax.persistence.Embeddable;
+import jakarta.persistence.Embeddable;
import java.io.Serializable;
@Embeddable
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java
index 7252ac46f5..afdbf067c3 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/entity/User.java
@@ -1,9 +1,9 @@
package com.baeldung.persistencecontext.entity;
-import javax.persistence.Entity;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
-@Entity
+@Entity(name = "users")
public class User {
@Id
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java
index ef25aac69f..7ad6aae745 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/ExtendedPersistenceContextUserService.java
@@ -1,15 +1,15 @@
package com.baeldung.persistencecontext.service;
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.persistence.PersistenceContextType;
-import javax.transaction.Transactional;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.PersistenceContext;
+import jakarta.persistence.PersistenceContextType;
+import jakarta.transaction.Transactional;
-import org.springframework.stereotype.Component;
+import org.springframework.stereotype.Service;
import com.baeldung.persistencecontext.entity.User;
-@Component
+@Service
public class ExtendedPersistenceContextUserService {
@PersistenceContext(type = PersistenceContextType.EXTENDED)
diff --git a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java
index 481defcf08..6b9fd1f14c 100644
--- a/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java
+++ b/persistence-modules/hibernate-jpa/src/main/java/com/baeldung/persistencecontext/service/TransctionPersistenceContextUserService.java
@@ -1,20 +1,20 @@
package com.baeldung.persistencecontext.service;
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.transaction.Transactional;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.PersistenceContext;
+import jakarta.transaction.Transactional;
-import org.springframework.stereotype.Component;
+import org.springframework.stereotype.Service;
import com.baeldung.persistencecontext.entity.User;
-@Component
+@Service
public class TransctionPersistenceContextUserService {
@PersistenceContext
private EntityManager entityManager;
-
+
@Transactional
public User insertWithTransaction(User user) {
entityManager.persist(user);
diff --git a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml
index 12b41a4973..1669413289 100644
--- a/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml
+++ b/persistence-modules/hibernate-jpa/src/main/resources/META-INF/persistence.xml
@@ -8,12 +8,13 @@
com.baeldung.hibernate.pojo.Movie
true
-
+
-
-
-
-
+
+
+
+
+
@@ -34,10 +35,14 @@
-
-
-
-
+
+
+
+
+
+
+
+
@@ -57,16 +62,20 @@
-
-
-
-
-
+
+
+
+
+
-
-
-
-
+
+
+
+
+
+
+
+
@@ -87,16 +96,20 @@
-
-
-
-
-
+
+
+
+
+
-
-
-
-
+
+
+
+
+
+
+
+
@@ -113,10 +126,16 @@
-
-
-
-
+
+
+
+
+
+
+
+
+
+
diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java
index e8e6aeed7c..86f059c6d7 100644
--- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java
+++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceH2IntegrationTest.java
@@ -5,9 +5,9 @@ import ch.qos.logback.classic.Logger;
import org.junit.jupiter.api.*;
import org.slf4j.LoggerFactory;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Persistence;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
+import jakarta.persistence.Persistence;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
@@ -87,8 +87,8 @@ public class GetReferenceH2IntegrationTest {
});
StringBuilder expected = new StringBuilder();
- expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n");
- expected.append("Hibernate: update Game set name=? where id=?\n");
+ expected.append("Hibernate: select g1_0.id,g1_0.name from Game g1_0 where g1_0.id=?" + System.lineSeparator());
+ expected.append("Hibernate: update Game set name=? where id=?" + System.lineSeparator());
assertEquals(expected.toString(), output.toString());
}
@@ -104,8 +104,8 @@ public class GetReferenceH2IntegrationTest {
});
StringBuilder expected = new StringBuilder();
- expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n");
- expected.append("Hibernate: update Game set name=? where id=?\n");
+ expected.append("Hibernate: select g1_0.id,g1_0.name from Game g1_0 where g1_0.id=?" + System.lineSeparator());
+ expected.append("Hibernate: update Game set name=? where id=?" + System.lineSeparator());
assertEquals(expected.toString(), output.toString());
}
@@ -120,10 +120,9 @@ public class GetReferenceH2IntegrationTest {
StringBuilder expected = new StringBuilder();
expected.append("Hibernate: select ");
- expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, ");
- expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ ");
- expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n");
- expected.append("Hibernate: delete from Player where id=?\n");
+ expected.append("p1_0.id,g1_0.id,g1_0.name,p1_0.name ");
+ expected.append("from Player p1_0 left join Game g1_0 on g1_0.id=p1_0.game_id where p1_0.id=?" + System.lineSeparator());
+ expected.append("Hibernate: delete from Player where id=?" + System.lineSeparator());
assertEquals(expected.toString(), output.toString());
}
@@ -137,11 +136,7 @@ public class GetReferenceH2IntegrationTest {
});
StringBuilder expected = new StringBuilder();
- expected.append("Hibernate: select ");
- expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, ");
- expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ ");
- expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n");
- expected.append("Hibernate: delete from Player where id=?\n");
+ expected.append("Hibernate: delete from Player where id=?" + System.lineSeparator());
assertEquals(expected.toString(), output.toString());
}
@@ -159,12 +154,11 @@ public class GetReferenceH2IntegrationTest {
}));
StringBuilder expected = new StringBuilder();
- expected.append("Hibernate: select game0_.id as id1_0_0_, game0_.name as name2_0_0_ from Game game0_ where game0_.id=?\n");
+ expected.append("Hibernate: select g1_0.id,g1_0.name from Game g1_0 where g1_0.id=?" + System.lineSeparator());
expected.append("Hibernate: select ");
- expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, ");
- expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ ");
- expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n");
- expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n");
+ expected.append("p1_0.id,g1_0.id,g1_0.name,p1_0.name ");
+ expected.append("from Player p1_0 left join Game g1_0 on g1_0.id=p1_0.game_id where p1_0.id=?" + System.lineSeparator());
+ expected.append("Hibernate: update Player set game_id=?,name=? where id=?" + System.lineSeparator());
assertEquals(expected.toString(), output.toString());
}
@@ -183,10 +177,9 @@ public class GetReferenceH2IntegrationTest {
StringBuilder expected = new StringBuilder();
expected.append("Hibernate: select ");
- expected.append("player0_.id as id1_1_0_, player0_.game_id as game_id3_1_0_, ");
- expected.append("player0_.name as name2_1_0_, game1_.id as id1_0_1_, game1_.name as name2_0_1_ ");
- expected.append("from Player player0_ left outer join Game game1_ on player0_.game_id=game1_.id where player0_.id=?\n");
- expected.append("Hibernate: update Player set game_id=?, name=? where id=?\n");
+ expected.append("p1_0.id,g1_0.id,g1_0.name,p1_0.name ");
+ expected.append("from Player p1_0 left join Game g1_0 on g1_0.id=p1_0.game_id where p1_0.id=?" + System.lineSeparator());
+ expected.append("Hibernate: update Player set game_id=?,name=? where id=?" + System.lineSeparator());
assertEquals(expected.toString(), output.toString());
}
diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java
index 2b7c5e8119..29be19dd68 100644
--- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java
+++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferenceMySQLManualTest.java
@@ -5,9 +5,9 @@ import ch.qos.logback.classic.Logger;
import org.junit.jupiter.api.*;
import org.slf4j.LoggerFactory;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Persistence;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
+import jakarta.persistence.Persistence;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java
index 17f6b10b8a..20a0bca6f1 100644
--- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java
+++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/entitymanager/getreference/GetReferencePostgreSQLManualTest.java
@@ -5,9 +5,9 @@ import ch.qos.logback.classic.Logger;
import org.junit.jupiter.api.*;
import org.slf4j.LoggerFactory;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Persistence;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
+import jakarta.persistence.Persistence;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java
index 2b12734a10..16d1057285 100644
--- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java
+++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/jpacriteriabuilder/EmployeeSearchServiceIntegrationTest.java
@@ -9,7 +9,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
-import javax.persistence.EntityManager;
+import jakarta.persistence.EntityManager;
import org.hibernate.HibernateException;
import org.hibernate.Session;
@@ -81,13 +81,10 @@ public class EmployeeSearchServiceIntegrationTest {
@Test
public final void givenCriteriaQuery_whenSearchedUsingCriteriaBuilderWithListofAuthors_thenResultIsFilteredByAuthorNames() {
- List titles = new ArrayList() {
- {
- add("Manager");
- add("Senior Manager");
- add("Director");
- }
- };
+ List titles = new ArrayList<>();
+ titles.add("Manager");
+ titles.add("Senior Manager");
+ titles.add("Director");
List result = searchService.filterbyTitleUsingCriteriaBuilder(titles);
assertEquals("Number of Employees does not match with expected.", 6, result.size());
assertThat(result.stream()
diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java
index 37c490f297..2fa302e270 100644
--- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java
+++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/optimisticlocking/OptimisticLockingIntegrationTest.java
@@ -3,9 +3,9 @@ package com.baeldung.hibernate.optimisticlocking;
import java.io.IOException;
import java.util.Arrays;
-import javax.persistence.EntityManager;
-import javax.persistence.LockModeType;
-import javax.persistence.OptimisticLockException;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.LockModeType;
+import jakarta.persistence.OptimisticLockException;
import org.hibernate.SessionFactory;
import org.junit.After;
diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java
index 4b9c7720fd..4085a98dad 100644
--- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java
+++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/BasicPessimisticLockingIntegrationTest.java
@@ -1,14 +1,14 @@
package com.baeldung.hibernate.pessimisticlocking;
import com.baeldung.hibernate.HibernateUtil;
-import com.vividsolutions.jts.util.Assert;
+import org.locationtech.jts.util.Assert;
import org.hibernate.SessionFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
-import javax.persistence.*;
+import jakarta.persistence.*;
import java.io.IOException;
import java.util.Arrays;
@@ -46,7 +46,7 @@ public class BasicPessimisticLockingIntegrationTest {
}
@Test
- public void givenRecordWithPessimisticReadQuery_whenQueryingNewOne_PessimisticLockExceptionThrown() throws IOException {
+ public void givenRecordWithPessimisticReadQuery_whenQueryingNewOne_PessimisticLockExceptionThrown() {
try {
EntityManager entityManager = getEntityManagerWithOpenTransaction();
Query query = entityManager.createQuery("from Student where studentId = :studentId");
diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java
index 81cb7d95f8..c2f2326159 100644
--- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java
+++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/pessimisticlocking/PessimisticLockScopesIntegrationTest.java
@@ -6,9 +6,9 @@ import org.hibernate.SessionFactory;
import org.junit.AfterClass;
import org.junit.Test;
-import javax.persistence.EntityManager;
-import javax.persistence.LockModeType;
-import javax.persistence.PessimisticLockScope;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.LockModeType;
+import jakarta.persistence.PessimisticLockScope;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
@@ -36,7 +36,7 @@ public class PessimisticLockScopesIntegrationTest {
// EXTENDED SCOPE
Map map = new HashMap<>();
- map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
+ map.put("jakarta.persistence", PessimisticLockScope.EXTENDED);
EntityManager em3 = getEntityManagerWithOpenTransaction();
foundEmployee = em3.find(PessimisticLockingEmployee.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
@@ -65,7 +65,7 @@ public class PessimisticLockScopesIntegrationTest {
// EXTENDED SCOPE
Map map = new HashMap<>();
- map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
+ map.put("jakarta.persistence", PessimisticLockScope.EXTENDED);
EntityManager em3 = getEntityManagerWithOpenTransaction();
foundCustomer = em3.find(Customer.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
@@ -96,7 +96,7 @@ public class PessimisticLockScopesIntegrationTest {
// EXTENDED SCOPE
Map map = new HashMap<>();
- map.put("javax.persistence.lock.scope", PessimisticLockScope.EXTENDED);
+ map.put("jakarta.persistence", PessimisticLockScope.EXTENDED);
EntityManager em3 = getEntityManagerWithOpenTransaction();
foundCourse = em3.find(PessimisticLockingCourse.class, 1L, LockModeType.PESSIMISTIC_WRITE, map);
diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/serializable/JPASerializableIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/serializable/JPASerializableIntegrationTest.java
index 696bc23ab0..5512757889 100644
--- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/serializable/JPASerializableIntegrationTest.java
+++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/serializable/JPASerializableIntegrationTest.java
@@ -4,10 +4,9 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import javax.persistence.EntityManager;
-import javax.persistence.EntityManagerFactory;
-import javax.persistence.Persistence;
-import java.io.IOException;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.EntityManagerFactory;
+import jakarta.persistence.Persistence;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -17,7 +16,7 @@ public class JPASerializableIntegrationTest {
private static EntityManager entityManager;
@Before
- public void setUp() throws IOException {
+ public void setUp() {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("com.baeldung.hibernate.serializable.h2_persistence_unit");
entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
@@ -63,7 +62,7 @@ public class JPASerializableIntegrationTest {
entityManager.persist(account);
entityManager.persist(account2);
- List userAccounts = entityManager.createQuery("select a from Account a join fetch a.user where a.user.email = :email")
+ List userAccounts = entityManager.createQuery("select a from Account a join fetch a.user where a.user.email = :email", Account.class)
.setParameter("email", email)
.getResultList();
assertEquals(2, userAccounts.size());
diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java
index 246a7d59f9..f64846ba59 100644
--- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java
+++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/hibernate/transaction/TransactionIntegrationTest.java
@@ -2,7 +2,6 @@ package com.baeldung.hibernate.transaction;
import com.baeldung.hibernate.HibernateUtil;
import com.baeldung.hibernate.pojo.Post;
-import com.baeldung.hibernate.transaction.PostService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.BeforeClass;
@@ -10,7 +9,6 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
diff --git a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java
index b299dd5834..37e6e438d8 100644
--- a/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java
+++ b/persistence-modules/hibernate-jpa/src/test/java/com/baeldung/persistencecontext/PersistenceContextIntegrationTest.java
@@ -4,8 +4,8 @@ import com.baeldung.persistencecontext.entity.User;
import com.baeldung.persistencecontext.service.ExtendedPersistenceContextUserService;
import com.baeldung.persistencecontext.service.TransctionPersistenceContextUserService;
-import javax.persistence.EntityExistsException;
-import javax.persistence.TransactionRequiredException;
+import jakarta.persistence.EntityExistsException;
+import jakarta.persistence.TransactionRequiredException;
import org.junit.Test;
import org.junit.runner.RunWith;
diff --git a/persistence-modules/hibernate-mapping-2/README.md b/persistence-modules/hibernate-mapping-2/README.md
index 7a811e17cf..36c9f8c304 100644
--- a/persistence-modules/hibernate-mapping-2/README.md
+++ b/persistence-modules/hibernate-mapping-2/README.md
@@ -4,4 +4,6 @@ This module contains articles about Hibernate Mappings.
### Relevant articles
-- [Hibernate Many to Many Annotation Tutorial](https://www.baeldung.com/hibernate-many-to-many)
\ No newline at end of file
+- [Hibernate Many to Many Annotation Tutorial](https://www.baeldung.com/hibernate-many-to-many)
+- [Boolean Converters in Hibernate 6](https://www.baeldung.com/java-hibernate-6-boolean-converters)
+- [Generate UUIDs as Primary Keys With Hibernate](https://www.baeldung.com/java-hibernate-uuid-primary-key)
diff --git a/persistence-modules/hibernate-mapping-2/pom.xml b/persistence-modules/hibernate-mapping-2/pom.xml
index 2a787a0e46..1b9a3e45d3 100644
--- a/persistence-modules/hibernate-mapping-2/pom.xml
+++ b/persistence-modules/hibernate-mapping-2/pom.xml
@@ -55,32 +55,15 @@
h2
${h2.version}
-
- com.sun.xml.bind
- jaxb-core
- ${com.sun.xml.version}
-
-
- javax.xml.bind
- jaxb-api
- ${javax.xml.bind.version}
-
-
- com.sun.xml.bind
- jaxb-impl
- ${com.sun.xml.version}
-
- 5.0.2.RELEASE
- 1.10.6.RELEASE
+ 6.0.6
+ 3.0.3
- 5.2.10.Final
9.0.0.M26
- 2.3.0.1
- 2.3.1
+ 4.0.2
2.1.214
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/HibernateUtil.java
new file mode 100644
index 0000000000..df409ee888
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/HibernateUtil.java
@@ -0,0 +1,58 @@
+package com.baeldung.hibernate;
+
+import static org.hibernate.boot.registry.StandardServiceRegistryBuilder.DEFAULT_CFG_RESOURCE_NAME;
+
+import org.hibernate.SessionFactory;
+import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.service.ServiceRegistry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.baeldung.hibernate.booleanconverters.model.Question;
+import com.baeldung.hibernate.manytomany.model.Employee;
+import com.baeldung.hibernate.manytomany.model.Project;
+import com.baeldung.hibernate.uuids.WebSiteUser;
+import com.baeldung.hibernate.uuids.Element;
+import com.baeldung.hibernate.uuids.Reservation;
+import com.baeldung.hibernate.uuids.Sale;
+
+public class HibernateUtil {
+
+ private static final String DEFAULT_RESOURCE = "manytomany.cfg.xml";
+ private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);
+
+ private static SessionFactory buildSessionFactory(String resource) {
+ try {
+ // Create the SessionFactory from hibernate-annotation.cfg.xml
+ Configuration configuration = new Configuration();
+ configuration.addAnnotatedClass(Employee.class);
+ configuration.addAnnotatedClass(Project.class);
+ configuration.addAnnotatedClass(WebSiteUser.class);
+ configuration.addAnnotatedClass(Element.class);
+ configuration.addAnnotatedClass(Reservation.class);
+ configuration.addAnnotatedClass(Sale.class);
+ configuration.addAnnotatedClass(Question.class);
+ configuration.addPackage(Question.class.getPackageName());
+ configuration.configure(resource);
+ LOGGER.debug("Hibernate Annotation Configuration loaded");
+
+ ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
+ .build();
+ LOGGER.debug("Hibernate Annotation serviceRegistry created");
+
+ return configuration.buildSessionFactory(serviceRegistry);
+ } catch (Throwable ex) {
+ LOGGER.error("Initial SessionFactory creation failed.", ex);
+ throw new ExceptionInInitializerError(ex);
+ }
+ }
+
+ public static SessionFactory getSessionFactory() {
+ return buildSessionFactory(DEFAULT_RESOURCE);
+ }
+
+ public static SessionFactory getSessionFactory(String resource) {
+ return buildSessionFactory(resource);
+ }
+}
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/booleanconverters/model/Question.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/booleanconverters/model/Question.java
new file mode 100644
index 0000000000..be2990359f
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/booleanconverters/model/Question.java
@@ -0,0 +1,86 @@
+package com.baeldung.hibernate.booleanconverters.model;
+
+import java.util.UUID;
+
+import org.hibernate.type.NumericBooleanConverter;
+import org.hibernate.type.TrueFalseConverter;
+import org.hibernate.type.YesNoConverter;
+
+import jakarta.persistence.Convert;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+
+@Entity
+public class Question {
+
+ @Id
+ private UUID id;
+ private String content;
+ @Convert(converter = YesNoConverter.class)
+ private Boolean correctAnswer;
+ @Convert(converter = TrueFalseConverter.class)
+ private Boolean shouldBeAsked;
+ @Convert(converter = NumericBooleanConverter.class)
+ private Boolean isEasy;
+ private Boolean wasAskedBefore;
+
+ public Question() {
+ }
+
+ public Question(UUID id, String content, Boolean correctAnswer, Boolean shouldBeAsked, Boolean isEasy, Boolean wasAskedBefore) {
+ this.id = id;
+ this.content = content;
+ this.correctAnswer = correctAnswer;
+ this.shouldBeAsked = shouldBeAsked;
+ this.isEasy = isEasy;
+ this.wasAskedBefore = wasAskedBefore;
+ }
+
+ public UUID getId() {
+ return id;
+ }
+
+ public String getContent() {
+ return content;
+ }
+
+ public Boolean getCorrectAnswer() {
+ return correctAnswer;
+ }
+
+ public Boolean getShouldBeAsked() {
+ return shouldBeAsked;
+ }
+
+ public Boolean isEasy() {
+ return isEasy;
+ }
+
+ public Boolean getWasAskedBefore() {
+ return wasAskedBefore;
+ }
+
+ public void setId(UUID id) {
+ this.id = id;
+ }
+
+ public void setContent(String content) {
+ this.content = content;
+ }
+
+ public void setCorrectAnswer(Boolean correctAnswer) {
+ this.correctAnswer = correctAnswer;
+ }
+
+ public void setShouldBeAsked(Boolean shouldBeAsked) {
+ this.shouldBeAsked = shouldBeAsked;
+ }
+
+ public void setEasy(Boolean easy) {
+ isEasy = easy;
+ }
+
+ public void setWasAskedBefore(Boolean wasAskedBefore) {
+ this.wasAskedBefore = wasAskedBefore;
+ }
+}
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/booleanconverters/model/package-info.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/booleanconverters/model/package-info.java
new file mode 100644
index 0000000000..d5041b87c0
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/booleanconverters/model/package-info.java
@@ -0,0 +1,5 @@
+@ConverterRegistration(converter = YesNoConverter.class)
+package com.baeldung.hibernate.booleanconverters.model;
+
+import org.hibernate.annotations.ConverterRegistration;
+import org.hibernate.type.YesNoConverter;
\ No newline at end of file
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/PersistenceConfig.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/PersistenceConfig.java
similarity index 95%
rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/PersistenceConfig.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/PersistenceConfig.java
index 0d7b8bdbcf..4ec6c9fb71 100644
--- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/PersistenceConfig.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/PersistenceConfig.java
@@ -1,4 +1,4 @@
-package com.baeldung.manytomany;
+package com.baeldung.hibernate.manytomany;
import java.util.Properties;
@@ -22,7 +22,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@PropertySource({ "classpath:persistence-h2.properties" })
-@ComponentScan({ "com.baeldung.manytomany" })
+@ComponentScan({ "com.baeldung.hibernate.manytomany" })
public class PersistenceConfig {
@Autowired
@@ -32,7 +32,7 @@ public class PersistenceConfig {
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(restDataSource());
- sessionFactory.setPackagesToScan(new String[] { "com.baeldung.manytomany" });
+ sessionFactory.setPackagesToScan(new String[] { "com.baeldung.hibernate.manytomany" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/IEmployeeDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/IEmployeeDao.java
new file mode 100644
index 0000000000..7bff73ecf4
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/IEmployeeDao.java
@@ -0,0 +1,8 @@
+package com.baeldung.hibernate.manytomany.dao;
+
+import com.baeldung.hibernate.manytomany.dao.common.IOperations;
+import com.baeldung.hibernate.manytomany.model.Employee;
+
+public interface IEmployeeDao extends IOperations{
+
+}
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/IProjectDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/IProjectDao.java
new file mode 100644
index 0000000000..de800ae783
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/IProjectDao.java
@@ -0,0 +1,8 @@
+package com.baeldung.hibernate.manytomany.dao;
+
+import com.baeldung.hibernate.manytomany.dao.common.IOperations;
+import com.baeldung.hibernate.manytomany.model.Project;
+
+public interface IProjectDao extends IOperations{
+
+}
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/AbstractDao.java
similarity index 85%
rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractDao.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/AbstractDao.java
index b37b48e645..6ed04a9b2f 100644
--- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractDao.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/AbstractDao.java
@@ -1,4 +1,4 @@
-package com.baeldung.manytomany.dao.common;
+package com.baeldung.hibernate.manytomany.dao.common;
import java.io.Serializable;
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractHibernateDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/AbstractHibernateDao.java
similarity index 96%
rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractHibernateDao.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/AbstractHibernateDao.java
index 9c8a8faa2e..67878906ca 100644
--- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/AbstractHibernateDao.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/AbstractHibernateDao.java
@@ -1,4 +1,4 @@
-package com.baeldung.manytomany.dao.common;
+package com.baeldung.hibernate.manytomany.dao.common;
import java.io.Serializable;
import java.util.List;
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/IOperations.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/IOperations.java
similarity index 85%
rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/IOperations.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/IOperations.java
index 8a85b52fc9..2be7fdb75e 100644
--- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/common/IOperations.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/common/IOperations.java
@@ -1,4 +1,4 @@
-package com.baeldung.manytomany.dao.common;
+package com.baeldung.hibernate.manytomany.dao.common;
import java.io.Serializable;
import java.util.List;
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/EmployeeDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/impl/EmployeeDao.java
similarity index 50%
rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/EmployeeDao.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/impl/EmployeeDao.java
index b24013c567..d4364c00c2 100644
--- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/EmployeeDao.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/impl/EmployeeDao.java
@@ -1,10 +1,10 @@
-package com.baeldung.manytomany.dao.impl;
+package com.baeldung.hibernate.manytomany.dao.impl;
import org.springframework.stereotype.Repository;
-import com.baeldung.manytomany.dao.IEmployeeDao;
-import com.baeldung.manytomany.dao.common.AbstractHibernateDao;
-import com.baeldung.manytomany.model.Employee;
+import com.baeldung.hibernate.manytomany.dao.IEmployeeDao;
+import com.baeldung.hibernate.manytomany.dao.common.AbstractHibernateDao;
+import com.baeldung.hibernate.manytomany.model.Employee;
@Repository
public class EmployeeDao extends AbstractHibernateDao implements IEmployeeDao {
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/impl/ProjectDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/impl/ProjectDao.java
new file mode 100644
index 0000000000..a221116013
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/dao/impl/ProjectDao.java
@@ -0,0 +1,17 @@
+package com.baeldung.hibernate.manytomany.dao.impl;
+
+import org.springframework.stereotype.Repository;
+
+import com.baeldung.hibernate.manytomany.dao.IProjectDao;
+import com.baeldung.hibernate.manytomany.dao.common.AbstractHibernateDao;
+import com.baeldung.hibernate.manytomany.model.Project;
+
+@Repository
+public class ProjectDao extends AbstractHibernateDao implements IProjectDao {
+
+ public ProjectDao() {
+ super();
+
+ setClazz(Project.class);
+ }
+}
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Employee.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
similarity index 80%
rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Employee.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
index 39671c21bc..d606f1281c 100644
--- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Employee.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/model/Employee.java
@@ -1,19 +1,19 @@
-package com.baeldung.manytomany.model;
+package com.baeldung.hibernate.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.ManyToMany;
-import javax.persistence.Table;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.JoinTable;
+import jakarta.persistence.ManyToMany;
+import jakarta.persistence.Table;
@Entity
@Table(name = "Employee")
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Project.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java
similarity index 79%
rename from persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Project.java
rename to persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java
index b5dc3cb856..8ea31dbc5f 100644
--- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/model/Project.java
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/manytomany/model/Project.java
@@ -1,15 +1,15 @@
-package com.baeldung.manytomany.model;
+package com.baeldung.hibernate.manytomany.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.ManyToMany;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.ManyToMany;
+import jakarta.persistence.Table;
@Entity
@Table(name = "Project")
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Element.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Element.java
new file mode 100644
index 0000000000..5112c6df0f
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Element.java
@@ -0,0 +1,32 @@
+package com.baeldung.hibernate.uuids;
+
+import java.util.UUID;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import org.hibernate.annotations.UuidGenerator;
+
+@Entity
+public class Element {
+
+ @Id
+ @UuidGenerator
+ private String id;
+
+ private String name;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Reservation.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Reservation.java
new file mode 100644
index 0000000000..389376e785
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Reservation.java
@@ -0,0 +1,43 @@
+package com.baeldung.hibernate.uuids;
+
+import java.util.UUID;
+import jakarta.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+
+@Entity
+public class Reservation {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.UUID)
+ private UUID id;
+
+ private String status;
+
+ private String number;
+
+ public UUID getId() {
+ return id;
+ }
+
+ public void setId(UUID id) {
+ this.id = id;
+ }
+
+ public String getStatus() {
+ return status;
+ }
+
+ public void setStatus(String status) {
+ this.status = status;
+ }
+
+ public String getNumber() {
+ return number;
+ }
+
+ public void setNumber(String number) {
+ this.number = number;
+ }
+}
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Sale.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Sale.java
new file mode 100644
index 0000000000..8eaab80912
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/Sale.java
@@ -0,0 +1,36 @@
+package com.baeldung.hibernate.uuids;
+
+import jakarta.persistence.Id;
+import jakarta.persistence.Entity;
+import org.hibernate.annotations.UuidGenerator;
+
+import java.util.UUID;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import org.hibernate.annotations.UuidGenerator;
+
+@Entity
+public class Sale {
+
+ @Id
+ @UuidGenerator
+ private UUID id;
+
+ private boolean completed;
+
+ public UUID getId() {
+ return id;
+ }
+
+ public void setId(UUID id) {
+ this.id = id;
+ }
+
+ public boolean isCompleted() {
+ return completed;
+ }
+
+ public void setCompleted(boolean completed) {
+ this.completed = completed;
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/WebSiteUser.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/WebSiteUser.java
new file mode 100644
index 0000000000..b1a115a3b9
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/hibernate/uuids/WebSiteUser.java
@@ -0,0 +1,33 @@
+package com.baeldung.hibernate.uuids;
+
+import java.util.UUID;
+import java.time.LocalDate;
+import jakarta.persistence.Id;
+import jakarta.persistence.Entity;
+import org.hibernate.annotations.UuidGenerator;
+
+@Entity
+public class WebSiteUser {
+
+ @Id
+ @UuidGenerator(style = UuidGenerator.Style.TIME)
+ private UUID id;
+
+ private LocalDate registrationDate;
+
+ public UUID getId() {
+ return id;
+ }
+
+ public void setId(UUID id) {
+ this.id = id;
+ }
+
+ public LocalDate getRegistrationDate() {
+ return registrationDate;
+ }
+
+ public void setRegistrationDate(LocalDate registrationDate) {
+ this.registrationDate = registrationDate;
+ }
+}
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java
deleted file mode 100644
index 68bf5d5bad..0000000000
--- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IEmployeeDao.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.baeldung.manytomany.dao;
-
-import com.baeldung.manytomany.dao.common.IOperations;
-import com.baeldung.manytomany.model.Employee;
-
-public interface IEmployeeDao extends IOperations{
-
-}
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java
deleted file mode 100644
index d2645db44a..0000000000
--- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/IProjectDao.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.baeldung.manytomany.dao;
-
-import com.baeldung.manytomany.dao.common.IOperations;
-import com.baeldung.manytomany.model.Project;
-
-public interface IProjectDao extends IOperations{
-
-}
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/ProjectDao.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/ProjectDao.java
deleted file mode 100644
index a70212f519..0000000000
--- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/dao/impl/ProjectDao.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.baeldung.manytomany.dao.impl;
-
-import org.springframework.stereotype.Repository;
-
-import com.baeldung.manytomany.dao.IProjectDao;
-import com.baeldung.manytomany.dao.common.AbstractHibernateDao;
-import com.baeldung.manytomany.model.Project;
-
-
-@Repository
-public class ProjectDao extends AbstractHibernateDao implements IProjectDao {
-
- public ProjectDao() {
- super();
-
- setClazz(Project.class);
- }
-}
diff --git a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/util/HibernateUtil.java b/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/util/HibernateUtil.java
deleted file mode 100644
index d429564564..0000000000
--- a/persistence-modules/hibernate-mapping-2/src/main/java/com/baeldung/manytomany/util/HibernateUtil.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.baeldung.manytomany.util;
-
-import org.hibernate.SessionFactory;
-import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.service.ServiceRegistry;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.baeldung.manytomany.model.Employee;
-import com.baeldung.manytomany.model.Project;
-
-public class HibernateUtil {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class);
- private static SessionFactory sessionFactory;
-
- private static SessionFactory buildSessionFactory() {
- try {
- // Create the SessionFactory from hibernate-annotation.cfg.xml
- Configuration configuration = new Configuration();
- configuration.addAnnotatedClass(Employee.class);
- configuration.addAnnotatedClass(Project.class);
- configuration.configure("manytomany.cfg.xml");
- LOGGER.debug("Hibernate Annotation Configuration loaded");
-
- ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
- .build();
- LOGGER.debug("Hibernate Annotation serviceRegistry created");
-
- SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
-
- return sessionFactory;
- } catch (Throwable ex) {
- LOGGER.error("Initial SessionFactory creation failed.", ex);
- throw new ExceptionInInitializerError(ex);
- }
- }
-
- public static SessionFactory getSessionFactory() {
- if (sessionFactory == null) {
- sessionFactory = buildSessionFactory();
- }
- return sessionFactory;
- }
-}
diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java
index f1a6f675ce..e1650dccd2 100644
--- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java
+++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/SpringContextTest.java
@@ -6,7 +6,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
-import com.baeldung.manytomany.PersistenceConfig;
+import com.baeldung.hibernate.manytomany.PersistenceConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/booleanconverters/HibernateBooleanConverterIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/booleanconverters/HibernateBooleanConverterIntegrationTest.java
new file mode 100644
index 0000000000..3235485e96
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/booleanconverters/HibernateBooleanConverterIntegrationTest.java
@@ -0,0 +1,158 @@
+package com.baeldung.hibernate.booleanconverters;
+
+import static java.lang.String.format;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+import java.util.UUID;
+
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import com.baeldung.hibernate.HibernateUtil;
+import com.baeldung.hibernate.booleanconverters.model.Question;
+
+public class HibernateBooleanConverterIntegrationTest {
+
+ private static final String PROPERTY_FILE_NAME = "booleanconverters.cfg.xml";
+
+ private static SessionFactory sessionFactory;
+ private static Session session;
+
+ @BeforeAll
+ static void createSessionFactory() {
+ sessionFactory = HibernateUtil.getSessionFactory(PROPERTY_FILE_NAME);
+ }
+
+ @BeforeEach
+ void openSessionAndBeginTransaction() {
+ session = sessionFactory.openSession();
+ }
+
+ @AfterAll
+ static void closeSessionFactory() {
+ sessionFactory.close();
+ }
+
+ @Test
+ void whenFieldAnnotatedWithYesNoConverter_ThenConversionWorks() {
+ session.beginTransaction();
+ UUID likeJavaQuestionId = UUID.randomUUID();
+ UUID sydneyCapitalOfAustraliaQuestionId = UUID.randomUUID();
+ session.persist(new QuestionBuilder().id(likeJavaQuestionId)
+ .content("Do you like Java?")
+ .correctAnswer(true)
+ .build());
+ session.persist(new QuestionBuilder().id(sydneyCapitalOfAustraliaQuestionId)
+ .content("Is Sydney the capital of Australia?")
+ .correctAnswer(false)
+ .build());
+ session.flush();
+
+ char likeJavaQuestionCorrectAnswerDbValue = session.createNativeQuery(format("SELECT correctAnswer FROM Question WHERE id='%s'", likeJavaQuestionId), Character.class)
+ .getSingleResult();
+ char sydneyCapitalOfAustraliaQuestionCorrectAnswerDbValue = session.createNativeQuery(format("SELECT correctAnswer FROM Question WHERE id='%s'", sydneyCapitalOfAustraliaQuestionId), Character.class)
+ .getSingleResult();
+ session.close();
+
+ assertEquals('Y', likeJavaQuestionCorrectAnswerDbValue);
+ assertEquals('N', sydneyCapitalOfAustraliaQuestionCorrectAnswerDbValue);
+ }
+
+ @Test
+ void whenFieldAnnotatedWithTrueFalseConverter_ThenConversionWorks() {
+ session.beginTransaction();
+ UUID codeTestedQuestionId = UUID.randomUUID();
+ UUID earningsQuestionId = UUID.randomUUID();
+ session.persist(new QuestionBuilder().id(codeTestedQuestionId)
+ .content("Is this code tested?")
+ .shouldBeAsked(true)
+ .build());
+ session.persist(new QuestionBuilder().id(earningsQuestionId)
+ .content("How much do you earn?")
+ .shouldBeAsked(false)
+ .build());
+ session.flush();
+
+ char codeTestedQuestionShouldBeAskedDbValue = session.createNativeQuery(format("SELECT shouldBeAsked FROM Question WHERE id='%s'", codeTestedQuestionId), Character.class)
+ .getSingleResult();
+ char earningsQuestionsShouldBeAskedDbValue = session.createNativeQuery(format("SELECT shouldBeAsked FROM Question WHERE id='%s'", earningsQuestionId), Character.class)
+ .getSingleResult();
+ session.close();
+
+ assertEquals('T', codeTestedQuestionShouldBeAskedDbValue);
+ assertEquals('F', earningsQuestionsShouldBeAskedDbValue);
+ }
+
+ @Test
+ void whenFieldAnnotatedWithNumericBooleanConverter_ThenConversionWorks() {
+ session.beginTransaction();
+ UUID earthFlatQuestionId = UUID.randomUUID();
+ UUID shouldLearnProgrammingQuestionId = UUID.randomUUID();
+ session.persist(new QuestionBuilder().id(earthFlatQuestionId)
+ .content("Is the Earth flat?")
+ .isEasy(true)
+ .build());
+ session.persist(new QuestionBuilder().id(shouldLearnProgrammingQuestionId)
+ .content("Should one learn programming")
+ .isEasy(false)
+ .build());
+ session.flush();
+
+ int earthFlatQuestionIsEasyDbValue = session.createNativeQuery(format("SELECT isEasy FROM Question WHERE id='%s'", earthFlatQuestionId), Integer.class)
+ .getSingleResult();
+ int shouldLearnProgrammingQuestionIsEasyDbValue = session.createNativeQuery(format("SELECT isEasy FROM Question WHERE id='%s'", shouldLearnProgrammingQuestionId), Integer.class)
+ .getSingleResult();
+ session.close();
+
+ assertEquals(1, earthFlatQuestionIsEasyDbValue);
+ assertEquals(0, shouldLearnProgrammingQuestionIsEasyDbValue);
+ }
+
+ @Test
+ void givenFieldAnnotatedWithYesNoConverter_WhenDbValueIsLowercase_ThenDomainModelValueNull() {
+ session.beginTransaction();
+ UUID mappedToNullQuestionId = UUID.randomUUID();
+ UUID behaviorIntuitiveQuestionId = UUID.randomUUID();
+ session.createNativeMutationQuery(format("INSERT INTO Question (id, content, correctAnswer) VALUES ('%s', 'Will correctAnswer be mapped to null?', 'y')", mappedToNullQuestionId))
+ .executeUpdate();
+ session.createNativeMutationQuery(format("INSERT INTO Question (id, content, correctAnswer) VALUES ('%s', 'Is this behavior intuitive?', 'n')", behaviorIntuitiveQuestionId))
+ .executeUpdate();
+
+ Question behaviorIntuitiveQuestion = session.get(Question.class, behaviorIntuitiveQuestionId);
+ Question mappedToNullQuestion = session.get(Question.class, mappedToNullQuestionId);
+ session.close();
+
+ assertNull(behaviorIntuitiveQuestion.getCorrectAnswer());
+ assertNull(mappedToNullQuestion.getCorrectAnswer());
+ }
+
+ @Test
+ void givenConverterRegisteredToAutoApply_whenFieldIsNotAnnotated_ThenConversionWorks() {
+ session.beginTransaction();
+ UUID likeJavaQuestionId = UUID.randomUUID();
+ UUID likeKotlinQuestionId = UUID.randomUUID();
+ session.persist(new QuestionBuilder().id(likeJavaQuestionId)
+ .content("Do you like Java?")
+ .wasAskedBefore(true)
+ .build());
+ session.persist(new QuestionBuilder().id(likeKotlinQuestionId)
+ .content("Do you like Kotlin?")
+ .wasAskedBefore(false)
+ .build());
+ session.flush();
+
+ char likeJavaQuestionWasAskedBeforeDbValue = session.createNativeQuery(format("SELECT wasAskedBefore FROM Question WHERE id='%s'", likeJavaQuestionId), Character.class)
+ .getSingleResult();
+ char likeKotlinQuestionWasAskedBeforeDbValue = session.createNativeQuery(format("SELECT wasAskedBefore FROM Question WHERE id='%s'", likeKotlinQuestionId), Character.class)
+ .getSingleResult();
+ session.close();
+
+ assertEquals('Y', likeJavaQuestionWasAskedBeforeDbValue);
+ assertEquals('N', likeKotlinQuestionWasAskedBeforeDbValue);
+ }
+}
diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/booleanconverters/QuestionBuilder.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/booleanconverters/QuestionBuilder.java
new file mode 100644
index 0000000000..26fe38c3c8
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/booleanconverters/QuestionBuilder.java
@@ -0,0 +1,48 @@
+package com.baeldung.hibernate.booleanconverters;
+
+import java.util.UUID;
+
+import com.baeldung.hibernate.booleanconverters.model.Question;
+
+public class QuestionBuilder {
+ private UUID id;
+ private String content;
+ private Boolean correctAnswer;
+ private Boolean shouldBeAsked;
+ private Boolean isEasy;
+ private Boolean wasAskedBefore;
+
+ public QuestionBuilder id(UUID id) {
+ this.id = id;
+ return this;
+ }
+
+ public QuestionBuilder content(String content) {
+ this.content = content;
+ return this;
+ }
+
+ public QuestionBuilder correctAnswer(Boolean correctAnswer) {
+ this.correctAnswer = correctAnswer;
+ return this;
+ }
+
+ public QuestionBuilder shouldBeAsked(Boolean shouldBeAsked) {
+ this.shouldBeAsked = shouldBeAsked;
+ return this;
+ }
+
+ public QuestionBuilder isEasy(Boolean isEasy) {
+ this.isEasy = isEasy;
+ return this;
+ }
+
+ public QuestionBuilder wasAskedBefore(Boolean wasAskedBefore) {
+ this.wasAskedBefore = wasAskedBefore;
+ return this;
+ }
+
+ public Question build() {
+ return new Question(id, content, correctAnswer, shouldBeAsked, isEasy, wasAskedBefore);
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
index 69b791b4d4..e4fcafcb56 100644
--- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
+++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationJavaConfigMainIntegrationTest.java
@@ -13,9 +13,9 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
-import com.baeldung.manytomany.PersistenceConfig;
-import com.baeldung.manytomany.model.Employee;
-import com.baeldung.manytomany.model.Project;
+
+import com.baeldung.hibernate.manytomany.model.Employee;
+import com.baeldung.hibernate.manytomany.model.Project;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { PersistenceConfig.class }, loader = AnnotationConfigContextLoader.class)
diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
index 5255cb040f..7c6861e63b 100644
--- a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
+++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/manytomany/HibernateManyToManyAnnotationMainIntegrationTest.java
@@ -15,9 +15,9 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import com.baeldung.manytomany.model.Employee;
-import com.baeldung.manytomany.model.Project;
-import com.baeldung.manytomany.util.HibernateUtil;
+import com.baeldung.hibernate.manytomany.model.Employee;
+import com.baeldung.hibernate.manytomany.model.Project;
+import com.baeldung.hibernate.HibernateUtil;
/**
* Configured in: manytomany.cfg.xml
diff --git a/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/uuids/UUIDsHibernateGenerationIntegrationTest.java b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/uuids/UUIDsHibernateGenerationIntegrationTest.java
new file mode 100644
index 0000000000..f36a4333c3
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/test/java/com/baeldung/hibernate/uuids/UUIDsHibernateGenerationIntegrationTest.java
@@ -0,0 +1,72 @@
+package com.baeldung.hibernate.uuids;
+
+import com.baeldung.hibernate.HibernateUtil;
+
+import org.assertj.core.api.Assertions;
+import java.io.IOException;
+
+import org.hibernate.SessionFactory;
+import org.hibernate.Session;
+import org.junit.Before;
+import org.junit.Test;
+import java.util.UUID;
+import java.time.LocalDate;
+
+public class UUIDsHibernateGenerationIntegrationTest {
+
+ private SessionFactory sessionFactory;
+
+ private Session session;
+
+ @Before
+ public void setUp() throws IOException {
+ sessionFactory = HibernateUtil.getSessionFactory();
+ session = sessionFactory.openSession();
+ }
+
+ @Test
+ public void whenGeneratingUUIDUsingNewJPAGenerationType_thenHibernateGeneratedUUID() throws IOException {
+ Reservation reservation = new Reservation();
+ reservation.setStatus("created");
+ reservation.setNumber("12345");
+ UUID saved = (UUID) session.save(reservation);
+ Assertions.assertThat(saved).isNotNull();
+ }
+
+ @Test
+ public void whenGeneratingUUIDUsingNewJPAGenerationType_thenHibernateGeneratedUUIDOfVersion4() throws IOException {
+ Reservation reservation = new Reservation();
+ reservation.setStatus("new");
+ reservation.setNumber("012");
+ UUID saved = (UUID) session.save(reservation);
+ Assertions.assertThat(saved).isNotNull();
+ Assertions.assertThat(saved.version()).isEqualTo(4);
+ }
+
+ @Test
+ public void whenGeneratingUUIDUsingGenericConverter_thenAlsoGetUUIDGeneratedVersion4() throws IOException {
+ Sale sale = new Sale();
+ sale.setCompleted(true);
+ UUID saved = (UUID) session.save(sale);
+ Assertions.assertThat(saved).isNotNull();
+ Assertions.assertThat(saved.version()).isEqualTo(4);
+ }
+
+ @Test
+ public void whenGeneratingTimeBasedUUID_thenUUIDGeneratedVersion1() throws IOException {
+ WebSiteUser user = new WebSiteUser();
+ user.setRegistrationDate(LocalDate.now());
+ UUID saved = (UUID) session.save(user);
+ Assertions.assertThat(saved).isNotNull();
+ Assertions.assertThat(saved.version()).isEqualTo(1);
+ }
+
+ @Test
+ public void whenGeneratingUUIDAsString_thenUUIDGeneratedVersion1() throws IOException {
+ Element element = new Element();
+ element.setName("a");
+ String saved = (String) session.save(element);
+ Assertions.assertThat(saved).isNotEmpty();
+ Assertions.assertThat(UUID.fromString(saved).version()).isEqualTo(4);
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/hibernate-mapping-2/src/test/resources/booleanconverters.cfg.xml b/persistence-modules/hibernate-mapping-2/src/test/resources/booleanconverters.cfg.xml
new file mode 100644
index 0000000000..6ca479b052
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/test/resources/booleanconverters.cfg.xml
@@ -0,0 +1,16 @@
+
+
+
+
+ org.h2.Driver
+
+ jdbc:h2:mem:booleanconvertersdb;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'src/test/resources/booleanconverters/init_database.sql'
+ sa
+ org.hibernate.dialect.H2Dialect
+ thread
+ false
+ none
+
+
\ No newline at end of file
diff --git a/persistence-modules/hibernate-mapping-2/src/test/resources/booleanconverters/init_database.sql b/persistence-modules/hibernate-mapping-2/src/test/resources/booleanconverters/init_database.sql
new file mode 100644
index 0000000000..cb0f4f329c
--- /dev/null
+++ b/persistence-modules/hibernate-mapping-2/src/test/resources/booleanconverters/init_database.sql
@@ -0,0 +1,9 @@
+CREATE TABLE Question (
+ id UUID,
+ content VARCHAR,
+ correctAnswer CHAR,
+ shouldBeAsked CHAR,
+ isEasy TINYINT,
+ wasAskedBefore CHAR,
+ PRIMARY KEY (id)
+)
diff --git a/persistence-modules/hibernate-mapping/pom.xml b/persistence-modules/hibernate-mapping/pom.xml
index 506283a4fb..1e3dc8be5f 100644
--- a/persistence-modules/hibernate-mapping/pom.xml
+++ b/persistence-modules/hibernate-mapping/pom.xml
@@ -26,7 +26,7 @@
com.vladmihalcea
- hibernate-types-52
+ hibernate-types-60
${hibernate-types.version}
@@ -41,9 +41,9 @@
${hibernate-validator.version}
- org.glassfish
- javax.el
- ${org.glassfish.javax.el.version}
+ org.glassfish.expressly
+ expressly
+ 5.0.0
javax.money
@@ -66,16 +66,27 @@
commons-io
${commons-io.version}
+
+ com.fasterxml.jackson.module
+ jackson-module-jakarta-xmlbind-annotations
+ ${jackson-module-jakarta-xmlbind-annotation}
+
+
+ org.openjdk.nashorn
+ nashorn-core
+ 15.4
+
- 1.4.197
- 5.4.12.Final
- 2.10.4
- 6.0.16.Final
+ 2.1.214
+ 6.1.7.Final
+ 2.21.1
+ 8.0.0.Final
3.0.1-b11
- 1.0.3
- 1.3
+ 1.1
+ 1.4.2
+ 2.14.2
\ No newline at end of file
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java
index fbd8bd487b..cbd73832a4 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/HibernateUtil.java
@@ -21,6 +21,7 @@ import com.baeldung.hibernate.pojo.inheritance.Animal;
import com.baeldung.hibernate.pojo.inheritance.Bag;
import com.baeldung.hibernate.pojo.inheritance.Book;
import com.baeldung.hibernate.pojo.inheritance.Car;
+import com.baeldung.hibernate.pojo.inheritance.Laptop;
import com.baeldung.hibernate.pojo.inheritance.MyEmployee;
import com.baeldung.hibernate.pojo.inheritance.MyProduct;
import com.baeldung.hibernate.pojo.inheritance.Pen;
@@ -79,6 +80,7 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);
metadataSources.addAnnotatedClass(Animal.class);
metadataSources.addAnnotatedClass(Bag.class);
+ metadataSources.addAnnotatedClass(Laptop.class);
metadataSources.addAnnotatedClass(Book.class);
metadataSources.addAnnotatedClass(Car.class);
metadataSources.addAnnotatedClass(MyEmployee.class);
@@ -86,7 +88,6 @@ public class HibernateUtil {
metadataSources.addAnnotatedClass(Pen.class);
metadataSources.addAnnotatedClass(Pet.class);
metadataSources.addAnnotatedClass(Vehicle.class);
-
Metadata metadata = metadataSources.getMetadataBuilder()
.build();
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomIntegerArrayType.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomIntegerArrayType.java
index 233bb95dc1..5d3e22bf05 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomIntegerArrayType.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomIntegerArrayType.java
@@ -8,58 +8,56 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
-import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
-public class CustomIntegerArrayType implements UserType {
+public class CustomIntegerArrayType implements UserType {
@Override
- public int[] sqlTypes() {
- return new int[]{Types.ARRAY};
+ public int getSqlType() {
+ return Types.ARRAY;
}
@Override
- public Class returnedClass() {
+ public Class returnedClass() {
return Integer[].class;
}
@Override
- public boolean equals(Object x, Object y) throws HibernateException {
+ public boolean equals(Integer[] x, Integer[] y) {
if (x instanceof Integer[] && y instanceof Integer[]) {
- return Arrays.deepEquals((Integer[])x, (Integer[])y);
+ return Arrays.deepEquals(x, y);
} else {
return false;
}
}
@Override
- public int hashCode(Object x) throws HibernateException {
- return Arrays.hashCode((Integer[])x);
+ public int hashCode(Integer[] x) {
+ return Arrays.hashCode(x);
}
@Override
- public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
- throws HibernateException, SQLException {
- Array array = rs.getArray(names[0]);
- return array != null ? array.getArray() : null;
+ public Integer[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
+ Array array = rs.getArray(position);
+ return array != null ? (Integer[]) array.getArray() : null;
}
@Override
- public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
- throws HibernateException, SQLException {
- if (value != null && st != null) {
- Array array = session.connection().createArrayOf("int", (Integer[])value);
- st.setArray(index, array);
- } else {
- st.setNull(index, sqlTypes()[0]);
+ public void nullSafeSet(PreparedStatement st, Integer[] value, int index, SharedSessionContractImplementor session) throws SQLException {
+ if (st != null) {
+ if (value != null) {
+ Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("int", value);
+ st.setArray(index, array);
+ } else {
+ st.setNull(index, Types.ARRAY);
+ }
}
}
@Override
- public Object deepCopy(Object value) throws HibernateException {
- Integer[] a = (Integer[])value;
- return Arrays.copyOf(a, a.length);
+ public Integer[] deepCopy(Integer[] value) {
+ return value != null ? Arrays.copyOf(value, value.length) : null;
}
@Override
@@ -68,18 +66,18 @@ public class CustomIntegerArrayType implements UserType {
}
@Override
- public Serializable disassemble(Object value) throws HibernateException {
- return (Serializable) value;
+ public Serializable disassemble(Integer[] value) {
+ return value;
}
@Override
- public Object assemble(Serializable cached, Object owner) throws HibernateException {
- return cached;
+ public Integer[] assemble(Serializable cached, Object owner) {
+ return (Integer[]) cached;
}
@Override
- public Object replace(Object original, Object target, Object owner) throws HibernateException {
- return original;
+ public Integer[] replace(Integer[] detached, Integer[] managed, Object owner) {
+ return detached;
}
}
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomStringArrayType.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomStringArrayType.java
index 7bd284def7..31a082fb05 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomStringArrayType.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/CustomStringArrayType.java
@@ -8,58 +8,56 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
-import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
-public class CustomStringArrayType implements UserType {
+public class CustomStringArrayType implements UserType {
@Override
- public int[] sqlTypes() {
- return new int[]{Types.ARRAY};
+ public int getSqlType() {
+ return Types.ARRAY;
}
@Override
- public Class returnedClass() {
+ public Class returnedClass() {
return String[].class;
}
@Override
- public boolean equals(Object x, Object y) throws HibernateException {
+ public boolean equals(String[] x, String[] y) {
if (x instanceof String[] && y instanceof String[]) {
- return Arrays.deepEquals((String[])x, (String[])y);
+ return Arrays.deepEquals(x, y);
} else {
return false;
}
}
@Override
- public int hashCode(Object x) throws HibernateException {
- return Arrays.hashCode((String[])x);
+ public int hashCode(String[] x) {
+ return Arrays.hashCode(x);
}
@Override
- public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
- throws HibernateException, SQLException {
- Array array = rs.getArray(names[0]);
- return array != null ? array.getArray() : null;
+ public String[] nullSafeGet(ResultSet rs, int position, SharedSessionContractImplementor session, Object owner) throws SQLException {
+ Array array = rs.getArray(position);
+ return array != null ? (String[]) array.getArray() : null;
}
@Override
- public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
- throws HibernateException, SQLException {
- if (value != null && st != null) {
- Array array = session.connection().createArrayOf("text", (String[])value);
- st.setArray(index, array);
- } else {
- st.setNull(index, sqlTypes()[0]);
+ public void nullSafeSet(PreparedStatement st, String[] value, int index, SharedSessionContractImplementor session) throws SQLException {
+ if (st != null) {
+ if (value != null) {
+ Array array = session.getJdbcConnectionAccess().obtainConnection().createArrayOf("text", value);
+ st.setArray(index, array);
+ } else {
+ st.setNull(index, Types.ARRAY);
+ }
}
}
@Override
- public Object deepCopy(Object value) throws HibernateException {
- String[] a = (String[])value;
- return Arrays.copyOf(a, a.length);
+ public String[] deepCopy(String[] value) {
+ return value != null ? Arrays.copyOf(value, value.length) : null;
}
@Override
@@ -68,18 +66,18 @@ public class CustomStringArrayType implements UserType {
}
@Override
- public Serializable disassemble(Object value) throws HibernateException {
- return (Serializable) value;
+ public Serializable disassemble(String[] value) {
+ return value;
}
@Override
- public Object assemble(Serializable cached, Object owner) throws HibernateException {
- return cached;
+ public String[] assemble(Serializable cached, Object owner) {
+ return (String[]) cached;
}
@Override
- public Object replace(Object original, Object target, Object owner) throws HibernateException {
- return original;
+ public String[] replace(String[] detached, String[] managed, Object owner) {
+ return detached;
}
}
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/User.java
index 018bedc349..81f2ee89f7 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/User.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/arraymapping/User.java
@@ -1,21 +1,13 @@
package com.baeldung.hibernate.arraymapping;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
import org.hibernate.annotations.Type;
import com.vladmihalcea.hibernate.type.array.StringArrayType;
-import org.hibernate.annotations.*;
-
-@TypeDefs({
- @TypeDef(
- name = "string-array",
- typeClass = StringArrayType.class
- )
-})
@Entity
public class User {
@@ -25,14 +17,14 @@ public class User {
private String name;
@Column(columnDefinition = "text[]")
- @Type(type = "com.baeldung.hibernate.arraymapping.CustomStringArrayType")
+ @Type(value = com.baeldung.hibernate.arraymapping.CustomStringArrayType.class)
private String[] roles;
@Column(columnDefinition = "int[]")
- @Type(type = "com.baeldung.hibernate.arraymapping.CustomIntegerArrayType")
+ @Type(value = com.baeldung.hibernate.arraymapping.CustomIntegerArrayType.class)
private Integer[] locations;
- @Type(type = "string-array")
+ @Type(StringArrayType.class)
@Column(
name = "phone_numbers",
columnDefinition = "text[]"
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/basicannotation/Course.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/basicannotation/Course.java
index e816fb0176..ca77888f9b 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/basicannotation/Course.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/basicannotation/Course.java
@@ -1,10 +1,9 @@
package com.baeldung.hibernate.basicannotation;
-import javax.persistence.Basic;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
+import jakarta.persistence.Basic;
+import jakarta.persistence.Entity;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.Id;
@Entity
public class Course {
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java
index ff94f4f849..39e69a2b1c 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/Department.java
@@ -2,7 +2,7 @@ package com.baeldung.hibernate.entities;
import java.util.List;
-import javax.persistence.*;
+import jakarta.persistence.*;
@Entity
public class Department {
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java
index 6510e70650..3c4f542ce7 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/entities/DeptEmployee.java
@@ -1,13 +1,13 @@
package com.baeldung.hibernate.entities;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.ManyToOne;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.ManyToOne;
@org.hibernate.annotations.NamedQueries({ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindByEmployeeNumber", query = "from DeptEmployee where employeeNumber = :employeeNo"),
- @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where designation = :designation"),
+ @org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDesgination", query = "from DeptEmployee where employeeNumber = :designation"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_UpdateEmployeeDepartment", query = "Update DeptEmployee set department = :newDepartment where employeeNumber = :employeeNo"),
@org.hibernate.annotations.NamedQuery(name = "DeptEmployee_FindAllByDepartment", query = "from DeptEmployee where department = :department", timeout = 1, fetchSize = 10) })
@org.hibernate.annotations.NamedNativeQueries({ @org.hibernate.annotations.NamedNativeQuery(name = "DeptEmployee_FindByEmployeeName", query = "select * from deptemployee emp where name=:name", resultClass = DeptEmployee.class),
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java
index 5589601da8..b8937c6692 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Customer.java
@@ -3,10 +3,10 @@ package com.baeldung.hibernate.fetchMode;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.OneToMany;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToMany;
import java.util.HashSet;
import java.util.Set;
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java
index aa9c517321..5be65bac0d 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/fetchMode/Order.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.fetchMode;
-import javax.persistence.*;
+import jakarta.persistence.*;
@Entity
public class Order {
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java
index 21f725b388..3c3b748990 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/lob/model/User.java
@@ -1,13 +1,13 @@
package com.baeldung.hibernate.lob.model;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Lob;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Lob;
+import jakarta.persistence.Table;
@Entity
-@Table(name="user")
+@Table(name="users")
public class User {
@Id
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Item.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Item.java
index 385ffe93ea..ff8115f5d9 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Item.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Item.java
@@ -2,15 +2,15 @@ package com.baeldung.hibernate.persistmaps.mapkey;
import com.baeldung.hibernate.persistmaps.ItemType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.EnumType;
-import javax.persistence.Enumerated;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.Table;
-import javax.persistence.Temporal;
-import javax.persistence.TemporalType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EnumType;
+import jakarta.persistence.Enumerated;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import java.util.Date;
import java.util.Objects;
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Order.java
index 8409cacd6b..e42ceda5de 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Order.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/Order.java
@@ -1,15 +1,15 @@
package com.baeldung.hibernate.persistmaps.mapkey;
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.MapKey;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.JoinTable;
+import jakarta.persistence.MapKey;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Table;
import java.util.Map;
@Entity
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java
index b2ee7e85fe..0a9694f43c 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkey/User.java
@@ -1,16 +1,15 @@
package com.baeldung.hibernate.persistmaps.mapkey;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.validation.constraints.Size;
-import javax.money.MonetaryAmount;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
+import jakarta.validation.constraints.Size;
import org.hibernate.validator.constraints.Length;
-import org.hibernate.validator.constraints.CreditCardNumber;
-import org.hibernate.validator.constraints.Currency;
@Entity
+@Table(name="users2")
public class User {
@Id
@Column(length = 3)
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeycolumn/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeycolumn/Order.java
index fa092060da..3d24c743d7 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeycolumn/Order.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeycolumn/Order.java
@@ -1,14 +1,14 @@
package com.baeldung.hibernate.persistmaps.mapkeycolumn;
-import javax.persistence.CollectionTable;
-import javax.persistence.Column;
-import javax.persistence.ElementCollection;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.MapKeyColumn;
-import javax.persistence.Table;
+import jakarta.persistence.CollectionTable;
+import jakarta.persistence.Column;
+import jakarta.persistence.ElementCollection;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.MapKeyColumn;
+import jakarta.persistence.Table;
import java.util.Map;
@Entity
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyenumerated/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyenumerated/Order.java
index e1f62599b8..19622ea01d 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyenumerated/Order.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyenumerated/Order.java
@@ -3,17 +3,17 @@ package com.baeldung.hibernate.persistmaps.mapkeyenumerated;
import com.baeldung.hibernate.persistmaps.ItemType;
import com.baeldung.hibernate.persistmaps.mapkey.Item;
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.EnumType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.MapKeyEnumerated;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EnumType;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.JoinTable;
+import jakarta.persistence.MapKeyEnumerated;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Table;
import java.util.Map;
@Entity
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Item.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Item.java
index 97bbd5b539..9ed58305da 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Item.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Item.java
@@ -2,18 +2,18 @@ package com.baeldung.hibernate.persistmaps.mapkeyjoincolumn;
import com.baeldung.hibernate.persistmaps.ItemType;
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.EnumType;
-import javax.persistence.Enumerated;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.Table;
-import javax.persistence.Temporal;
-import javax.persistence.TemporalType;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.EnumType;
+import jakarta.persistence.Enumerated;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToOne;
+import jakarta.persistence.Table;
+import jakarta.persistence.Temporal;
+import jakarta.persistence.TemporalType;
import java.util.Date;
import java.util.Objects;
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Order.java
index d680d84501..9d20237860 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Order.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Order.java
@@ -1,15 +1,15 @@
package com.baeldung.hibernate.persistmaps.mapkeyjoincolumn;
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.MapKeyJoinColumn;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.JoinTable;
+import jakarta.persistence.MapKeyJoinColumn;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Table;
import java.util.Map;
@Entity
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Seller.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Seller.java
index 15b08e9fe6..ca06db241e 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Seller.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeyjoincolumn/Seller.java
@@ -1,10 +1,10 @@
package com.baeldung.hibernate.persistmaps.mapkeyjoincolumn;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
import java.util.Objects;
@Entity
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeytemporal/Order.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeytemporal/Order.java
index be602c1e9f..920d693d16 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeytemporal/Order.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/persistmaps/mapkeytemporal/Order.java
@@ -2,17 +2,17 @@ package com.baeldung.hibernate.persistmaps.mapkeytemporal;
import com.baeldung.hibernate.persistmaps.mapkey.Item;
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.MapKeyTemporal;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
-import javax.persistence.TemporalType;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.JoinTable;
+import jakarta.persistence.MapKeyTemporal;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.Table;
+import jakarta.persistence.TemporalType;
import java.util.Date;
import java.util.Map;
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java
index e9732b2b67..7d8a254eec 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Employee.java
@@ -2,15 +2,15 @@ package com.baeldung.hibernate.pojo;
import org.hibernate.annotations.*;
-import javax.persistence.Entity;
-import javax.persistence.*;
+import jakarta.persistence.Entity;
+import jakarta.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
@Where(clause = "deleted = false")
-@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int"))
+@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = Integer.class))
@Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit")
public class Employee implements Serializable {
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java
index 131bb73a80..29befd80f2 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/EntityDescription.java
@@ -1,8 +1,11 @@
package com.baeldung.hibernate.pojo;
import org.hibernate.annotations.Any;
+import org.hibernate.annotations.AnyDiscriminator;
+import org.hibernate.annotations.AnyDiscriminatorValue;
+import org.hibernate.annotations.AnyKeyJavaClass;
-import javax.persistence.*;
+import jakarta.persistence.*;
import java.io.Serializable;
@Entity
@@ -14,10 +17,12 @@ public class EntityDescription implements Serializable {
private String description;
- @Any(
- metaDef = "EntityDescriptionMetaDef",
- metaColumn = @Column(name = "entity_type")
- )
+ @Any
+ @AnyDiscriminator(DiscriminatorType.STRING)
+ @AnyDiscriminatorValue(discriminator = "S", entity = Employee.class)
+ @AnyDiscriminatorValue(discriminator = "I", entity = Phone.class)
+ @AnyKeyJavaClass(Integer.class)
+ @Column(name = "entity_type")
@JoinColumn(name = "entity_id")
private Serializable entity;
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java
index d923bda5de..e173aa8b47 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/Phone.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.pojo;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
import java.io.Serializable;
@Entity
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java
index f3fe095cae..0c022884eb 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/TemporalValues.java
@@ -1,7 +1,6 @@
package com.baeldung.hibernate.pojo;
-import javax.persistence.*;
-import java.io.Serializable;
+import jakarta.persistence.*;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
@@ -9,7 +8,7 @@ import java.time.*;
import java.util.Calendar;
@Entity
-public class TemporalValues implements Serializable {
+public class TemporalValues {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@@ -48,7 +47,7 @@ public class TemporalValues implements Serializable {
private java.time.LocalDate localDate;
@Basic
- private java.time.LocalTime localTime;
+ private java.time.LocalTime localTimeField;
@Basic
private java.time.OffsetTime offsetTime;
@@ -146,11 +145,11 @@ public class TemporalValues implements Serializable {
}
public LocalTime getLocalTime() {
- return localTime;
+ return localTimeField;
}
public void setLocalTime(LocalTime localTime) {
- this.localTime = localTime;
+ this.localTimeField = localTime;
}
public OffsetTime getOffsetTime() {
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java
index 6fe7f915fc..c44a542b60 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Animal.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.pojo.inheritance;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Inheritance;
-import javax.persistence.InheritanceType;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Inheritance;
+import jakarta.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java
index fa6e1b4bef..707e387866 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Bag.java
@@ -1,7 +1,7 @@
package com.baeldung.hibernate.pojo.inheritance;
-import javax.persistence.Entity;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
import org.hibernate.annotations.Polymorphism;
import org.hibernate.annotations.PolymorphismType;
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java
index 36ca8dd77c..286a30cc14 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Book.java
@@ -1,7 +1,7 @@
package com.baeldung.hibernate.pojo.inheritance;
-import javax.persistence.DiscriminatorValue;
-import javax.persistence.Entity;
+import jakarta.persistence.DiscriminatorValue;
+import jakarta.persistence.Entity;
@Entity
@DiscriminatorValue("1")
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java
index 49d1f7749a..987e299625 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Car.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.pojo.inheritance;
-import javax.persistence.Entity;
+import jakarta.persistence.Entity;
@Entity
public class Car extends Vehicle {
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Laptop.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Laptop.java
new file mode 100644
index 0000000000..cced365d78
--- /dev/null
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Laptop.java
@@ -0,0 +1,39 @@
+package com.baeldung.hibernate.pojo.inheritance;
+
+import org.hibernate.annotations.Polymorphism;
+import org.hibernate.annotations.PolymorphismType;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+
+@Entity
+@Polymorphism(type = PolymorphismType.IMPLICIT)
+public class Laptop implements Item {
+
+ @Id
+ private Long id;
+
+ private String type;
+
+ public Laptop(Long id, String type) {
+ this.id = id;
+ this.type = type;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+}
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java
index 9a6bce16cf..96958c6e28 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyEmployee.java
@@ -1,6 +1,6 @@
package com.baeldung.hibernate.pojo.inheritance;
-import javax.persistence.Entity;
+import jakarta.persistence.Entity;
@Entity
public class MyEmployee extends Person {
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java
index 13f04d8904..62214fc16e 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/MyProduct.java
@@ -1,13 +1,11 @@
package com.baeldung.hibernate.pojo.inheritance;
-import javax.persistence.DiscriminatorColumn;
-import javax.persistence.DiscriminatorType;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Inheritance;
-import javax.persistence.InheritanceType;
-
-import org.hibernate.annotations.DiscriminatorFormula;
+import jakarta.persistence.DiscriminatorColumn;
+import jakarta.persistence.DiscriminatorType;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Inheritance;
+import jakarta.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java
index 32b77e52af..2382cab405 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pen.java
@@ -1,7 +1,7 @@
package com.baeldung.hibernate.pojo.inheritance;
-import javax.persistence.DiscriminatorValue;
-import javax.persistence.Entity;
+import jakarta.persistence.DiscriminatorValue;
+import jakarta.persistence.Entity;
@Entity
@DiscriminatorValue("2")
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java
index 99084b88af..9bf8ac254c 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Person.java
@@ -1,7 +1,7 @@
package com.baeldung.hibernate.pojo.inheritance;
-import javax.persistence.Id;
-import javax.persistence.MappedSuperclass;
+import jakarta.persistence.Id;
+import jakarta.persistence.MappedSuperclass;
@MappedSuperclass
public class Person {
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java
index 870b3cd684..b359eb3a21 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Pet.java
@@ -1,7 +1,7 @@
package com.baeldung.hibernate.pojo.inheritance;
-import javax.persistence.Entity;
-import javax.persistence.PrimaryKeyJoinColumn;
+import jakarta.persistence.Entity;
+import jakarta.persistence.PrimaryKeyJoinColumn;
@Entity
@PrimaryKeyJoinColumn(name = "petId")
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java
index b2a920573e..9bdde8c33b 100644
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java
+++ b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/inheritance/Vehicle.java
@@ -1,9 +1,9 @@
package com.baeldung.hibernate.pojo.inheritance;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.Inheritance;
-import javax.persistence.InheritanceType;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.Inheritance;
+import jakarta.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
diff --git a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java b/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java
deleted file mode 100644
index 992cda7c1d..0000000000
--- a/persistence-modules/hibernate-mapping/src/main/java/com/baeldung/hibernate/pojo/package-info.java
+++ /dev/null
@@ -1,9 +0,0 @@
-@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int",
- metaValues = {
- @MetaValue(value = "Employee", targetEntity = Employee.class),
- @MetaValue(value = "Phone", targetEntity = Phone.class)
- })
-package com.baeldung.hibernate.pojo;
-
-import org.hibernate.annotations.AnyMetaDef;
-import org.hibernate.annotations.MetaValue;
\ No newline at end of file
diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java
index 7a112200b5..833c5cc3ff 100644
--- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java
+++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/DynamicMappingIntegrationTest.java
@@ -119,8 +119,8 @@ public class DynamicMappingIntegrationTest {
assertThat(employees).hasSize(2);
- Employee employee = session.get(Employee.class, 1);
- assertThat(employee.getGrossIncome()).isEqualTo(10_000);
+ Employee employee = session.get(Employee.class, 2);
+ assertThat(employee.getGrossIncome()).isEqualTo(12_000);
session.disableFilter("incomeLevelFilter");
employees = session.createQuery("from Employee").getResultList();
diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java
index 0f35dbb8af..7f4cac141c 100644
--- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java
+++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/InheritanceMappingIntegrationTest.java
@@ -13,6 +13,7 @@ import org.junit.Test;
import com.baeldung.hibernate.pojo.inheritance.Bag;
import com.baeldung.hibernate.pojo.inheritance.Book;
import com.baeldung.hibernate.pojo.inheritance.Car;
+import com.baeldung.hibernate.pojo.inheritance.Laptop;
import com.baeldung.hibernate.pojo.inheritance.MyEmployee;
import com.baeldung.hibernate.pojo.inheritance.Pen;
import com.baeldung.hibernate.pojo.inheritance.Pet;
@@ -81,9 +82,12 @@ public class InheritanceMappingIntegrationTest {
public void givenSubclasses_whenQueryNonMappedInterface_thenOk() {
Bag bag = new Bag(1, "large");
session.save(bag);
+
+ Laptop laptop = new Laptop(1L, "Dell");
+ session.save(laptop);
assertThat(session.createQuery("from com.baeldung.hibernate.pojo.inheritance.Item")
.getResultList()
- .size()).isEqualTo(0);
+ .size()).isEqualTo(1);
}
}
diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java
index 930bea60c5..6a9a4f095b 100644
--- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java
+++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/basicannotation/BasicAnnotationIntegrationTest.java
@@ -2,7 +2,7 @@ package com.baeldung.hibernate.basicannotation;
import java.io.IOException;
-import javax.persistence.PersistenceException;
+import jakarta.persistence.PersistenceException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java
index 0f2a0403e9..17212173ec 100644
--- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java
+++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserAdditionalValidationUnitTest.java
@@ -7,13 +7,12 @@ import java.math.BigDecimal;
import java.time.Duration;
import java.util.Set;
-import javax.money.CurrencyContextBuilder;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
-import javax.validation.ValidatorFactory;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
+import jakarta.validation.ValidatorFactory;
import org.hibernate.validator.constraints.CodePointLength;
import org.hibernate.validator.constraints.CreditCardNumber;
@@ -21,12 +20,10 @@ import org.hibernate.validator.constraints.Currency;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.LuhnCheck;
import org.hibernate.validator.constraints.Range;
-import org.hibernate.validator.constraints.SafeHtml;
import org.hibernate.validator.constraints.ScriptAssert;
import org.hibernate.validator.constraints.URL;
import org.hibernate.validator.constraints.time.DurationMax;
import org.hibernate.validator.constraints.time.DurationMin;
-import org.javamoney.moneta.CurrencyUnitBuilder;
import org.javamoney.moneta.Money;
import org.junit.BeforeClass;
import org.junit.Test;
diff --git a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserValidationUnitTest.java b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserValidationUnitTest.java
index e39f324856..495ad657be 100644
--- a/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserValidationUnitTest.java
+++ b/persistence-modules/hibernate-mapping/src/test/java/com/baeldung/hibernate/validation/UserValidationUnitTest.java
@@ -2,11 +2,11 @@ package com.baeldung.hibernate.validation;
import static org.junit.Assert.assertEquals;
import java.util.Set;
-import javax.persistence.PersistenceException;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
-import javax.validation.ValidatorFactory;
+import jakarta.persistence.PersistenceException;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
+import jakarta.validation.ValidatorFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Before;
diff --git a/persistence-modules/hibernate-queries/README.md b/persistence-modules/hibernate-queries/README.md
index f5cba1aa6f..9e6c52d6dc 100644
--- a/persistence-modules/hibernate-queries/README.md
+++ b/persistence-modules/hibernate-queries/README.md
@@ -12,3 +12,4 @@ This module contains articles about use of Queries in Hibernate.
- [Hibernate’s addScalar() Method](https://www.baeldung.com/hibernate-addscalar)
- [Distinct Queries in HQL](https://www.baeldung.com/java-hql-distinct)
- [JPA and Hibernate – Criteria vs. JPQL vs. HQL Query](https://www.baeldung.com/jpql-hql-criteria-query)
+- [Database Keywords as Columns in Hibernate Entities](https://www.baeldung.com/java-hibernate-db-keywords-as-columns)
diff --git a/persistence-modules/hibernate-queries/pom.xml b/persistence-modules/hibernate-queries/pom.xml
index 68a46b82b1..bb60c7b83a 100644
--- a/persistence-modules/hibernate-queries/pom.xml
+++ b/persistence-modules/hibernate-queries/pom.xml
@@ -85,15 +85,21 @@
${testcontainers.mysql.version}
test
+
+ io.hypersistence
+ hypersistence-utils-hibernate-60
+ 3.3.1
+
- 5.0.2.RELEASE
- 1.10.6.RELEASE
+ 6.0.6
+ 3.0.3
9.0.0.M26
- 6.0.6
- 2.2.3
+ 8.0.32
+ 2.6.0
2.1.214
+ 6.1.7.Final
1.17.6
diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java
index 8771e02e0b..9041c6727c 100644
--- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java
+++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/model/Employee.java
@@ -1,7 +1,7 @@
package com.baeldung.hibernate.criteria.model;
import java.io.Serializable;
-import javax.persistence.Entity;
+import jakarta.persistence.Entity;
@org.hibernate.annotations.NamedQueries({
@org.hibernate.annotations.NamedQuery(name = "Employee_findByEmployeeId", query = "from Employee where id = :employeeId"),
diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java
index 248f64474a..2b782c2a1d 100644
--- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java
+++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/ApplicationView.java
@@ -12,10 +12,10 @@ package com.baeldung.hibernate.criteria.view;
import java.util.List;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.Predicate;
-import javax.persistence.criteria.Root;
+import jakarta.persistence.criteria.CriteriaBuilder;
+import jakarta.persistence.criteria.CriteriaQuery;
+import jakarta.persistence.criteria.Predicate;
+import jakarta.persistence.criteria.Root;
import org.hibernate.Session;
import org.hibernate.query.Query;
diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java
index f8c525611b..9303fd893e 100644
--- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java
+++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteria/view/EmployeeCriteriaQueries.java
@@ -3,9 +3,9 @@ package com.baeldung.hibernate.criteria.view;
import com.baeldung.hibernate.criteria.model.Employee;
import com.baeldung.hibernate.criteria.util.HibernateUtil;
import java.util.List;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.Root;
+import jakarta.persistence.criteria.CriteriaBuilder;
+import jakarta.persistence.criteria.CriteriaQuery;
+import jakarta.persistence.criteria.Root;
import org.hibernate.Session;
import org.hibernate.query.Query;
diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java
index 314e7ca557..af6b561091 100644
--- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java
+++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/criteriaquery/Student.java
@@ -1,11 +1,11 @@
package com.baeldung.hibernate.criteriaquery;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
@Entity
@Table(name = "students")
diff --git a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java
index 56be9e693f..58d8e8628a 100644
--- a/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java
+++ b/persistence-modules/hibernate-queries/src/main/java/com/baeldung/hibernate/customtypes/LocalDateStringJavaDescriptor.java
@@ -1,14 +1,15 @@
package com.baeldung.hibernate.customtypes;
-import org.hibernate.type.LocalDateType;
-import org.hibernate.type.descriptor.WrapperOptions;
-import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
-import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan;
-import org.hibernate.type.descriptor.java.MutabilityPlan;
import java.time.LocalDate;
+import java.time.format.DateTimeFormatter;
-public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor {
+import org.hibernate.type.descriptor.WrapperOptions;
+import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan;
+
+import io.hypersistence.utils.hibernate.type.array.internal.AbstractArrayTypeDescriptor;
+
+public class LocalDateStringJavaDescriptor extends AbstractArrayTypeDescriptor {
public static final LocalDateStringJavaDescriptor INSTANCE = new LocalDateStringJavaDescriptor();
@@ -18,12 +19,12 @@ public class LocalDateStringJavaDescriptor extends AbstractTypeDescriptor implements DiscriminatorType {
+public class LocalDateStringType extends AbstractSingleColumnStandardBasicType {
public static final LocalDateStringType INSTANCE = new LocalDateStringType();
public LocalDateStringType() {
- super(VarcharTypeDescriptor.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
+ super(VarcharJdbcType.INSTANCE, LocalDateStringJavaDescriptor.INSTANCE);
}
@Override
@@ -21,14 +19,12 @@ public class LocalDateStringType extends AbstractSingleColumnStandardBasicTypeHibernate EntityManager Demo
true
-
+
-
-
-
-
+
+
+
+
\ No newline at end of file
diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java
index a1f88f3387..c405eb9ebd 100644
--- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java
+++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteria/HibernateCriteriaIntegrationTest.java
@@ -15,10 +15,10 @@ import com.baeldung.hibernate.criteria.model.Item;
import com.baeldung.hibernate.criteria.util.HibernateUtil;
import com.baeldung.hibernate.criteria.view.ApplicationView;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaDelete;
-import javax.persistence.criteria.CriteriaUpdate;
-import javax.persistence.criteria.Root;
+import jakarta.persistence.criteria.CriteriaBuilder;
+import jakarta.persistence.criteria.CriteriaDelete;
+import jakarta.persistence.criteria.CriteriaUpdate;
+import jakarta.persistence.criteria.Root;
public class HibernateCriteriaIntegrationTest {
diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java
index cedba412d9..bfcb4301a7 100644
--- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java
+++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/criteriaquery/TypeSafeCriteriaIntegrationTest.java
@@ -1,6 +1,5 @@
package com.baeldung.hibernate.criteriaquery;
-import com.baeldung.hibernate.criteriaquery.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
@@ -10,9 +9,9 @@ import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.Root;
+import jakarta.persistence.criteria.CriteriaBuilder;
+import jakarta.persistence.criteria.CriteriaQuery;
+import jakarta.persistence.criteria.Root;
import java.io.IOException;
import java.util.List;
diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java
index 799439a51b..3ce384741f 100644
--- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java
+++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/distinct/entities/DistinctHqlQueriesUnitTest.java
@@ -8,7 +8,6 @@ import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.hibernate.annotations.QueryHints;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -45,12 +44,12 @@ public class DistinctHqlQueriesUnitTest {
}
@Test
- public void whenExecutingSelectQuery_thereWillBeDuplicates() {
+ public void whenExecutingSelectQuery_thereTheInsertedPosts() {
String hql = "SELECT p FROM Post p LEFT JOIN FETCH p.comments";
List posts = session.createQuery(hql, Post.class)
.getResultList();
- assertThat(posts).hasSize(3);
+ assertThat(posts).hasSize(1);
}
@Test
@@ -68,8 +67,8 @@ public class DistinctHqlQueriesUnitTest {
@Test
public void whenExecutingSelectDistinctQueryWithHint_thereShouldBeNoDuplicates() {
String hql = "SELECT DISTINCT p FROM Post p LEFT JOIN FETCH p.comments";
+ // From Hibernate ORM 6, distinct is always passed to the SQL query and the flag QueryHints#HINT_PASS_DISTINCT_THROUGH has been removed.
List posts = session.createQuery(hql, Post.class)
- .setHint(QueryHints.PASS_DISTINCT_THROUGH, false)
.getResultList();
assertThat(posts).hasSize(1)
diff --git a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationIntegrationTest.java b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationManualTest.java
similarity index 78%
rename from persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationIntegrationTest.java
rename to persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationManualTest.java
index 4282da3de4..780a0fd77e 100644
--- a/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationIntegrationTest.java
+++ b/persistence-modules/hibernate-queries/src/test/java/com/baeldung/hibernate/keywords/HibernateKeywordsApplicationManualTest.java
@@ -3,8 +3,6 @@ package com.baeldung.hibernate.keywords;
import static java.util.UUID.randomUUID;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
-import javax.persistence.PersistenceException;
-
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
@@ -13,7 +11,17 @@ import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
-public class HibernateKeywordsApplicationIntegrationTest {
+import jakarta.persistence.PersistenceException;
+
+/**
+ * This test suite uses testcontainers library and therefore
+ * requires Docker installed on the local system to be able to run it.
+ *
+ * When docker is available on the local machine it can be run either by:
+ * - running it from your favorite IDE
+ * - or through `mvn test -Dtest=HibernateKeywordsApplicationManualTest`
+ */
+public class HibernateKeywordsApplicationManualTest {
private static SessionFactory sessionFactory;
private Session session;
diff --git a/persistence-modules/java-mongodb-3/README.md b/persistence-modules/java-mongodb-3/README.md
index 4296c96ed8..48fc211370 100644
--- a/persistence-modules/java-mongodb-3/README.md
+++ b/persistence-modules/java-mongodb-3/README.md
@@ -4,3 +4,4 @@
- [Query Documents using Document ID in MongoDB](https://www.baeldung.com/mongodb-query-documents-id)
- [Insert Array Inside an Object in MongoDB](https://www.baeldung.com/java-mongodb-document-insert-array)
- [Guide to Filters in MongoDB](https://www.baeldung.com/java-mongodb-filters)
+- [Add Field to an Existing MongoDB Bson Filter in Java](https://www.baeldung.com/java-mongodb-add-field-bson-filter)
diff --git a/persistence-modules/java-mongodb-3/src/main/java/com/baeldung/mongo/insert/InsertFieldIntoFilter.java b/persistence-modules/java-mongodb-3/src/main/java/com/baeldung/mongo/insert/InsertFieldIntoFilter.java
new file mode 100644
index 0000000000..aabc6aef18
--- /dev/null
+++ b/persistence-modules/java-mongodb-3/src/main/java/com/baeldung/mongo/insert/InsertFieldIntoFilter.java
@@ -0,0 +1,74 @@
+package com.baeldung.mongo.insert;
+
+import com.mongodb.MongoClient;
+import com.mongodb.client.FindIterable;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoCursor;
+import com.mongodb.client.MongoDatabase;
+import org.bson.BsonDocument;
+import org.bson.Document;
+import org.bson.conversions.Bson;
+
+import static com.mongodb.client.model.Filters.*;
+
+public class InsertFieldIntoFilter {
+
+ private static MongoClient mongoClient;
+ private static MongoDatabase database;
+ private static MongoCollection collection;
+ private static String collectionName;
+ private static String databaseName;
+
+ public static void setUp() {
+ if (mongoClient == null) {
+ mongoClient = new MongoClient("localhost", 27017);
+
+ databaseName = "baeldung";
+ collectionName = "pet";
+
+ database = mongoClient.getDatabase(databaseName);
+ collection = database.getCollection(collectionName);
+ }
+ }
+
+ public static void addFieldToExistingBsonFilter() {
+
+ Bson existingFilter = and(eq("type", "Dog"), eq("gender", "Male"));
+
+ Bson newFilter = and(existingFilter, gt("age", 5));
+ FindIterable documents = collection.find(newFilter);
+
+ MongoCursor cursor = documents.iterator();
+ while (cursor.hasNext()) {
+ System.out.println(cursor.next());
+ }
+ }
+
+
+ public static void addFieldToExistingBsonFilterUsingBsonDocument() {
+
+ Bson existingFilter = eq("type", "Dog");
+ BsonDocument existingBsonDocument = existingFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
+
+ Bson newFilter = gt("age", 5);
+ BsonDocument newBsonDocument = newFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
+
+ existingBsonDocument.append("age", newBsonDocument.get("age"));
+
+ FindIterable documents = collection.find(existingBsonDocument);
+
+ MongoCursor cursor = documents.iterator();
+ while (cursor.hasNext()) {
+ System.out.println(cursor.next());
+ }
+ }
+
+ public static void main(String args[]) {
+
+ setUp();
+
+ addFieldToExistingBsonFilter();
+
+ addFieldToExistingBsonFilterUsingBsonDocument();
+ }
+}
diff --git a/persistence-modules/java-mongodb-3/src/test/java/com/baeldung/mongo/insert/InsertFieldIntoFilterLiveTest.java b/persistence-modules/java-mongodb-3/src/test/java/com/baeldung/mongo/insert/InsertFieldIntoFilterLiveTest.java
new file mode 100644
index 0000000000..be4ed260d9
--- /dev/null
+++ b/persistence-modules/java-mongodb-3/src/test/java/com/baeldung/mongo/insert/InsertFieldIntoFilterLiveTest.java
@@ -0,0 +1,73 @@
+package com.baeldung.mongo.insert;
+
+import com.baeldung.mongo.find.FindOperationLiveTest;
+import com.mongodb.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoCursor;
+import com.mongodb.client.MongoDatabase;
+import org.bson.BsonDocument;
+import org.bson.Document;
+import org.bson.conversions.Bson;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+
+import static com.mongodb.client.model.Filters.*;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+public class InsertFieldIntoFilterLiveTest {
+
+ private static MongoClient mongoClient;
+ private static MongoDatabase database;
+ private static MongoCollection collection;
+ private static final String DATASET_JSON = "/pet.json";
+
+ @BeforeClass
+ public static void setUp() throws IOException {
+ if (mongoClient == null) {
+ mongoClient = new MongoClient("localhost", 27017);
+
+ database = mongoClient.getDatabase("baeldung");
+ collection = database.getCollection("pet");
+
+ collection.drop();
+
+ InputStream is = FindOperationLiveTest.class.getResourceAsStream(DATASET_JSON);
+ BufferedReader reader = new BufferedReader(new InputStreamReader(is));
+ reader.lines()
+ .forEach(line -> collection.insertOne(Document.parse(line)));
+ reader.close();
+ }
+ }
+
+ @Test
+ public void givenPetCollection_whenFetchingAfterAddingFieldToFilter_thenFindMatchingDocuments() {
+ Bson existingFilter = and(eq("type", "Dog"), eq("gender", "Male"));
+
+ Bson newFilter = and(existingFilter, gt("age", 5));
+ MongoCursor cursor = collection.find(newFilter).iterator();
+
+ assertNotNull(cursor);
+ assertTrue(cursor.hasNext());
+ }
+
+ @Test
+ public void givenPetCollection_whenFetchingAfterAddingFieldToFilterUsingBsonDocument_thenFindMatchingDocuments() {
+ Bson existingFilter = eq("type", "Dog");
+ BsonDocument existingBsonDocument = existingFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
+
+ Bson newFilter = gt("age", 5);
+ BsonDocument newBsonDocument = newFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
+
+ existingBsonDocument.append("age", newBsonDocument.get("age"));
+ MongoCursor cursor = collection.find(existingBsonDocument).iterator();
+
+ assertNotNull(cursor);
+ assertTrue(cursor.hasNext());
+ }
+}
diff --git a/persistence-modules/java-mongodb-3/src/test/resources/pet.json b/persistence-modules/java-mongodb-3/src/test/resources/pet.json
new file mode 100644
index 0000000000..b31cf16718
--- /dev/null
+++ b/persistence-modules/java-mongodb-3/src/test/resources/pet.json
@@ -0,0 +1,3 @@
+{"petId":"P1","name":"Tom","age":3,"type":"Cat","gender":"Female"}
+{"petId":"P2","name":"Max","age":4,"type":"Dog","gender":"Male"}
+{"petId":"P3","name":"Milo","age":8,"type":"Dog","gender":"Male"}
\ No newline at end of file
diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml
index 2e366d8368..844b9e5bcd 100644
--- a/persistence-modules/java-mongodb/pom.xml
+++ b/persistence-modules/java-mongodb/pom.xml
@@ -14,20 +14,14 @@
-
- de.flapdoodle.embedmongo
- de.flapdoodle.embedmongo
- ${flapdoodle.version}
- test
-
org.mongodb
- mongo-java-driver
+ mongodb-driver-sync
${mongo.version}
dev.morphia.morphia
- core
+ morphia-core
${morphia.version}
@@ -42,12 +36,18 @@
${testcontainers.version}
test
+
+ de.flapdoodle.embed
+ de.flapdoodle.embed.mongo
+ ${flapdoodle.version}
+ test
+
- 3.12.1
- 1.11
- 1.5.3
+ 4.8.2
+ 4.4.1
+ 2.0.0
\ No newline at end of file
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/MongoExample.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/MongoExample.java
index 9af1e1f6a4..ef4003fa82 100644
--- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/MongoExample.java
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/MongoExample.java
@@ -1,53 +1,64 @@
package com.baeldung;
-import com.mongodb.BasicDBObject;
-import com.mongodb.DB;
-import com.mongodb.DBCollection;
-import com.mongodb.DBCursor;
-import com.mongodb.MongoClient;
+import java.util.ArrayList;
+
+import org.bson.Document;
+
+import com.mongodb.client.FindIterable;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoCursor;
+import com.mongodb.client.MongoDatabase;
public class MongoExample {
public static void main(String[] args) {
+ try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
- MongoClient mongoClient = new MongoClient("localhost", 27017);
+ MongoDatabase database = mongoClient.getDatabase("myMongoDb");
- DB database = mongoClient.getDB("myMongoDb");
+ // print existing databases
+ mongoClient.listDatabaseNames().forEach(System.out::println);
- // print existing databases
- mongoClient.getDatabaseNames().forEach(System.out::println);
+ boolean collectionExists = mongoClient.getDatabase("myMongoDb").listCollectionNames()
+ .into(new ArrayList<>()).contains("customers");
+ if (!collectionExists) {
+ database.createCollection("customers");
+ }
- database.createCollection("customers", null);
+ // print all collections in customers database
+ database.listCollectionNames().forEach(System.out::println);
- // print all collections in customers database
- database.getCollectionNames().forEach(System.out::println);
+ // create data
+ MongoCollection collection = database.getCollection("customers");
+ Document document = new Document();
+ document.put("name", "Shubham");
+ document.put("company", "Baeldung");
+ collection.insertOne(document);
- // create data
- DBCollection collection = database.getCollection("customers");
- BasicDBObject document = new BasicDBObject();
- document.put("name", "Shubham");
- document.put("company", "Baeldung");
- collection.insert(document);
+ // update data
+ Document query = new Document();
+ query.put("name", "Shubham");
+ Document newDocument = new Document();
+ newDocument.put("name", "John");
+ Document updateObject = new Document();
+ updateObject.put("$set", newDocument);
+ collection.updateOne(query, updateObject);
- // update data
- BasicDBObject query = new BasicDBObject();
- query.put("name", "Shubham");
- BasicDBObject newDocument = new BasicDBObject();
- newDocument.put("name", "John");
- BasicDBObject updateObject = new BasicDBObject();
- updateObject.put("$set", newDocument);
- collection.update(query, updateObject);
+ // read data
+ Document searchQuery = new Document();
+ searchQuery.put("name", "John");
+ FindIterable cursor = collection.find(searchQuery);
+ try (final MongoCursor cursorIterator = cursor.cursor()) {
+ while (cursorIterator.hasNext()) {
+ System.out.println(cursorIterator.next());
+ }
+ }
- // read data
- BasicDBObject searchQuery = new BasicDBObject();
- searchQuery.put("name", "John");
- DBCursor cursor = collection.find(searchQuery);
- while (cursor.hasNext()) {
- System.out.println(cursor.next());
+ // delete data
+ Document deleteQuery = new Document();
+ deleteQuery.put("name", "John");
+ collection.deleteOne(deleteQuery);
}
-
- // delete data
- BasicDBObject deleteQuery = new BasicDBObject();
- deleteQuery.put("name", "John");
- collection.remove(deleteQuery);
}
}
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java
index 44e4ecb539..c57f759a95 100644
--- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/bsontojson/Book.java
@@ -1,11 +1,9 @@
package com.baeldung.bsontojson;
-import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
-import dev.morphia.annotations.Embedded;
import dev.morphia.annotations.Entity;
import dev.morphia.annotations.Field;
import dev.morphia.annotations.Id;
@@ -25,7 +23,7 @@ public class Book {
@Property
private String title;
private String author;
- @Embedded
+
private Publisher publisher;
@Property("price")
private double cost;
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/CollectionExistence.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/CollectionExistence.java
index 074913af4e..c94a7c042a 100644
--- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/CollectionExistence.java
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/CollectionExistence.java
@@ -4,8 +4,8 @@ import java.util.ArrayList;
import org.bson.Document;
-import com.mongodb.DB;
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
@@ -18,7 +18,7 @@ public class CollectionExistence {
public static void setUp() {
if (mongoClient == null) {
- mongoClient = new MongoClient("localhost", 27017);
+ mongoClient = MongoClients.create("mongodb://localhost:27017");
}
databaseName = "baeldung";
testCollectionName = "student";
@@ -26,9 +26,9 @@ public class CollectionExistence {
public static void collectionExistsSolution() {
- DB db = mongoClient.getDB(databaseName);
+ MongoDatabase db = mongoClient.getDatabase(databaseName);
- System.out.println("collectionName " + testCollectionName + db.collectionExists(testCollectionName));
+ System.out.println("collectionName " + testCollectionName + db.listCollectionNames().into(new ArrayList<>()).contains(testCollectionName));
}
@@ -62,7 +62,7 @@ public class CollectionExistence {
MongoCollection collection = database.getCollection(testCollectionName);
- System.out.println(collection.count());
+ System.out.println(collection.countDocuments());
}
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java
index 74279bbfcd..5ccabc9326 100644
--- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/objectid/RetrieveIdExample.java
@@ -5,7 +5,8 @@ import java.util.Date;
import org.bson.Document;
import org.bson.types.ObjectId;
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
@@ -13,7 +14,7 @@ public class RetrieveIdExample {
public static void main(String[] args) {
- try ( MongoClient mongoClient = new MongoClient("localhost", 27017) ) {
+ try ( MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017") ) {
MongoDatabase database = mongoClient.getDatabase("myMongoDb");
MongoCollection collection = database.getCollection("example");
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java
index ebc56cbfd0..9ad62bc1c7 100644
--- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/MultipleFieldsExample.java
@@ -3,7 +3,8 @@ package com.baeldung.mongo.update;
import org.bson.Document;
import com.mongodb.BasicDBObject;
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.UpdateResult;
@@ -16,7 +17,7 @@ public class MultipleFieldsExample {
// Connect to cluster (default is localhost:27017)
//
- MongoClient mongoClient = new MongoClient("localhost", 27017);
+ MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017");
MongoDatabase database = mongoClient.getDatabase("baeldung");
MongoCollection collection = database.getCollection("employee");
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateFields.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateFields.java
index a1b051e74c..594d535245 100644
--- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateFields.java
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateFields.java
@@ -2,7 +2,8 @@ package com.baeldung.mongo.update;
import org.bson.Document;
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
@@ -83,10 +84,9 @@ public class UpdateFields {
public static void setup() {
if (mongoClient == null) {
- mongoClient = new MongoClient("localhost", 27017);
+ mongoClient = MongoClients.create("mongodb://localhost:27017");
database = mongoClient.getDatabase("baeldung");
collection = database.getCollection("student");
-
}
}
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java
index 96dd086ed7..08fdce68d6 100644
--- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/mongo/update/UpdateMultipleFields.java
@@ -2,7 +2,8 @@ package com.baeldung.mongo.update;
import org.bson.Document;
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
@@ -16,19 +17,19 @@ public class UpdateMultipleFields {
//
// Connect to cluster
//
+ try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27007");) {
+ MongoDatabase database = mongoClient.getDatabase("baeldung");
+ MongoCollection collection = database.getCollection("employee");
- MongoClient mongoClient = new MongoClient("localhost", 27007);
- MongoDatabase database = mongoClient.getDatabase("baeldung");
- MongoCollection collection = database.getCollection("employee");
+ //
+ // Update query
+ //
- //
- // Update query
- //
+ UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
- UpdateResult updateResult = collection.updateMany(Filters.eq("employee_id", 794875), Updates.combine(Updates.set("department_id", 4), Updates.set("job", "Sales Manager")));
-
- System.out.println("updateResult:- " + updateResult);
- System.out.println("updateResult:- " + updateResult.getModifiedCount());
+ System.out.println("updateResult:- " + updateResult);
+ System.out.println("updateResult:- " + updateResult.getModifiedCount());
+ }
}
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java
index 4ed2ab8580..b79550dcd1 100644
--- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/morphia/domain/Book.java
@@ -1,6 +1,5 @@
package com.baeldung.morphia.domain;
-import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
@@ -25,7 +24,7 @@ public class Book {
@Property
private String title;
private String author;
- @Embedded
+
private Publisher publisher;
@Property("price")
private double cost;
diff --git a/persistence-modules/java-mongodb/src/main/java/com/baeldung/tagging/TagRepository.java b/persistence-modules/java-mongodb/src/main/java/com/baeldung/tagging/TagRepository.java
index d27d48c743..44b5d461bc 100644
--- a/persistence-modules/java-mongodb/src/main/java/com/baeldung/tagging/TagRepository.java
+++ b/persistence-modules/java-mongodb/src/main/java/com/baeldung/tagging/TagRepository.java
@@ -10,8 +10,9 @@ import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
-import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
@@ -45,7 +46,7 @@ public class TagRepository implements Closeable {
* Instantiates a new TagRepository by opening the DB connection.
*/
public TagRepository() {
- mongoClient = new MongoClient("localhost", 27018);
+ mongoClient = MongoClients.create("mongodb://localhost:27018");
MongoDatabase database = mongoClient.getDatabase("blog");
collection = database.getCollection("posts");
}
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppLiveTest.java
index 7692a37d03..2abecdbd48 100644
--- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppLiveTest.java
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/AppLiveTest.java
@@ -2,71 +2,50 @@ package com.baeldung;
import static org.junit.Assert.assertEquals;
-import org.junit.After;
-import org.junit.Before;
+import org.bson.Document;
import org.junit.Test;
-import com.mongodb.BasicDBObject;
-import com.mongodb.DB;
-import com.mongodb.DBCollection;
-import com.mongodb.DBCursor;
-import com.mongodb.Mongo;
+import com.mongodb.client.FindIterable;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoCursor;
+import com.mongodb.client.MongoDatabase;
-import de.flapdoodle.embedmongo.MongoDBRuntime;
-import de.flapdoodle.embedmongo.MongodExecutable;
-import de.flapdoodle.embedmongo.MongodProcess;
-import de.flapdoodle.embedmongo.config.MongodConfig;
-import de.flapdoodle.embedmongo.distribution.Version;
-import de.flapdoodle.embedmongo.runtime.Network;
+import de.flapdoodle.embed.mongo.distribution.Version;
+import de.flapdoodle.embed.mongo.transitions.Mongod;
+import de.flapdoodle.embed.mongo.transitions.RunningMongodProcess;
+import de.flapdoodle.reverse.TransitionWalker;
public class AppLiveTest {
private static final String DB_NAME = "myMongoDb";
- private MongodExecutable mongodExe;
- private MongodProcess mongod;
- private Mongo mongo;
- private DB db;
- private DBCollection collection;
-
- @Before
- public void setup() throws Exception {
- // Creating Mongodbruntime instance
- MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance();
-
- // Creating MongodbExecutable
- mongodExe = runtime.prepare(new MongodConfig(Version.V2_0_1, 12345, Network.localhostIsIPv6()));
-
- // Starting Mongodb
- mongod = mongodExe.start();
- mongo = new Mongo("localhost", 12345);
-
- // Creating DB
- db = mongo.getDB(DB_NAME);
-
- // Creating collection Object and adding values
- collection = db.getCollection("customers");
- }
-
- @After
- public void teardown() throws Exception {
- mongod.stop();
- mongodExe.cleanup();
- }
@Test
public void testAddressPersistance() {
- BasicDBObject contact = new BasicDBObject();
- contact.put("name", "John");
- contact.put("company", "Baeldung");
+ try (TransitionWalker.ReachedState running = Mongod.instance().start(Version.V6_0_3)) {
+ try (MongoClient mongo = MongoClients.create("mongodb://" + running.current().getServerAddress().getHost() + ":" + running.current().getServerAddress().getPort())) {
+ // Creating DB
+ MongoDatabase db = mongo.getDatabase(DB_NAME);
- // Inserting document
- collection.insert(contact);
- DBCursor cursorDoc = collection.find();
- BasicDBObject contact1 = new BasicDBObject();
- while (cursorDoc.hasNext()) {
- contact1 = (BasicDBObject) cursorDoc.next();
- System.out.println(contact1);
+ // Creating collection Object and adding values
+ MongoCollection collection = db.getCollection("customers");
+
+ Document contact = new Document();
+ contact.put("name", "John");
+ contact.put("company", "Baeldung");
+
+ // Inserting document
+ collection.insertOne(contact);
+ FindIterable cursorDoc = collection.find();
+ Document contact1 = new Document();
+ final MongoCursor cursor = cursorDoc.cursor();
+ while (cursor.hasNext()) {
+ contact1 = cursor.next();
+ System.out.println(contact1);
+ }
+ assertEquals(contact1.get("name"), "John");
+ }
}
- assertEquals(contact1.get("name"), "John");
}
}
\ No newline at end of file
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java
index 0548119d7a..e2b53436b3 100644
--- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/BsonToJsonLiveTest.java
@@ -1,5 +1,6 @@
package com.baeldung.bsontojson;
+import static dev.morphia.query.experimental.filters.Filters.eq;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -14,10 +15,12 @@ import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import dev.morphia.Datastore;
+import dev.morphia.DeleteOptions;
import dev.morphia.Morphia;
public class BsonToJsonLiveTest {
@@ -27,9 +30,8 @@ public class BsonToJsonLiveTest {
@BeforeClass
public static void setUp() {
- Morphia morphia = new Morphia();
- morphia.mapPackage("com.baeldung.bsontojson");
- datastore = morphia.createDatastore(new MongoClient(), DB_NAME);
+ datastore = Morphia.createDatastore(MongoClients.create(), DB_NAME);
+ datastore.getMapper().mapPackage("com.baeldung.bsontojson");
datastore.ensureIndexes();
datastore.save(new Book()
@@ -44,25 +46,33 @@ public class BsonToJsonLiveTest {
@AfterClass
public static void tearDown() {
- datastore.delete(datastore.createQuery(Book.class));
+ datastore.find(Book.class)
+ .filter(eq("isbn", "isbn"))
+ .filter(eq("title", "title"))
+ .filter(eq("author", "author"))
+ .filter(eq("cost", "3.95"))
+ .delete(new DeleteOptions().multi(true));
}
@Test
public void givenBsonDocument_whenUsingStandardJsonTransformation_thenJsonDateIsObjectEpochTime() {
String json;
- try (MongoClient mongoClient = new MongoClient()) {
+ try (MongoClient mongoClient = MongoClients.create()) {
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
Document bson = mongoDatabase.getCollection("Books").find().first();
- json = bson.toJson();
+ json = bson.toJson(JsonWriterSettings
+ .builder()
+ .dateTimeConverter(new JSONDateFormatEpochTimeConverter())
+ .build());
}
String expectedJson = "{\"_id\": \"isbn\", " +
- "\"className\": \"com.baeldung.bsontojson.Book\", " +
+ "\"_t\": \"Book\", " +
"\"title\": \"title\", " +
"\"author\": \"author\", " +
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
- "\"name\": \"publisher\"}, " +
+ "\"_t\": \"Publisher\", \"name\": \"publisher\"}, " +
"\"price\": 3.95, " +
"\"publishDate\": {\"$date\": 1577898812000}}";
@@ -71,12 +81,11 @@ public class BsonToJsonLiveTest {
assertEquals(expectedJson, json);
}
-
@Test
public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() {
String json;
- try (MongoClient mongoClient = new MongoClient()) {
+ try (MongoClient mongoClient = MongoClients.create()) {
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
Document bson = mongoDatabase.getCollection("Books").find().first();
json = bson.toJson(JsonWriterSettings
@@ -86,11 +95,11 @@ public class BsonToJsonLiveTest {
}
String expectedJson = "{\"_id\": \"isbn\", " +
- "\"className\": \"com.baeldung.bsontojson.Book\", " +
+ "\"_t\": \"Book\", " +
"\"title\": \"title\", " +
"\"author\": \"author\", " +
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
- "\"name\": \"publisher\"}, " +
+ "\"_t\": \"Publisher\", \"name\": \"publisher\"}, " +
"\"price\": 3.95, " +
"\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}";
@@ -103,7 +112,7 @@ public class BsonToJsonLiveTest {
public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() {
String json;
- try (MongoClient mongoClient = new MongoClient()) {
+ try (MongoClient mongoClient = MongoClients.create()) {
MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
Document bson = mongoDatabase.getCollection("Books").find().first();
json = bson.toJson(JsonWriterSettings
@@ -113,11 +122,11 @@ public class BsonToJsonLiveTest {
}
String expectedJson = "{\"_id\": \"isbn\", " +
- "\"className\": \"com.baeldung.bsontojson.Book\", " +
+ "\"_t\": \"Book\", " +
"\"title\": \"title\", " +
"\"author\": \"author\", " +
"\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " +
- "\"name\": \"publisher\"}, " +
+ "\"_t\": \"Publisher\", \"name\": \"publisher\"}, " +
"\"price\": 3.95, " +
"\"publishDate\": \"2020-01-01T17:13:32Z\"}";
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JSONDateFormatEpochTimeConverter.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JSONDateFormatEpochTimeConverter.java
new file mode 100644
index 0000000000..7f3a4f936f
--- /dev/null
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/bsontojson/JSONDateFormatEpochTimeConverter.java
@@ -0,0 +1,18 @@
+package com.baeldung.bsontojson;
+
+import org.bson.json.Converter;
+import org.bson.json.StrictJsonWriter;
+
+/**
+ * Convertor to epoch time
+ */
+public class JSONDateFormatEpochTimeConverter implements Converter {
+
+ @Override
+ public void convert(Long value, StrictJsonWriter writer) {
+ writer.writeStartObject();
+ writer.writeName("$date");
+ writer.writeNumber(String.valueOf(value));
+ writer.writeEndObject();
+ }
+}
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/CollectionExistenceLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/CollectionExistenceLiveTest.java
index ad839d1219..5be97bcb25 100644
--- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/CollectionExistenceLiveTest.java
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/mongo/CollectionExistenceLiveTest.java
@@ -8,8 +8,8 @@ import org.bson.Document;
import org.junit.Before;
import org.junit.Test;
-import com.mongodb.DB;
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
@@ -22,7 +22,7 @@ public class CollectionExistenceLiveTest {
@Before
public void setup() {
if (mongoClient == null) {
- mongoClient = new MongoClient("localhost", 27017);
+ mongoClient = MongoClients.create("mongodb://localhost:27017");
databaseName = "baeldung";
testCollectionName = "student";
@@ -58,28 +58,16 @@ public class CollectionExistenceLiveTest {
}
- @Test
- public void givenCollectionExists_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
-
- DB db = mongoClient.getDB(databaseName);
- Boolean collectionStatus = db.collectionExists(testCollectionName);
-
- Boolean expectedStatus = true;
- assertEquals(expectedStatus, collectionStatus);
-
- }
-
@Test
public void givenListCollectionNames_whenCollectionAlreadyExists_thenCheckingForCollectionExistence() {
MongoDatabase database = mongoClient.getDatabase(databaseName);
boolean collectionExists = database.listCollectionNames()
- .into(new ArrayList())
+ .into(new ArrayList<>())
.contains(testCollectionName);
Boolean expectedStatus = true;
assertEquals(expectedStatus, collectionExists);
-
}
@Test
@@ -88,7 +76,7 @@ public class CollectionExistenceLiveTest {
MongoDatabase database = mongoClient.getDatabase(databaseName);
MongoCollection collection = database.getCollection(testCollectionName);
- Boolean collectionExists = collection.count() > 0 ? true : false;
+ Boolean collectionExists = collection.countDocuments() > 0 ? true : false;
Boolean expectedStatus = false;
assertEquals(expectedStatus, collectionExists);
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java
index f508c5f525..d702c691d6 100644
--- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/morphia/MorphiaIntegrationTest.java
@@ -2,39 +2,44 @@ package com.baeldung.morphia;
import static dev.morphia.aggregation.Group.grouping;
import static dev.morphia.aggregation.Group.push;
+import static dev.morphia.query.experimental.filters.Filters.eq;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Iterator;
import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
import org.bson.types.ObjectId;
import org.junit.BeforeClass;
-import org.junit.Ignore;
import org.junit.Test;
import com.baeldung.morphia.domain.Author;
import com.baeldung.morphia.domain.Book;
import com.baeldung.morphia.domain.Publisher;
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClients;
+import com.mongodb.client.model.ReturnDocument;
import dev.morphia.Datastore;
+import dev.morphia.DeleteOptions;
+import dev.morphia.ModifyOptions;
import dev.morphia.Morphia;
+import dev.morphia.query.FindOptions;
import dev.morphia.query.Query;
-import dev.morphia.query.UpdateOperations;
+import dev.morphia.query.experimental.updates.UpdateOperators;
-@Ignore
public class MorphiaIntegrationTest {
private static Datastore datastore;
private static ObjectId id = new ObjectId();
- @BeforeClass
+ @BeforeClass
public static void setUp() {
- Morphia morphia = new Morphia();
- morphia.mapPackage("com.baeldung.morphia");
- datastore = morphia.createDatastore(new MongoClient(), "library");
+ datastore = Morphia.createDatastore(MongoClients.create(), "library");
+ datastore.getMapper().mapPackage("com.baeldung.morphia");
datastore.ensureIndexes();
}
@@ -47,11 +52,11 @@ public class MorphiaIntegrationTest {
datastore.save(companionBook);
datastore.save(book);
- List books = datastore.createQuery(Book.class)
- .field("title")
- .contains("Learning Java")
- .find()
- .toList();
+ Query booksQuery = datastore.find(Book.class)
+ .filter(eq("title", "Learning Java"));
+ List books = StreamSupport
+ .stream(booksQuery.spliterator(), true)
+ .collect(Collectors.toList());
assertEquals(1, books.size());
assertEquals(book, books.get(0));
}
@@ -61,19 +66,13 @@ public class MorphiaIntegrationTest {
Publisher publisher = new Publisher(id, "Awsome Publisher");
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
datastore.save(book);
- Query query = datastore.createQuery(Book.class)
- .field("title")
- .contains("Learning Java");
- UpdateOperations updates = datastore.createUpdateOperations(Book.class)
- .inc("price", 1);
- datastore.update(query, updates);
- List books = datastore.createQuery(Book.class)
- .field("title")
- .contains("Learning Java")
- .find()
- .toList();
- assertEquals(4.95, books.get(0)
- .getCost());
+
+ final Book execute = datastore.find(Book.class)
+ .filter(eq("title", "Learning Java"))
+ .modify(UpdateOperators.set("price", 4.95))
+ .execute(new ModifyOptions().returnDocument(ReturnDocument.AFTER));
+
+ assertEquals(4.95, execute.getCost());
}
@Test
@@ -81,16 +80,12 @@ public class MorphiaIntegrationTest {
Publisher publisher = new Publisher(id, "Awsome Publisher");
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
datastore.save(book);
- Query query = datastore.createQuery(Book.class)
- .field("title")
- .contains("Learning Java");
- datastore.delete(query);
- List books = datastore.createQuery(Book.class)
- .field("title")
- .contains("Learning Java")
- .find()
- .toList();
- assertEquals(0, books.size());
+ datastore.find(Book.class)
+ .filter(eq("title", "Learning Java"))
+ .delete(new DeleteOptions().multi(true));
+ Query books = datastore.find(Book.class)
+ .filter(eq("title", "Learning Java"));
+ assertFalse(books.iterator().hasNext());
}
@Test
@@ -107,7 +102,6 @@ public class MorphiaIntegrationTest {
.out(Author.class);
assertTrue(authors.hasNext());
-
}
@Test
@@ -115,17 +109,12 @@ public class MorphiaIntegrationTest {
Publisher publisher = new Publisher(id, "Awsome Publisher");
Book book = new Book("9781565927186", "Learning Java", "Tom Kirkman", 3.95, publisher);
datastore.save(book);
- List books = datastore.createQuery(Book.class)
- .field("title")
- .contains("Learning Java")
- .project("title", true)
- .find()
- .toList();
- assertEquals(books.size(), 1);
- assertEquals("Learning Java", books.get(0)
- .getTitle());
- assertNull(books.get(0)
- .getAuthor());
+ List books = datastore.find(Book.class)
+ .filter(eq("title", "Learning Java"))
+ .iterator(new FindOptions().projection().include("title")).toList();
+ assertEquals( 1, books.size());
+ assertEquals("Learning Java", books.get(0).getTitle());
+ assertNull(books.get(0).getAuthor());
}
}
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingLiveTest.java
index edd8e22775..2a7afbd753 100644
--- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingLiveTest.java
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/tagging/TaggingLiveTest.java
@@ -100,9 +100,7 @@ public class TaggingLiveTest {
results.forEach(System.out::println);
Assert.assertEquals(1, results.size());
- results.forEach(post -> {
- Assert.assertFalse(post.getTags().contains("MongoDB"));
- });
+ results.forEach(post -> Assert.assertFalse(post.getTags().contains("MongoDB")));
}
/**
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateFieldLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateFieldLiveTest.java
index 47114e1f1a..ef725a9435 100644
--- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateFieldLiveTest.java
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateFieldLiveTest.java
@@ -8,7 +8,8 @@ import org.bson.Document;
import org.junit.BeforeClass;
import org.junit.Test;
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
@@ -27,7 +28,7 @@ public class UpdateFieldLiveTest {
@BeforeClass
public static void setup() {
if (mongoClient == null) {
- mongoClient = new MongoClient("localhost", 27017);
+ mongoClient = MongoClients.create("mongodb://localhost:27017");
db = mongoClient.getDatabase("baeldung");
collection = db.getCollection("student");
diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java
index d06de23423..19edda5870 100644
--- a/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java
+++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/update/UpdateMultipleFieldsLiveTest.java
@@ -8,7 +8,8 @@ import org.junit.Before;
import org.junit.Test;
import com.mongodb.BasicDBObject;
-import com.mongodb.MongoClient;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
@@ -23,7 +24,7 @@ public class UpdateMultipleFieldsLiveTest {
@Before
public void setup() {
if (mongoClient == null) {
- mongoClient = new MongoClient("localhost", 27017);
+ mongoClient = MongoClients.create("mongodb://localhost:27017");
db = mongoClient.getDatabase("baeldung");
collection = db.getCollection("employee");
diff --git a/persistence-modules/pom.xml b/persistence-modules/pom.xml
index 8c191b0abd..b92fb45e6f 100644
--- a/persistence-modules/pom.xml
+++ b/persistence-modules/pom.xml
@@ -21,7 +21,6 @@
blaze-persistence
core-java-persistence
core-java-persistence-2
- deltaspike
elasticsearch
flyway
flyway-repair
@@ -29,7 +28,6 @@
hibernate5
hibernate-mapping
hibernate-mapping-2
- hibernate-ogm
hibernate-annotations
hibernate-exceptions
hibernate-libraries
@@ -37,26 +35,27 @@
hibernate-queries
hibernate-enterprise
influxdb
- java-cassandra
+
java-cockroachdb
java-jdbi
- java-jpa
- java-jpa-2
+
+
java-jpa-3
- java-mongodb
+
+
java-mongodb-2
java-mongodb-3
java-mongodb-queries
- jnosql
+
jooq
jpa-hibernate-cascade-type
liquibase
orientdb
persistence-libraries
- querydsl
- r2dbc
+
+
read-only-transactions
- redis
+
solr
spring-boot-persistence-2
@@ -70,11 +69,11 @@
spring-data-arangodb
spring-data-cassandra
spring-data-cassandra-test
- spring-data-cassandra-reactive
+
spring-data-cosmosdb
- spring-data-couchbase-2
+
spring-data-dynamodb
- spring-data-eclipselink
+
spring-data-elasticsearch
@@ -88,35 +87,36 @@
spring-data-jpa-query
spring-data-jpa-query-2
spring-data-jpa-query-3
- spring-data-jpa-repo
+
spring-data-jpa-repo-2
spring-data-jdbc
spring-data-keyvalue
- spring-data-mongodb
+
spring-data-mongodb-2
spring-data-mongodb-reactive
- spring-data-neo4j
+
spring-data-redis
- spring-data-rest
+
+
spring-data-rest-2
spring-data-rest-querydsl
spring-data-solr
- spring-hibernate-3
- spring-hibernate-5
- spring-jpa
- spring-jpa-2
+
+
+
spring-jdbc
- spring-jooq
+
spring-mybatis
spring-persistence-simple
- 5.2.17.Final
- 42.2.20
- 2.3.4
+ 6.2.0.Final
+ 42.5.4
+ 2.7.1
1.16.3
-
\ No newline at end of file
+
diff --git a/persistence-modules/questdb/README.md b/persistence-modules/questdb/README.md
new file mode 100644
index 0000000000..cd5d11f7da
--- /dev/null
+++ b/persistence-modules/questdb/README.md
@@ -0,0 +1,2 @@
+### Relevant Articles:
+- [Introduction to QuestDB](https://www.baeldung.com/java-questdb)
diff --git a/persistence-modules/questdb/pom.xml b/persistence-modules/questdb/pom.xml
new file mode 100644
index 0000000000..ee3db461cb
--- /dev/null
+++ b/persistence-modules/questdb/pom.xml
@@ -0,0 +1,29 @@
+
+ 4.0.0
+
+ org.baeldung
+ questdb
+ questdb
+ 0.0.1-SNAPSHOT
+
+
+ com.baeldung
+ parent-java
+ 0.0.1-SNAPSHOT
+ ../../parent-java
+
+
+
+ UTF-8
+ 7.0.0
+
+
+
+
+ org.questdb
+ questdb
+ ${questdb.version}
+
+
+
diff --git a/persistence-modules/questdb/src/main/java/com/baeldung/InsertData.java b/persistence-modules/questdb/src/main/java/com/baeldung/InsertData.java
new file mode 100644
index 0000000000..9699b7c2d0
--- /dev/null
+++ b/persistence-modules/questdb/src/main/java/com/baeldung/InsertData.java
@@ -0,0 +1,29 @@
+package com.baeldung;
+
+import io.questdb.client.Sender;
+
+
+public class InsertData {
+ static final String SENSORS_TABLE_NAME = "sensors";
+
+ public static void main(String[] args) {
+ try (Sender sender = Sender.builder().address("localhost:9009").build()) {
+ sender.table(SENSORS_TABLE_NAME)
+ .stringColumn("id", "KTC")
+ .stringColumn("name", "Kitchen temperature (Celsius)")
+ .doubleColumn("currentValue", 20)
+ .atNow();
+ sender.table(SENSORS_TABLE_NAME)
+ .stringColumn("id", "SMT")
+ .stringColumn("name", "Smart Garden temperature (Celsius)")
+ .doubleColumn("currentValue", 28.5)
+ .atNow();
+ sender.table(SENSORS_TABLE_NAME)
+ .stringColumn("id", "RM1")
+ .stringColumn("name", "Room 1")
+ .doubleColumn("currentValue", 19.5)
+ .doubleColumn("idealValue", 18.5)
+ .atNow();
+ }
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/r2dbc/README.md b/persistence-modules/r2dbc/README.md
index 02d3cbf5fc..ceb7982cd4 100644
--- a/persistence-modules/r2dbc/README.md
+++ b/persistence-modules/r2dbc/README.md
@@ -1,3 +1,3 @@
### Relevant Articles:
- [R2DBC – Reactive Relational Database Connectivity](https://www.baeldung.com/r2dbc)
-
+- [Spring R2DBC Migrations Using Flyway](https://www.baeldung.com/spring-r2dbc-flyway)
diff --git a/persistence-modules/r2dbc/pom.xml b/persistence-modules/r2dbc/pom.xml
index f32b37974b..cfe344eba9 100644
--- a/persistence-modules/r2dbc/pom.xml
+++ b/persistence-modules/r2dbc/pom.xml
@@ -49,6 +49,34 @@
org.springframework.boot
spring-boot-devtools
+
+ org.projectlombok
+ lombok
+
+
+ org.springframework.boot
+ spring-boot-starter-data-r2dbc
+
+
+ org.postgresql
+ r2dbc-postgresql
+ ${r2dbc.postgresql.version}
+
+
+ org.postgresql
+ postgresql
+ ${jdbc.postgresql.version}
+
+
+ org.flywaydb
+ flyway-core
+ ${flyway.core.version}
+
+
+ io.r2dbc
+ r2dbc-h2
+ test
+
@@ -60,4 +88,10 @@
-
\ No newline at end of file
+
+ 9.14.1
+ 42.5.2
+ 1.0.0.RELEASE
+
+
+
diff --git a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/SpringWebfluxFlywayApplication.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/SpringWebfluxFlywayApplication.java
new file mode 100644
index 0000000000..7eb3f8180c
--- /dev/null
+++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/SpringWebfluxFlywayApplication.java
@@ -0,0 +1,13 @@
+package com.baeldung.examples.r2dbc.flyway;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class SpringWebfluxFlywayApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SpringWebfluxFlywayApplication.class, args);
+ }
+
+}
diff --git a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/config/DatabaseConfig.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/config/DatabaseConfig.java
new file mode 100644
index 0000000000..d4a4be93e9
--- /dev/null
+++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/config/DatabaseConfig.java
@@ -0,0 +1,23 @@
+package com.baeldung.examples.r2dbc.flyway.config;
+
+import org.flywaydb.core.Flyway;
+import org.springframework.boot.autoconfigure.flyway.FlywayProperties;
+import org.springframework.boot.autoconfigure.r2dbc.R2dbcProperties;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+@EnableConfigurationProperties({ R2dbcProperties.class, FlywayProperties.class })
+class DatabaseConfig {
+ @Bean(initMethod = "migrate")
+ public Flyway flyway(FlywayProperties flywayProperties, R2dbcProperties r2dbcProperties) {
+ return Flyway.configure()
+ .dataSource(flywayProperties.getUrl(), r2dbcProperties.getUsername(), r2dbcProperties.getPassword())
+ .locations(flywayProperties.getLocations()
+ .stream()
+ .toArray(String[]::new))
+ .baselineOnMigrate(true)
+ .load();
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/model/Department.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/model/Department.java
new file mode 100644
index 0000000000..cfb1555847
--- /dev/null
+++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/model/Department.java
@@ -0,0 +1,40 @@
+package com.baeldung.examples.r2dbc.flyway.model;
+
+import java.util.UUID;
+
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Size;
+
+import org.springframework.data.annotation.Id;
+import org.springframework.data.domain.Persistable;
+import org.springframework.data.relational.core.mapping.Table;
+
+import com.fasterxml.jackson.annotation.JsonAlias;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Table("department")
+@Data
+@AllArgsConstructor
+@NoArgsConstructor
+public class Department implements Persistable {
+
+ @Id
+ @JsonProperty("uuid")
+ @JsonAlias("id")
+ private UUID id;
+
+ @NotNull
+ @Size(max = 255, message = "The property 'name' must be less than or equal to 255 characters.")
+ private String name;
+
+ @Override
+ @JsonIgnore
+ public boolean isNew() {
+ return true;
+ }
+}
diff --git a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/model/Student.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/model/Student.java
new file mode 100644
index 0000000000..94dbe6e97f
--- /dev/null
+++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/model/Student.java
@@ -0,0 +1,55 @@
+package com.baeldung.examples.r2dbc.flyway.model;
+
+import java.time.LocalDate;
+import java.util.UUID;
+
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Size;
+
+import org.springframework.data.annotation.Id;
+import org.springframework.data.domain.Persistable;
+import org.springframework.data.relational.core.mapping.Table;
+
+import com.fasterxml.jackson.annotation.JsonAlias;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import lombok.AllArgsConstructor;
+import lombok.Builder;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+@Table("student")
+@Data
+@Builder
+@AllArgsConstructor
+@NoArgsConstructor
+public class Student implements Persistable {
+
+ @Id
+ @JsonProperty("uuid")
+ @JsonAlias("id")
+ private UUID id;
+
+ @NotNull
+ @Size(max = 255, message = "The property 'firstName' must be less than or equal to 255 characters.")
+ private String firstName;
+
+ @NotNull
+ @Size(max = 255, message = "The property 'lastName' must be less than or equal to 255 characters.")
+ private String lastName;
+
+ @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
+ private LocalDate dateOfBirth;
+
+ @NotNull
+ private UUID department;
+
+ @Override
+ @JsonIgnore
+ public boolean isNew() {
+ return true;
+ }
+}
+
diff --git a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/repository/DepartmentRepository.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/repository/DepartmentRepository.java
new file mode 100644
index 0000000000..85edf964b7
--- /dev/null
+++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/repository/DepartmentRepository.java
@@ -0,0 +1,10 @@
+package com.baeldung.examples.r2dbc.flyway.repository;
+
+import java.util.UUID;
+
+import org.springframework.data.repository.reactive.ReactiveCrudRepository;
+
+import com.baeldung.examples.r2dbc.flyway.model.Department;
+
+public interface DepartmentRepository extends ReactiveCrudRepository {
+}
diff --git a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/repository/StudentRepository.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/repository/StudentRepository.java
new file mode 100644
index 0000000000..1fc3ae1641
--- /dev/null
+++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/repository/StudentRepository.java
@@ -0,0 +1,10 @@
+package com.baeldung.examples.r2dbc.flyway.repository;
+
+import java.util.UUID;
+
+import org.springframework.data.repository.reactive.ReactiveCrudRepository;
+
+import com.baeldung.examples.r2dbc.flyway.model.Student;
+
+public interface StudentRepository extends ReactiveCrudRepository {
+}
diff --git a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/rest/DepartmentResource.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/rest/DepartmentResource.java
new file mode 100644
index 0000000000..32c3d5bbd8
--- /dev/null
+++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/rest/DepartmentResource.java
@@ -0,0 +1,29 @@
+package com.baeldung.examples.r2dbc.flyway.rest;
+
+import java.util.List;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.baeldung.examples.r2dbc.flyway.model.Department;
+import com.baeldung.examples.r2dbc.flyway.repository.DepartmentRepository;
+
+import lombok.RequiredArgsConstructor;
+import reactor.core.publisher.Mono;
+
+@RestController
+@RequiredArgsConstructor
+public class DepartmentResource {
+
+ private final DepartmentRepository departmentRepository;
+
+ @GetMapping(path = "/department")
+ public Mono>> getDepartments() {
+ return departmentRepository.findAll()
+ .collectList()
+ .map(departments -> new ResponseEntity(departments, HttpStatus.OK));
+ }
+
+}
diff --git a/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/rest/StudentResource.java b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/rest/StudentResource.java
new file mode 100644
index 0000000000..624f673406
--- /dev/null
+++ b/persistence-modules/r2dbc/src/main/java/com/baeldung/examples/r2dbc/flyway/rest/StudentResource.java
@@ -0,0 +1,29 @@
+package com.baeldung.examples.r2dbc.flyway.rest;
+
+import javax.validation.Valid;
+
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.baeldung.examples.r2dbc.flyway.model.Student;
+import com.baeldung.examples.r2dbc.flyway.repository.StudentRepository;
+
+import lombok.RequiredArgsConstructor;
+import reactor.core.publisher.Mono;
+
+@RestController
+@RequiredArgsConstructor
+public class StudentResource {
+
+ private final StudentRepository studentRepository;
+
+ @PostMapping(path = "/student")
+ public Mono> createStudent(@RequestBody @Valid Mono createStudentRequest) {
+ return createStudentRequest.flatMap(studentRepository::save)
+ .map(student -> new ResponseEntity(student, HttpStatus.CREATED));
+ }
+
+}
diff --git a/persistence-modules/r2dbc/src/main/resources/application.yml b/persistence-modules/r2dbc/src/main/resources/application.yml
index bb47c7261c..919a088209 100644
--- a/persistence-modules/r2dbc/src/main/resources/application.yml
+++ b/persistence-modules/r2dbc/src/main/resources/application.yml
@@ -1,7 +1,14 @@
spring:
application:
name: r2dbc-test
-
+
+ r2dbc:
+ username: local
+ password: local
+ url: r2dbc:postgresql://localhost:8082/flyway-test-db
+ flyway:
+ url: jdbc:postgresql://localhost:8082/flyway-test-db
+ locations: classpath:db/postgres/migration
# R2DBC URL
r2dbc:
url: r2dbc:h2:mem://./testdb
diff --git a/persistence-modules/r2dbc/src/main/resources/db/docker-compose.yml b/persistence-modules/r2dbc/src/main/resources/db/docker-compose.yml
new file mode 100644
index 0000000000..5b95899e4b
--- /dev/null
+++ b/persistence-modules/r2dbc/src/main/resources/db/docker-compose.yml
@@ -0,0 +1,14 @@
+version: '3.9'
+networks:
+ obref:
+services:
+ postgres_db_service:
+ container_name: postgres_db_service
+ image: postgres:11
+ ports:
+ - "8082:5432"
+ hostname: postgres_db_service
+ environment:
+ - POSTGRES_PASSWORD=local
+ - POSTGRES_USER=local
+ - POSTGRES_DB=flyway-test-db
\ No newline at end of file
diff --git a/persistence-modules/r2dbc/src/main/resources/db/postgres/migration/V1_1__create_tables.sql b/persistence-modules/r2dbc/src/main/resources/db/postgres/migration/V1_1__create_tables.sql
new file mode 100644
index 0000000000..23ecd2ca59
--- /dev/null
+++ b/persistence-modules/r2dbc/src/main/resources/db/postgres/migration/V1_1__create_tables.sql
@@ -0,0 +1,17 @@
+
+CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
+
+CREATE TABLE IF NOT EXISTS department
+(
+ id uuid PRIMARY KEY UNIQUE DEFAULT uuid_generate_v4(),
+ name varchar(255)
+);
+
+CREATE TABLE IF NOT EXISTS student
+(
+ id uuid PRIMARY KEY UNIQUE DEFAULT uuid_generate_v4(),
+ first_name varchar(255),
+ last_name varchar(255),
+ date_of_birth DATE NOT NULL,
+ department uuid NOT NULL CONSTRAINT student_foreign_key1 REFERENCES department (id)
+);
\ No newline at end of file
diff --git a/persistence-modules/r2dbc/src/main/resources/db/postgres/migration/V1_2__insert_department.sql b/persistence-modules/r2dbc/src/main/resources/db/postgres/migration/V1_2__insert_department.sql
new file mode 100644
index 0000000000..62fa654d57
--- /dev/null
+++ b/persistence-modules/r2dbc/src/main/resources/db/postgres/migration/V1_2__insert_department.sql
@@ -0,0 +1,3 @@
+
+insert into department(name) values ('Computer Science');
+insert into department(name) values ('Biomedical');
\ No newline at end of file
diff --git a/persistence-modules/r2dbc/src/test/java/com/baeldung/examples/r2dbc/flyway/rest/StudentResourceUnitTest.java b/persistence-modules/r2dbc/src/test/java/com/baeldung/examples/r2dbc/flyway/rest/StudentResourceUnitTest.java
new file mode 100644
index 0000000000..455b6862f8
--- /dev/null
+++ b/persistence-modules/r2dbc/src/test/java/com/baeldung/examples/r2dbc/flyway/rest/StudentResourceUnitTest.java
@@ -0,0 +1,71 @@
+package com.baeldung.examples.r2dbc.flyway.rest;
+
+import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
+
+import java.time.LocalDate;
+import java.util.List;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+import org.springframework.test.web.reactive.server.WebTestClient;
+import org.springframework.web.reactive.function.BodyInserters;
+
+import com.baeldung.examples.r2dbc.flyway.model.Department;
+import com.baeldung.examples.r2dbc.flyway.model.Student;
+
+import reactor.core.publisher.Mono;
+
+@ExtendWith(SpringExtension.class)
+@SpringBootTest(webEnvironment = RANDOM_PORT)
+class StudentResourceUnitTest {
+
+ private static final String DEPARTMENT_ENDPOINT = "/department";
+ private static final String STUDENT_ENDPOINT = "/student";
+
+ @Autowired
+ protected WebTestClient webTestClient;
+
+ @Test
+ void givenDepartmentExists_WhenCreateStudentRequestIsSent_ShouldBeProcessedSuccessfully() {
+
+ // Given
+ List departmentList = webTestClient.get()
+ .uri(DEPARTMENT_ENDPOINT)
+ .exchange()
+ .expectStatus()
+ .isOk()
+ .expectBodyList(Department.class)
+ .returnResult()
+ .getResponseBody();
+
+ Assertions.assertNotNull(departmentList);
+
+ // When
+ Student student = webTestClient.post()
+ .uri(STUDENT_ENDPOINT)
+ .body(BodyInserters.fromPublisher(Mono.just(Student.builder()
+ .firstName("John")
+ .lastName("Doe")
+ .dateOfBirth(LocalDate.of(2015, 12, 1))
+ .department(departmentList.get(0)
+ .getId())
+ .build()), Student.class))
+ .exchange()
+ .expectStatus()
+ .isEqualTo(201)
+ .expectBody(Student.class)
+ .returnResult()
+ .getResponseBody();
+
+ // Then
+ Assertions.assertNotNull(student.getId());
+ Assertions.assertEquals("John", student.getFirstName());
+ Assertions.assertEquals("Doe", student.getLastName());
+ Assertions.assertEquals(LocalDate.of(2015, 12, 1), student.getDateOfBirth());
+ }
+
+}
\ No newline at end of file
diff --git a/persistence-modules/r2dbc/src/test/resources/application.yml b/persistence-modules/r2dbc/src/test/resources/application.yml
index 8925116e4a..f99f02c9c1 100644
--- a/persistence-modules/r2dbc/src/test/resources/application.yml
+++ b/persistence-modules/r2dbc/src/test/resources/application.yml
@@ -1,6 +1,32 @@
# R2DBC Test configuration
r2dbc:
url: r2dbc:h2:mem://./testdb
-
+ user: local
+ password: local
+
+server:
+ port: 8080
+
+spring:
+ r2dbc:
+ host: localhost
+ port: 8082
+ database: testdb
+ username: local
+ password: local
+
+ h2:
+ console:
+ enabled: true
+ path: h2-console
+
+
+ flyway:
+ url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;
+ user: local
+ password: local
+ locations: classpath:db/h2/migration
+ main:
+ allow-bean-definition-overriding: true
diff --git a/persistence-modules/r2dbc/src/test/resources/db/h2/migration/V1_1__create_tables.sql b/persistence-modules/r2dbc/src/test/resources/db/h2/migration/V1_1__create_tables.sql
new file mode 100644
index 0000000000..388b23fcf5
--- /dev/null
+++ b/persistence-modules/r2dbc/src/test/resources/db/h2/migration/V1_1__create_tables.sql
@@ -0,0 +1,19 @@
+
+CREATE TABLE department
+(
+ id uuid DEFAULT random_uuid() PRIMARY KEY UNIQUE NOT NULL,
+ name varchar(255)
+);
+
+CREATE TABLE student
+(
+ id uuid DEFAULT random_uuid() UNIQUE NOT NULL,
+ first_name varchar(255),
+ last_name varchar(255),
+ date_of_birth DATE NOT NULL,
+ department uuid NOT NULL
+);
+
+
+ALTER TABLE student
+ ADD FOREIGN KEY (department) REFERENCES department(id);
\ No newline at end of file
diff --git a/persistence-modules/r2dbc/src/test/resources/db/h2/migration/V1_2__insert_department.sql b/persistence-modules/r2dbc/src/test/resources/db/h2/migration/V1_2__insert_department.sql
new file mode 100644
index 0000000000..62fa654d57
--- /dev/null
+++ b/persistence-modules/r2dbc/src/test/resources/db/h2/migration/V1_2__insert_department.sql
@@ -0,0 +1,3 @@
+
+insert into department(name) values ('Computer Science');
+insert into department(name) values ('Biomedical');
\ No newline at end of file
diff --git a/persistence-modules/rethinkdb/README.md b/persistence-modules/rethinkdb/README.md
new file mode 100644
index 0000000000..e8cf1415e7
--- /dev/null
+++ b/persistence-modules/rethinkdb/README.md
@@ -0,0 +1,2 @@
+## Relevant Articles
+- [Getting Started With RethinkDB](https://www.baeldung.com/rethinkdb)
diff --git a/persistence-modules/spring-boot-persistence-2/pom.xml b/persistence-modules/spring-boot-persistence-2/pom.xml
index 1a02b18e50..260c558875 100644
--- a/persistence-modules/spring-boot-persistence-2/pom.xml
+++ b/persistence-modules/spring-boot-persistence-2/pom.xml
@@ -17,13 +17,6 @@
-
- org.junit
- junit-bom
- ${junit-jupiter.version}
- pom
- import
-
org.springframework.boot
spring-boot-dependencies
@@ -33,7 +26,7 @@
org.jdbi
- jdbi3-spring4
+ jdbi3-spring5
${jdbi.version}
@@ -55,7 +48,7 @@
org.jdbi
- jdbi3-spring4
+ jdbi3-spring5
org.jdbi
@@ -103,6 +96,7 @@
mysql
mysql-connector-java
+ ${mysql-connector-java.version}
org.xerial
@@ -143,10 +137,14 @@
- 3.9.1
- 2.1.8.RELEASE
- 0.9.5.2
- 21.1.0.0
+ 3.38.0
+ 3.0.5
+ 0.9.5.5
+ 21.9.0.0
+
+ 2.0.7
+ 1.4.6
+ 8.0.33
\ No newline at end of file
diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java
index ddbe6cc118..d744a46f3f 100644
--- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java
+++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/JdbiConfiguration.java
@@ -31,11 +31,11 @@ public class JdbiConfiguration {
// Register all available plugins
log.info("[I27] Installing plugins... ({} found)", jdbiPlugins.size());
- jdbiPlugins.forEach(plugin -> jdbi.installPlugin(plugin));
+ jdbiPlugins.forEach(jdbi::installPlugin);
// Register all available rowMappers
log.info("[I31] Installing rowMappers... ({} found)", rowMappers.size());
- rowMappers.forEach(mapper -> jdbi.registerRowMapper(mapper));
+ rowMappers.forEach(jdbi::registerRowMapper);
return jdbi;
}
diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java
index 80b615801b..36cfd59b6d 100644
--- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java
+++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/domain/CarModel.java
@@ -8,7 +8,7 @@ import lombok.Data;
public class CarModel {
private Long id;
private String name;
- private Integer year;
+ private Integer yearDate;
private String sku;
private Long makerId;
}
diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java
index eeceafd649..b2311ef6a9 100644
--- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java
+++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/boot/jdbi/mapper/CarModelMapper.java
@@ -18,7 +18,7 @@ public class CarModelMapper implements RowMapper{
.id(rs.getLong("id"))
.name(rs.getString("name"))
.sku(rs.getString("sku"))
- .year(rs.getInt("year"))
+ .yearDate(rs.getInt("year"))
.build();
}
diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/db/indexing/Image.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/db/indexing/Image.java
index e3fcf53f81..7c7a558777 100644
--- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/db/indexing/Image.java
+++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/db/indexing/Image.java
@@ -1,9 +1,9 @@
package com.baeldung.db.indexing;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.Lob;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.Id;
+import jakarta.persistence.Lob;
@Entity
class Image {
diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java
index fb2c3fcf6a..af4199e65b 100644
--- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java
+++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/spring/oracle/pooling/entity/Book.java
@@ -1,9 +1,9 @@
package com.baeldung.spring.oracle.pooling.entity;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
@Entity
public class Book {
diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java
index ee2735abb8..cd4fafb60f 100644
--- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java
+++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/springboothsqldb/application/entities/Customer.java
@@ -1,10 +1,10 @@
package com.baeldung.springboothsqldb.application.entities;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
@Entity
@Table(name = "customers")
diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntity.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntity.java
index 90bd275240..8c3494d1e4 100644
--- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntity.java
+++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntity.java
@@ -5,9 +5,9 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.ManyToOne;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.ManyToOne;
@Entity
@AllArgsConstructor
diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntityWithCascade.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntityWithCascade.java
index de0d62bfe2..ada6b87ae3 100644
--- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntityWithCascade.java
+++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/states/UserEntityWithCascade.java
@@ -5,10 +5,10 @@ import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
-import javax.persistence.CascadeType;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.ManyToOne;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+import jakarta.persistence.ManyToOne;
@Entity
@AllArgsConstructor
diff --git a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java
index 712506eb98..02af097dc0 100644
--- a/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java
+++ b/persistence-modules/spring-boot-persistence-2/src/main/java/com/baeldung/tomcatconnectionpool/application/entities/Customer.java
@@ -1,11 +1,11 @@
package com.baeldung.tomcatconnectionpool.application.entities;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.Table;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.Table;
@Entity
@Table(name = "customers")
diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql
index 0e045d7274..0b1a93158b 100644
--- a/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql
+++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarMakerDao/insert.sql
@@ -1,4 +1,4 @@
--
-- Insert
--
-insert into car_maker(id,name) values (:id,:name);
+insert into car_maker(name) values (:name);
diff --git a/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql
index b277213584..6bca3a0d6d 100644
--- a/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql
+++ b/persistence-modules/spring-boot-persistence-2/src/main/resources/com/baeldung/boot/jdbi/dao/CarModelDao/insert.sql
@@ -1,8 +1,8 @@
--
-- Insert
--
-insert into car_model(maker_fk,name,sku,year) values (
+insert into car_model(maker_fk,name,sku,yearDate) values (
:makerId,
:name,
:sku,
- :year );
+ :yearDate );
diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java
index ac5661afbc..948d197f14 100644
--- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java
+++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/boot/jdbi/SpringBootJdbiApplicationIntegrationTest.java
@@ -76,7 +76,7 @@ public class SpringBootJdbiApplicationIntegrationTest {
@Test
public void givenExistingCarMaker_whenFindById_thenReturnExistingCarMaker() {
- CarMaker maker = carMakerDao.findById(1l);
+ CarMaker maker = carMakerDao.findById(1L);
assertThat(maker).isNotNull();
assertThat(maker.getId()).isEqualTo(1);
@@ -85,12 +85,12 @@ public class SpringBootJdbiApplicationIntegrationTest {
@Test
public void givenExistingCarMaker_whenBulkInsertFails_thenRollback() {
- CarMaker maker = carMakerDao.findById(1l);
+ CarMaker maker = carMakerDao.findById(1L);
CarModel m1 = CarModel.builder()
.makerId(maker.getId())
.name("Model X1")
.sku("1-M1")
- .year(2019)
+ .yearDate(2019)
.build();
maker.getModels().add(m1);
@@ -98,7 +98,7 @@ public class SpringBootJdbiApplicationIntegrationTest {
.makerId(maker.getId())
.name("Model X1")
.sku("1-M1")
- .year(2019)
+ .yearDate(2019)
.build();
maker.getModels().add(m2);
diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/FileSystemImageIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/FileSystemImageIntegrationTest.java
index 83f5bae095..809d04cc96 100644
--- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/FileSystemImageIntegrationTest.java
+++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/FileSystemImageIntegrationTest.java
@@ -4,8 +4,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+import java.io.File;
import java.io.InputStream;
-import java.nio.file.Paths;
+import java.net.URISyntaxException;
+import java.net.URL;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
@@ -64,10 +66,13 @@ class FileSystemImageIntegrationTest {
private FileSystemResource baeldungJpegResource() {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
- String imagePath = classLoader.getResource("baeldung.jpeg")
- .getFile();
-
- return new FileSystemResource(Paths.get(imagePath));
+ try {
+ final URL resource = classLoader.getResource("baeldung.jpeg");
+ if (resource != null) {
+ return new FileSystemResource(new File(resource.toURI()).getAbsolutePath());
+ }
+ } catch (URISyntaxException ignore) {}
+ return null;
}
}
diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/ImageIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/ImageIntegrationTest.java
index e38e0a21a9..09e13aefd4 100644
--- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/ImageIntegrationTest.java
+++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/db/indexing/ImageIntegrationTest.java
@@ -7,6 +7,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import java.io.IOException;
import java.io.InputStream;
+import java.net.URISyntaxException;
+import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Optional;
@@ -68,11 +70,15 @@ class ImageIntegrationTest {
private Image baeldungImage() throws IOException {
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
-
- Image mockImage = new Image();
- mockImage.setContent(Files.readAllBytes(Paths.get(classLoader.getResource("baeldung.jpeg")
- .getFile())));
- return mockImage;
+ try {
+ final URL resource = classLoader.getResource("baeldung.jpeg");
+ if (resource != null) {
+ Image mockImage = new Image();
+ mockImage.setContent(Files.readAllBytes(Paths.get(resource.toURI())));
+ return mockImage;
+ }
+ } catch (URISyntaxException ignore) {}
+ return null;
}
}
diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java
index 6956df0b13..bdd9a19b68 100644
--- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java
+++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/springboothsqldb/application/tests/CustomerControllerIntegrationTest.java
@@ -29,8 +29,7 @@ public class CustomerControllerIntegrationTest {
@Before
public void setUpJsonMediaType() {
- MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
-
+ MEDIA_TYPE_JSON = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype());
}
@Test
diff --git a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/states/UserEntityIntegrationTest.java b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/states/UserEntityIntegrationTest.java
index 5d0dc99ad7..0ce3ff34ce 100644
--- a/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/states/UserEntityIntegrationTest.java
+++ b/persistence-modules/spring-boot-persistence-2/src/test/java/com/baeldung/states/UserEntityIntegrationTest.java
@@ -9,7 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
-import javax.persistence.EntityManagerFactory;
+import jakarta.persistence.EntityManagerFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
diff --git a/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql b/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql
index e3e1f4ae32..fb97140b48 100644
--- a/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql
+++ b/persistence-modules/spring-boot-persistence-2/src/test/resources/data.sql
@@ -1,12 +1,12 @@
-insert into car_maker(id,name) values (1,'Special Motors');
-insert into car_maker(id,name) values (2,'BWM');
-insert into car_maker(id,name) values (3,'Dolores');
+insert into car_maker(id,name) values (99,'Special Motors');
+insert into car_maker(id,name) values (100,'BWM');
+insert into car_maker(id,name) values (102,'Dolores');
-insert into car_model(id,maker_fk,name,sku,year) values(1,1,'Muze','SM001',2018);
-insert into car_model(id,maker_fk,name,sku,year) values(2,1,'Empada','SM002',2008);
+insert into car_model(id,maker_fk,name,sku,yearDate) values(132,99,'Muze','SM001',2018);
+insert into car_model(id,maker_fk,name,sku,yearDate) values(145,99,'Empada','SM002',2008);
-insert into car_model(id,maker_fk,name,sku,year) values(4,2,'BWM-100','BWM100',2008);
-insert into car_model(id,maker_fk,name,sku,year) values(5,2,'BWM-200','BWM200',2009);
-insert into car_model(id,maker_fk,name,sku,year) values(6,2,'BWM-300','BWM300',2008);
+insert into car_model(id,maker_fk,name,sku,yearDate) values(43,100,'BWM-100','BWM100',2008);
+insert into car_model(id,maker_fk,name,sku,yearDate) values(564,100,'BWM-200','BWM200',2009);
+insert into car_model(id,maker_fk,name,sku,yearDate) values(343,100,'BWM-300','BWM300',2008);
diff --git a/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql b/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql
index 8d7db6c9f3..72f9e606de 100644
--- a/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql
+++ b/persistence-modules/spring-boot-persistence-2/src/test/resources/schema.sql
@@ -19,9 +19,9 @@ create table car_model(
maker_fk int not null,
name varchar(128) not null,
sku varchar(128) not null,
- year int not null
+ yearDate int not null
);
create unique index ui_car_model_01 on car_model(maker_fk,sku);
-create unique index ui_car_model_02 on car_model(maker_fk,name,year);
+create unique index ui_car_model_02 on car_model(maker_fk,name,yearDate);
diff --git a/persistence-modules/spring-boot-persistence-h2/README.md b/persistence-modules/spring-boot-persistence-h2/README.md
index 1d47907a98..7f6e243677 100644
--- a/persistence-modules/spring-boot-persistence-h2/README.md
+++ b/persistence-modules/spring-boot-persistence-h2/README.md
@@ -5,3 +5,4 @@
- [Hibernate @NotNull vs @Column(nullable = false)](https://www.baeldung.com/hibernate-notnull-vs-nullable)
- [Quick Guide to Hibernate enable_lazy_load_no_trans Property](https://www.baeldung.com/hibernate-lazy-loading-workaround)
- [Where Does H2’s Embedded Database Store The Data?](https://www.baeldung.com/h2-embedded-db-data-storage)
+- [Spring Boot H2 JdbcSQLSyntaxErrorException expected “identifier”](https://www.baeldung.com/spring-boot-h2-jdbcsqlsyntaxerrorexception-expected-identifier)
diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/SpringBootH2Exceptions.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/SpringBootH2Exceptions.java
new file mode 100644
index 0000000000..c7684423a2
--- /dev/null
+++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/SpringBootH2Exceptions.java
@@ -0,0 +1,15 @@
+package com.baeldung.h2.exceptions;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.PropertySource;
+
+@SpringBootApplication
+@PropertySource("classpath:app-h2.properties")
+public class SpringBootH2Exceptions {
+
+ public static void main(String... args) {
+ SpringApplication.run(SpringBootH2Exceptions.class, args);
+ }
+
+}
diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/models/User.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/models/User.java
new file mode 100644
index 0000000000..e54e725fd0
--- /dev/null
+++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/models/User.java
@@ -0,0 +1,38 @@
+package com.baeldung.h2.exceptions.models;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+@Entity
+public class User {
+
+ @Id
+ private int id;
+ private String login;
+ private String password;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getLogin() {
+ return login;
+ }
+
+ public void setLogin(String login) {
+ this.login = login;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public void setPassword(String password) {
+ this.password = password;
+ }
+
+}
diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/repos/UserRepository.java b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/repos/UserRepository.java
new file mode 100644
index 0000000000..d014fb16c6
--- /dev/null
+++ b/persistence-modules/spring-boot-persistence-h2/src/main/java/com/baeldung/h2/exceptions/repos/UserRepository.java
@@ -0,0 +1,11 @@
+package com.baeldung.h2.exceptions.repos;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+import com.baeldung.h2.exceptions.models.User;
+
+@Repository
+public interface UserRepository extends JpaRepository {
+
+}
diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/app-h2.properties b/persistence-modules/spring-boot-persistence-h2/src/main/resources/app-h2.properties
new file mode 100644
index 0000000000..bb88e7fef4
--- /dev/null
+++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/app-h2.properties
@@ -0,0 +1 @@
+spring.sql.init.data-locations=user-data.sql
diff --git a/persistence-modules/spring-boot-persistence-h2/src/main/resources/user-data.sql b/persistence-modules/spring-boot-persistence-h2/src/main/resources/user-data.sql
new file mode 100644
index 0000000000..cea758c74e
--- /dev/null
+++ b/persistence-modules/spring-boot-persistence-h2/src/main/resources/user-data.sql
@@ -0,0 +1,8 @@
+/* These commented lines will cause Spring Boot to fail at startup
+ *
+ * INSERT INTO user VALUES (1, 'admin', 'p@ssw@rd');
+ * INSERT INTO user VALUES (2, 'user', 'userpasswd');
+ *
+*/
+INSERT INTO "user" VALUES (1, 'admin', 'p@ssw@rd');
+INSERT INTO "user" VALUES (2, 'user', 'userpasswd');
\ No newline at end of file
diff --git a/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/h2/exceptions/SpringBootH2ExceptionsIntegrationTest.java b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/h2/exceptions/SpringBootH2ExceptionsIntegrationTest.java
new file mode 100644
index 0000000000..94cf08fb76
--- /dev/null
+++ b/persistence-modules/spring-boot-persistence-h2/src/test/java/com/baeldung/h2/exceptions/SpringBootH2ExceptionsIntegrationTest.java
@@ -0,0 +1,30 @@
+package com.baeldung.h2.exceptions;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.List;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.test.context.junit4.SpringRunner;
+
+import com.baeldung.h2.exceptions.models.User;
+import com.baeldung.h2.exceptions.repos.UserRepository;
+
+@RunWith(SpringRunner.class)
+@SpringBootTest(classes = SpringBootH2Exceptions.class)
+public class SpringBootH2ExceptionsIntegrationTest {
+
+ @Autowired
+ private UserRepository userRepository;
+
+ @Test
+ public void givenValidInitData_whenCallingFindAll_thenReturnData() {
+ List users = userRepository.findAll();
+
+ assertThat(users).hasSize(2);
+ }
+
+}
diff --git a/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml b/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml
index cd7198b931..121581498a 100644
--- a/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml
+++ b/persistence-modules/spring-boot-persistence-mongodb-2/pom.xml
@@ -5,7 +5,6 @@
4.0.0
spring-boot-persistence-mongodb-2
spring-boot-persistence-mongodb-2
- war
This is simple boot application for Spring boot persistence mongodb test
diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/pom.xml b/persistence-modules/spring-boot-persistence-mongodb-3/pom.xml
index b9a47aa703..b699a33559 100644
--- a/persistence-modules/spring-boot-persistence-mongodb-3/pom.xml
+++ b/persistence-modules/spring-boot-persistence-mongodb-3/pom.xml
@@ -5,7 +5,6 @@
4.0.0
spring-boot-persistence-mongodb-3
spring-boot-persistence-mongodb-3
- war
This is simple boot application for Spring boot persistence mongodb
@@ -16,6 +15,21 @@
+
+ org.mongodb
+ mongodb-driver-sync
+ ${mongodb-driver.version}
+
+
+ org.mongodb
+ mongodb-driver-core
+ ${mongodb-driver.version}
+
+
+ org.mongodb
+ bson
+ ${mongodb-driver.version}
+
org.springframework.boot
spring-boot-starter-web
@@ -23,6 +37,16 @@
org.springframework.boot
spring-boot-starter-data-mongodb
+
+
+ org.mongodb
+ mongodb-driver-sync
+
+
+ org.mongodb
+ mongodb-driver-core
+
+
org.mongodb
@@ -37,7 +61,8 @@
- 1.6.1
+ 1.7.3
+ 4.9.1
diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/EncryptionConfig.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/EncryptionConfig.java
index 0ff97eb6c1..1a74340057 100644
--- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/EncryptionConfig.java
+++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/EncryptionConfig.java
@@ -1,5 +1,7 @@
package com.baeldung.boot.csfle.config;
+import java.io.File;
+
import org.bson.BsonBinary;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@@ -17,7 +19,13 @@ public class EncryptionConfig {
private String keyVaultAlias;
@Value("${com.baeldung.csfle.auto-decryption:false}")
- private Boolean autoDecryption;
+ private boolean autoDecryption;
+
+ @Value("${com.baeldung.csfle.auto-encryption:false}")
+ private boolean autoEncryption;
+
+ @Value("${com.baeldung.csfle.auto-encryption-lib:#{null}}")
+ private File autoEncryptionLib;
private BsonBinary dataKeyId;
@@ -41,7 +49,23 @@ public class EncryptionConfig {
return masterKeyPath;
}
- public Boolean getAutoDecryption() {
+ public boolean isAutoDecryption() {
return autoDecryption;
}
+
+ public boolean isAutoEncryption() {
+ return autoEncryption;
+ }
+
+ public File getAutoEncryptionLib() {
+ return autoEncryptionLib;
+ }
+
+ public String dataKeyIdUuid() {
+ if (dataKeyId == null)
+ throw new IllegalStateException("data key not initialized");
+
+ return dataKeyId.asUuid()
+ .toString();
+ }
}
diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java
index 0dff1ec86d..19d0af08b2 100644
--- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java
+++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/config/MongoClientConfig.java
@@ -1,14 +1,15 @@
package com.baeldung.boot.csfle.config;
+import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
+import java.util.HashMap;
import java.util.Map;
import org.bson.BsonBinary;
import org.bson.BsonDocument;
import org.bson.Document;
-import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
@@ -51,14 +52,10 @@ public class MongoClientConfig extends AbstractMongoClientConfiguration {
@Bean
@Override
public MongoClient mongoClient() {
- MongoClient client;
try {
- client = MongoClients.create(clientSettings());
-
ClientEncryption encryption = clientEncryption();
- encryptionConfig.setDataKeyId(createOrRetrieveDataKey(client, encryption));
-
- return client;
+ encryptionConfig.setDataKeyId(createOrRetrieveDataKey(encryption));
+ return MongoClients.create(clientSettings());
} catch (IOException e) {
throw new IllegalStateException("unable to create client", e);
}
@@ -77,19 +74,10 @@ public class MongoClientConfig extends AbstractMongoClientConfiguration {
return ClientEncryptions.create(encryptionSettings);
}
- private BsonBinary createOrRetrieveDataKey(MongoClient client, ClientEncryption encryption) {
- MongoNamespace namespace = new MongoNamespace(encryptionConfig.getKeyVaultNamespace());
- MongoCollection keyVault = client.getDatabase(namespace.getDatabaseName())
- .getCollection(namespace.getCollectionName());
-
- Bson query = Filters.in("keyAltNames", encryptionConfig.getKeyVaultAlias());
- BsonDocument key = keyVault.withDocumentClass(BsonDocument.class)
- .find(query)
- .first();
-
+ private BsonBinary createOrRetrieveDataKey(ClientEncryption encryption) {
+ BsonDocument key = encryption.getKeyByAltName(encryptionConfig.getKeyVaultAlias());
if (key == null) {
- keyVault.createIndex(Indexes.ascending("keyAltNames"), new IndexOptions().unique(true)
- .partialFilterExpression(Filters.exists("keyAltNames")));
+ createKeyUniqueIndex();
DataKeyOptions options = new DataKeyOptions();
options.keyAltNames(Arrays.asList(encryptionConfig.getKeyVaultAlias()));
@@ -99,16 +87,68 @@ public class MongoClientConfig extends AbstractMongoClientConfiguration {
}
}
+ private void createKeyUniqueIndex() {
+ try (MongoClient client = MongoClients.create(MongoClientSettings.builder()
+ .applyConnectionString(new ConnectionString(uri))
+ .build())) {
+ MongoNamespace namespace = new MongoNamespace(encryptionConfig.getKeyVaultNamespace());
+ MongoCollection keyVault = client.getDatabase(namespace.getDatabaseName())
+ .getCollection(namespace.getCollectionName());
+
+ keyVault.createIndex(Indexes.ascending("keyAltNames"), new IndexOptions().unique(true)
+ .partialFilterExpression(Filters.exists("keyAltNames")));
+ }
+ }
+
private MongoClientSettings clientSettings() throws FileNotFoundException, IOException {
Builder settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri));
- if (encryptionConfig.getAutoDecryption()) {
- settings.autoEncryptionSettings(AutoEncryptionSettings.builder()
+ if (encryptionConfig.isAutoDecryption()) {
+ AutoEncryptionSettings.Builder builder = AutoEncryptionSettings.builder()
.keyVaultNamespace(encryptionConfig.getKeyVaultNamespace())
- .kmsProviders(LocalKmsUtils.providersMap(encryptionConfig.getMasterKeyPath()))
- .bypassAutoEncryption(true)
- .build());
+ .kmsProviders(LocalKmsUtils.providersMap(encryptionConfig.getMasterKeyPath()));
+
+ if (encryptionConfig.isAutoEncryption() && encryptionConfig.getDataKeyId() != null) {
+ File autoEncryptionLib = encryptionConfig.getAutoEncryptionLib();
+ if (!autoEncryptionLib.isFile()) {
+ throw new IllegalArgumentException("encryption lib must be an existing file");
+ }
+
+ Map map = new HashMap<>();
+ map.put("cryptSharedLibRequired", true);
+ map.put("cryptSharedLibPath", autoEncryptionLib.toString());
+ builder.extraOptions(map);
+
+ String keyUuid = encryptionConfig.dataKeyIdUuid();
+ HashMap schemaMap = new HashMap<>();
+ schemaMap.put(getDatabaseName() + ".citizens",
+ BsonDocument.parse("{"
+ + " bsonType: \"object\","
+ + " encryptMetadata: {"
+ + " keyId: [UUID(\"" + keyUuid + "\")]"
+ + " },"
+ + " properties: {"
+ + " email: {"
+ + " encrypt: {"
+ + " bsonType: \"string\","
+ + " algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic\""
+ + " }"
+ + " },"
+ + " birthYear: {"
+ + " encrypt: {"
+ + " bsonType: \"int\","
+ + " algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Random\""
+ + " }"
+ + " }"
+ + " }"
+ + "}"));
+ builder.schemaMap(schemaMap);
+ } else {
+ builder.bypassAutoEncryption(true);
+ }
+
+ settings.autoEncryptionSettings(builder.build());
}
return settings.build();
diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java
index 6b3c463d0d..c93b00f3f8 100644
--- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java
+++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/service/CitizenService.java
@@ -35,16 +35,20 @@ public class CitizenService {
@Autowired
private ClientEncryption clientEncryption;
- public EncryptedCitizen save(Citizen citizen) {
- EncryptedCitizen encryptedCitizen = new EncryptedCitizen(citizen);
- encryptedCitizen.setEmail(encrypt(citizen.getEmail(), DETERMINISTIC_ALGORITHM));
- encryptedCitizen.setBirthYear(encrypt(citizen.getBirthYear(), RANDOM_ALGORITHM));
+ public Object save(Citizen citizen) {
+ if (encryptionConfig.isAutoEncryption()) {
+ return mongo.save(citizen);
+ } else {
+ EncryptedCitizen encryptedCitizen = new EncryptedCitizen(citizen);
+ encryptedCitizen.setEmail(encrypt(citizen.getEmail(), DETERMINISTIC_ALGORITHM));
+ encryptedCitizen.setBirthYear(encrypt(citizen.getBirthYear(), RANDOM_ALGORITHM));
- return mongo.save(encryptedCitizen);
+ return mongo.save(encryptedCitizen);
+ }
}
public List findAll() {
- if (!encryptionConfig.getAutoDecryption()) {
+ if (!encryptionConfig.isAutoDecryption()) {
List allEncrypted = mongo.findAll(EncryptedCitizen.class);
return allEncrypted.stream()
@@ -56,13 +60,20 @@ public class CitizenService {
}
public Citizen findByEmail(String email) {
- Query byEmail = new Query(Criteria.where("email")
- .is(encrypt(email, DETERMINISTIC_ALGORITHM)));
- if (!encryptionConfig.getAutoDecryption()) {
+ Criteria emailCriteria = Criteria.where("email");
+ if (encryptionConfig.isAutoEncryption()) {
+ emailCriteria.is(email);
+ } else {
+ emailCriteria
+ .is(encrypt(email, DETERMINISTIC_ALGORITHM));
+ }
+
+ Query byEmail = new Query(emailCriteria);
+ if (encryptionConfig.isAutoDecryption()) {
+ return mongo.findOne(byEmail, Citizen.class);
+ } else {
EncryptedCitizen encryptedCitizen = mongo.findOne(byEmail, EncryptedCitizen.class);
return decrypt(encryptedCitizen);
- } else {
- return mongo.findOne(byEmail, Citizen.class);
}
}
diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/web/CitizenController.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/web/CitizenController.java
index d17435fb5e..7a2b2605cd 100644
--- a/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/web/CitizenController.java
+++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/main/java/com/baeldung/boot/csfle/web/CitizenController.java
@@ -11,7 +11,6 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.boot.csfle.data.Citizen;
-import com.baeldung.boot.csfle.data.EncryptedCitizen;
import com.baeldung.boot.csfle.service.CitizenService;
@RestController
@@ -32,7 +31,7 @@ public class CitizenController {
}
@PostMapping
- public EncryptedCitizen post(@RequestBody Citizen citizen) {
+ public Object post(@RequestBody Citizen citizen) {
return service.save(citizen);
}
}
diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/csfle/CitizenServiceLiveTest.java b/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/csfle/CitizenServiceLiveTest.java
index 471cb2883a..d57da43751 100644
--- a/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/csfle/CitizenServiceLiveTest.java
+++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/test/java/com/baeldung/boot/csfle/CitizenServiceLiveTest.java
@@ -38,10 +38,14 @@ public class CitizenServiceLiveTest {
citizen.setName("Foo");
citizen.setEmail("foo@citizen.com");
- Binary encryptedEmail = service.encrypt(citizen.getEmail(), CitizenService.DETERMINISTIC_ALGORITHM);
+ Object saved = service.save(citizen);
+ if (saved instanceof EncryptedCitizen) {
+ Binary encryptedEmail = service.encrypt(citizen.getEmail(), CitizenService.DETERMINISTIC_ALGORITHM);
- EncryptedCitizen saved = service.save(citizen);
- assertEquals(encryptedEmail, saved.getEmail());
+ assertEquals(encryptedEmail, ((EncryptedCitizen) saved).getEmail());
+ } else {
+ assertEquals(citizen.getEmail(), ((Citizen) saved).getEmail());
+ }
}
@Test
diff --git a/persistence-modules/spring-boot-persistence-mongodb-3/src/test/resources/embedded.properties b/persistence-modules/spring-boot-persistence-mongodb-3/src/test/resources/embedded.properties
index 5325354e55..cd1c1d43c7 100644
--- a/persistence-modules/spring-boot-persistence-mongodb-3/src/test/resources/embedded.properties
+++ b/persistence-modules/spring-boot-persistence-mongodb-3/src/test/resources/embedded.properties
@@ -1,10 +1,10 @@
spring.mongodb.embedded.version=4.4.9
-spring.data.mongodb.uri=changeit
-spring.data.mongodb.database=changeit
+#spring.data.mongodb.uri=changeit
+#spring.data.mongodb.database=changeit
com.baeldung.csfle.kms-provider=local
com.baeldung.csfle.key-vault.namespace=encryption._keyVault
com.baeldung.csfle.key-vault.alias=master.key
-com.baeldung.csfle.master-key-path=/tmp/master.key
+#com.baeldung.csfle.master-key-path=/tmp/master.key
com.baeldung.csfle.auto-decryption=false
diff --git a/persistence-modules/spring-boot-persistence-mongodb/pom.xml b/persistence-modules/spring-boot-persistence-mongodb/pom.xml
index 724fa38f7e..aae307f7f8 100644
--- a/persistence-modules/spring-boot-persistence-mongodb/pom.xml
+++ b/persistence-modules/spring-boot-persistence-mongodb/pom.xml
@@ -5,7 +5,6 @@
4.0.0
spring-boot-persistence-mongodb
spring-boot-persistence-mongodb
- war
This is simple boot application for Spring boot persistence mongodb test
diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dataloading/ApplicationDataLoading.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dataloading/ApplicationDataLoading.java
new file mode 100644
index 0000000000..40742d303e
--- /dev/null
+++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dataloading/ApplicationDataLoading.java
@@ -0,0 +1,16 @@
+package com.baeldung.dataloading;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.core.env.AbstractEnvironment;
+
+@SpringBootApplication(scanBasePackages = { "com.baeldung.dataloading" })
+public class ApplicationDataLoading {
+
+ public static void main(String[] args) {
+ System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "datasource");
+
+ SpringApplication.run(ApplicationDataLoading.class, args);
+ }
+
+}
diff --git a/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dataloading/model/Country.java b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dataloading/model/Country.java
new file mode 100644
index 0000000000..692d48caf0
--- /dev/null
+++ b/persistence-modules/spring-boot-persistence/src/main/java/com/baeldung/dataloading/model/Country.java
@@ -0,0 +1,36 @@
+package com.baeldung.dataloading.model;
+
+import static javax.persistence.GenerationType.IDENTITY;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+
+@Entity
+public class Country {
+
+ @Id
+ @GeneratedValue(strategy = IDENTITY)
+ private Integer id;
+
+ @Column(nullable = false)
+ private String name;
+
+ 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;
+ }
+
+}
diff --git a/persistence-modules/spring-boot-persistence/src/main/resources/application-datasource.properties b/persistence-modules/spring-boot-persistence/src/main/resources/application-datasource.properties
new file mode 100644
index 0000000000..98cf2ba965
--- /dev/null
+++ b/persistence-modules/spring-boot-persistence/src/main/resources/application-datasource.properties
@@ -0,0 +1,14 @@
+spring.datasource.driver-class-name=org.h2.Driver
+spring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
+spring.datasource.username=sa
+spring.datasource.password=
+
+spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
+spring.jpa.hibernate.ddl-auto=create
+spring.jpa.defer-datasource-initialization=true
+
+# Enabling H2 Console
+spring.h2.console.enabled=true
+
+# By default enabled for Embedded Databases
+#spring.sql.init.mode=always
\ No newline at end of file
diff --git a/persistence-modules/spring-data-cassandra-2/README.md b/persistence-modules/spring-data-cassandra-2/README.md
index f5cf20b8a9..3f49d6ae93 100644
--- a/persistence-modules/spring-data-cassandra-2/README.md
+++ b/persistence-modules/spring-data-cassandra-2/README.md
@@ -1,3 +1,4 @@
### Relevant Articles:
- [Using Test Containers With Spring Data Cassandra](https://www.baeldung.com/spring-data-cassandra-test-containers)
+- [Cassandra – Object Mapping with DataStax Java Driver](https://www.baeldung.com/cassandra-object-mapping-datastax-java-driver)
diff --git a/persistence-modules/spring-data-jpa-annotations/README.md b/persistence-modules/spring-data-jpa-annotations/README.md
index 5a5440b1ed..d7e6189ae5 100644
--- a/persistence-modules/spring-data-jpa-annotations/README.md
+++ b/persistence-modules/spring-data-jpa-annotations/README.md
@@ -10,6 +10,7 @@ This module contains articles about annotations used in Spring Data JPA
- [Programmatic Transaction Management in Spring](https://www.baeldung.com/spring-programmatic-transaction-management)
- [JPA Entity Lifecycle Events](https://www.baeldung.com/jpa-entity-lifecycle-events)
- [Overriding Column Definition With @AttributeOverride](https://www.baeldung.com/jpa-attributeoverride)
+- [A Spring Custom Annotation for a Better DAO](http://www.baeldung.com/spring-annotation-bean-pre-processor)
### Eclipse Config
After importing the project into Eclipse, you may see the following error:
diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java
similarity index 100%
rename from spring-core-3/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java
rename to persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/CustomAnnotationConfiguration.java
diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccess.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/DataAccess.java
similarity index 100%
rename from spring-core-3/src/main/java/com/baeldung/customannotation/DataAccess.java
rename to persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/DataAccess.java
diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java
similarity index 100%
rename from spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java
rename to persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/DataAccessAnnotationProcessor.java
diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java
similarity index 100%
rename from spring-core-3/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java
rename to persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/DataAccessFieldCallback.java
diff --git a/spring-core-3/src/main/java/com/baeldung/customannotation/GenericDAO.java b/persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/GenericDAO.java
similarity index 100%
rename from spring-core-3/src/main/java/com/baeldung/customannotation/GenericDAO.java
rename to persistence-modules/spring-data-jpa-annotations/src/main/java/com/baeldung/customannotation/GenericDAO.java
diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/Account.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/Account.java
similarity index 100%
rename from spring-core-3/src/test/java/com/baeldung/customannotation/Account.java
rename to persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/Account.java
diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java
similarity index 100%
rename from spring-core-3/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java
rename to persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/BeanWithGenericDAO.java
diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java
similarity index 100%
rename from spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java
rename to persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/DataAccessAnnotationIntegrationTest.java
diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java
similarity index 100%
rename from spring-core-3/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java
rename to persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/DataAccessFieldCallbackIntegrationTest.java
diff --git a/spring-core-3/src/test/java/com/baeldung/customannotation/Person.java b/persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/Person.java
similarity index 100%
rename from spring-core-3/src/test/java/com/baeldung/customannotation/Person.java
rename to persistence-modules/spring-data-jpa-annotations/src/test/java/com/baeldung/customannotation/Person.java
diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/entity/Customer.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/entity/Customer.java
index efcae73853..5af96d7822 100644
--- a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/entity/Customer.java
+++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/entity/Customer.java
@@ -1,8 +1,11 @@
package com.baeldung.entity;
+import org.hibernate.annotations.Type;
+
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
+import java.util.UUID;
@Entity
public class Customer {
@@ -13,11 +16,20 @@ public class Customer {
private String name;
private String email;
+ @Type(type = "org.hibernate.type.UUIDCharType")
+ private UUID uuid;
+
public Customer(String name, String email) {
this.name = name;
this.email = email;
}
+ public Customer(String name, String email, UUID uuid) {
+ this.name = name;
+ this.email = email;
+ this.uuid = uuid;
+ }
+
public String getName() {
return name;
}
@@ -34,4 +46,7 @@ public class Customer {
this.email = email;
}
+ public UUID getUuid() {
+ return this.uuid;
+ }
}
diff --git a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/repository/CustomerRepository.java b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/repository/CustomerRepository.java
index 65b22bbd84..5f9710b839 100644
--- a/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/repository/CustomerRepository.java
+++ b/persistence-modules/spring-data-jpa-filtering/src/main/java/com/baeldung/repository/CustomerRepository.java
@@ -6,6 +6,7 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
+import java.util.UUID;
public interface CustomerRepository extends JpaRepository {
@@ -16,4 +17,5 @@ public interface CustomerRepository extends JpaRepository {
@Query("SELECT c FROM Customer c WHERE (:name is null or c.name = :name) and (:email is null or c.email = :email)")
List findCustomerByNameAndEmail(@Param("name") String name, @Param("email") String email);
+ List findCustomerByUuid(@Param("uuid") UUID uuid);
}
diff --git a/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java
index 5d6457ce30..27208507f1 100644
--- a/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java
+++ b/persistence-modules/spring-data-jpa-filtering/src/test/java/com/baeldung/repository/CustomerRepositoryIntegrationTest.java
@@ -12,6 +12,7 @@ import org.springframework.test.context.junit4.SpringRunner;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
+import java.util.UUID;
import static org.junit.Assert.assertEquals;
@@ -30,6 +31,7 @@ public class CustomerRepositoryIntegrationTest {
entityManager.persist(new Customer("A", "A@example.com"));
entityManager.persist(new Customer("D", null));
entityManager.persist(new Customer("D", "D@example.com"));
+ entityManager.persist(new Customer("C", null, UUID.fromString("c7c19ff4-8636-4b99-9591-c3327652f191")));
}
@Test
@@ -57,6 +59,20 @@ public class CustomerRepositoryIntegrationTest {
assertEquals(2, customers.size());
}
+ @Test
+ public void givenUUIDIsPresent_whenQueryMethod_thenFetchedCorrectly() {
+ List customers = repository.findCustomerByUuid(UUID.fromString("c7c19ff4-8636-4b99-9591-c3327652f191"));
+
+ assertEquals(1, customers.size());
+ }
+
+ @Test
+ public void givenNullUuid_whenQueryMethod_thenFetchedCorrectly() {
+ List customers = repository.findCustomerByUuid(null);
+
+ assertEquals(3, customers.size());
+ }
+
@After
public void cleanUp() {
repository.deleteAll();
diff --git a/persistence-modules/spring-data-jpa-repo-2/README.md b/persistence-modules/spring-data-jpa-repo-2/README.md
index 23134ec02d..dc94ba41d0 100644
--- a/persistence-modules/spring-data-jpa-repo-2/README.md
+++ b/persistence-modules/spring-data-jpa-repo-2/README.md
@@ -9,4 +9,5 @@
- [Difference Between JPA and Spring Data JPA](https://www.baeldung.com/spring-data-jpa-vs-jpa)
- [Differences Between Spring Data JPA findFirst() and findTop()](https://www.baeldung.com/spring-data-jpa-findfirst-vs-findtop)
- [Difference Between findBy and findAllBy in Spring Data JPA](https://www.baeldung.com/spring-data-jpa-find-by-vs-find-all-by)
+- [Unidirectional One-to-Many and Cascading Delete in JPA](https://www.baeldung.com/spring-jpa-unidirectional-one-to-many-and-cascading-delete)
- More articles: [[<-- prev]](../spring-data-jpa-repo)
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/EntityManagerRepository.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/EntityManagerRepository.java
new file mode 100644
index 0000000000..9d04d7bde7
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/EntityManagerRepository.java
@@ -0,0 +1,22 @@
+package com.baeldung.spring.data.persistence.truncate;
+
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.Query;
+
+@Repository
+public class EntityManagerRepository {
+
+ @PersistenceContext
+ private EntityManager entityManager;
+
+ @Transactional
+ public void truncateTable(String tableName) {
+ String sql = "TRUNCATE TABLE " + tableName;
+ Query query = entityManager.createNativeQuery(sql);
+ query.executeUpdate();
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/JdbcTemplateRepository.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/JdbcTemplateRepository.java
new file mode 100644
index 0000000000..29706311cb
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/JdbcTemplateRepository.java
@@ -0,0 +1,20 @@
+package com.baeldung.spring.data.persistence.truncate;
+
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+
+@Repository
+public class JdbcTemplateRepository {
+ private final JdbcTemplate jdbcTemplate;
+
+ public JdbcTemplateRepository(JdbcTemplate jdbcTemplate) {
+ this.jdbcTemplate = jdbcTemplate;
+ }
+
+ @Transactional
+ public void truncateTable(String tableName) {
+ String sql = "TRUNCATE TABLE " + tableName;
+ jdbcTemplate.execute(sql);
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntity.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntity.java
new file mode 100644
index 0000000000..29f82ed717
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntity.java
@@ -0,0 +1,45 @@
+package com.baeldung.spring.data.persistence.truncate;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import java.util.Objects;
+
+@Entity
+@Table(name = MyEntity.TABLE_NAME)
+public class MyEntity {
+
+ public final static String TABLE_NAME = "my_entity";
+ @Id
+ @GeneratedValue
+ private Long id;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ MyEntity myEntity = (MyEntity) o;
+ return Objects.equals(id, myEntity.id);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(id);
+ }
+
+ @Override
+ public String toString() {
+ return "MyEntity{" +
+ "id=" + id +
+ '}';
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntityRepository.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntityRepository.java
new file mode 100644
index 0000000000..d0e032bebe
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/MyEntityRepository.java
@@ -0,0 +1,20 @@
+package com.baeldung.spring.data.persistence.truncate;
+
+import org.springframework.data.jpa.repository.Modifying;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.CrudRepository;
+import org.springframework.stereotype.Repository;
+
+import javax.transaction.Transactional;
+
+@Repository
+public interface MyEntityRepository extends CrudRepository {
+
+ @Modifying
+ @Transactional
+ // need to wrap in double quotes due to
+ // spring.jpa.properties.hibernate.globally_quoted_identifiers=true backward compatibility
+ // property disabled in tests
+ @Query(value = "truncate table " + MyEntity.TABLE_NAME, nativeQuery = true)
+ void truncateTable();
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/TruncateSpringBootApplication.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/TruncateSpringBootApplication.java
new file mode 100644
index 0000000000..322549e19b
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/truncate/TruncateSpringBootApplication.java
@@ -0,0 +1,14 @@
+package com.baeldung.spring.data.persistence.truncate;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.autoconfigure.domain.EntityScan;
+
+@EntityScan(basePackageClasses = MyEntity.class)
+@SpringBootApplication
+public class TruncateSpringBootApplication {
+
+ public static void main(String[] args) {
+ SpringApplication.run(TruncateSpringBootApplication.class);
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Article.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Article.java
new file mode 100644
index 0000000000..97f79515cc
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Article.java
@@ -0,0 +1,46 @@
+package com.baeldung.spring.data.persistence.unidirectionalcascadingdelete;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+
+@Entity
+public class Article {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private long id;
+ private String name;
+ @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
+ private Set comments = new HashSet<>();
+
+ public Set getComments() {
+ return comments;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public void setComments(Set comments) {
+ this.comments = comments;
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleRepository.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleRepository.java
new file mode 100644
index 0000000000..7cf88c73b1
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleRepository.java
@@ -0,0 +1,9 @@
+package com.baeldung.spring.data.persistence.unidirectionalcascadingdelete;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface ArticleRepository extends JpaRepository {
+
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleService.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleService.java
new file mode 100644
index 0000000000..b0f9bdb05e
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/ArticleService.java
@@ -0,0 +1,17 @@
+package com.baeldung.spring.data.persistence.unidirectionalcascadingdelete;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+@Service
+public class ArticleService {
+
+ @Autowired
+ private ArticleRepository articleRepository;
+
+ public void deleteArticle(Article article) {
+ articleRepository.delete(article);
+
+ }
+
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CascadingDeleteApplication.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CascadingDeleteApplication.java
new file mode 100644
index 0000000000..1c417d9cc9
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CascadingDeleteApplication.java
@@ -0,0 +1,12 @@
+package com.baeldung.spring.data.persistence.unidirectionalcascadingdelete;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class CascadingDeleteApplication {
+ public static void main(String[] args) {
+ SpringApplication.run(CascadingDeleteApplication.class, args);
+ }
+
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Comment.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Comment.java
new file mode 100644
index 0000000000..334ac01ea5
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/Comment.java
@@ -0,0 +1,45 @@
+package com.baeldung.spring.data.persistence.unidirectionalcascadingdelete;
+
+import java.util.Date;
+
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+
+@Entity
+public class Comment {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ private long id;
+
+ private String description;
+ private Date date;
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public void setDate(Date total) {
+ this.date = total;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+}
+
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CommentRepository.java b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CommentRepository.java
new file mode 100644
index 0000000000..cadb1d7173
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/main/java/com/baeldung/spring/data/persistence/unidirectionalcascadingdelete/CommentRepository.java
@@ -0,0 +1,8 @@
+package com.baeldung.spring.data.persistence.unidirectionalcascadingdelete;
+
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface CommentRepository extends JpaRepository {
+}
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/deletionCascading/ArticleRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/deletionCascading/ArticleRepositoryIntegrationTest.java
new file mode 100644
index 0000000000..6ff8d57b6e
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/deletionCascading/ArticleRepositoryIntegrationTest.java
@@ -0,0 +1,75 @@
+package com.baeldung.spring.data.persistence.deletionCascading;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.transaction.Transactional;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+
+import com.baeldung.spring.data.persistence.unidirectionalcascadingdelete.Article;
+import com.baeldung.spring.data.persistence.unidirectionalcascadingdelete.ArticleRepository;
+import com.baeldung.spring.data.persistence.unidirectionalcascadingdelete.ArticleService;
+import com.baeldung.spring.data.persistence.unidirectionalcascadingdelete.CascadingDeleteApplication;
+import com.baeldung.spring.data.persistence.unidirectionalcascadingdelete.Comment;
+import com.baeldung.spring.data.persistence.unidirectionalcascadingdelete.CommentRepository;
+
+@SpringBootTest(classes = CascadingDeleteApplication.class)
+@Transactional
+public class ArticleRepositoryIntegrationTest {
+
+ @Autowired
+ private ArticleRepository articleRepository;
+
+ @Autowired
+ private CommentRepository commentRepository;
+
+ @Autowired
+ private ArticleService articleService;
+
+ @Test
+ @Transactional
+ public void givenAnArticleAndItsComments_whenDeleteArticle_thenCommentsDeletedAutomatically() {
+
+ Set comments = new HashSet<>();
+ Article article = new Article();
+ article.setName("introduction to Spring");
+
+ Comment comment1 = new Comment();
+ comment1.setDescription("Explain types of Autowired");
+ comment1.setDate(Date.from(Instant.now()));
+
+ Comment comment2 = new Comment();
+ comment2.setDescription("Good article");
+ comment2.setDate(Date.from(Instant.now()
+ .minus(10, ChronoUnit.MINUTES)));
+
+ comments.add(comment1);
+ comments.add(comment2);
+
+ article.setComments(comments);
+ articleRepository.save(article);
+
+ List articles = articleRepository.findAll();
+ assertThat(articles.size()).isEqualTo(1);
+ Article retrivedArticle = articles.get(0);
+
+ List fetchedComments = commentRepository.findAll();
+ assertThat(fetchedComments.size()).isEqualTo(2);
+
+ articleService.deleteArticle(retrivedArticle);
+ assertThat(articleRepository.findAll()).isEmpty();
+
+ assertThat(commentRepository.findAll()).isEmpty();
+
+ }
+}
+
diff --git a/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/truncate/TruncateIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/truncate/TruncateIntegrationTest.java
new file mode 100644
index 0000000000..b2b6a655db
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-2/src/test/java/com/baeldung/spring/data/persistence/truncate/TruncateIntegrationTest.java
@@ -0,0 +1,71 @@
+package com.baeldung.spring.data.persistence.truncate;
+
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+@SpringBootTest(classes = TruncateSpringBootApplication.class,
+ properties = "spring.jpa.properties.hibernate.globally_quoted_identifiers=false")
+class TruncateIntegrationTest {
+
+ @Autowired
+ private MyEntityRepository myEntityRepository;
+
+ @Autowired
+ private JdbcTemplateRepository jdbcTemplateRepository;
+
+ @Autowired
+ private EntityManagerRepository entityManagerRepository;
+
+ @Test
+ void givenSomeData_whenRepositoryTruncateDate_thenNoDataLeft() {
+ int givenCount = 3;
+ givenDummyData(givenCount);
+
+ myEntityRepository.truncateTable();
+
+ assertThat(myEntityRepository.count())
+ .isNotEqualTo(givenCount)
+ .isZero();
+ }
+
+ @Test
+ void givenSomeData_whenEntityManagerTruncateDate_thenNoDataLeft() {
+ int givenCount = 3;
+ givenDummyData(givenCount);
+
+ entityManagerRepository.truncateTable(MyEntity.TABLE_NAME);
+
+ assertThat(myEntityRepository.count())
+ .isNotEqualTo(givenCount)
+ .isZero();
+ }
+
+ @Test
+ void givenSomeData_whenJDBCTemplateTruncateDate_thenNoDataLeft() {
+ int givenCount = 3;
+ givenDummyData(givenCount);
+
+ jdbcTemplateRepository.truncateTable(MyEntity.TABLE_NAME);
+
+ assertThat(myEntityRepository.count())
+ .isNotEqualTo(givenCount)
+ .isZero();
+ }
+
+ private void givenDummyData(int count) {
+ List input = Stream.generate(this::givenMyEntity).limit(count).collect(Collectors.toList());
+ myEntityRepository.saveAll(input);
+ }
+
+ private MyEntity givenMyEntity() {
+ return new MyEntity();
+ }
+
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-repo-3/README.md b/persistence-modules/spring-data-jpa-repo-3/README.md
new file mode 100644
index 0000000000..d3782eb1e6
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/README.md
@@ -0,0 +1,8 @@
+## Spring Data JPA - Repositories
+
+This module contains articles about Spring Data JPA.
+
+### Relevant Articles:
+- [New CRUD Repository Interfaces in Spring Data 3](https://www.baeldung.com/spring-data-3-crud-repository-interfaces)
+- [How to Persist a List of String in JPA?](https://www.baeldung.com/java-jpa-persist-string-list)
+- More articles: [[<-- prev]](../spring-data-jpa-repo-2)
diff --git a/persistence-modules/spring-data-jpa-repo-3/pom.xml b/persistence-modules/spring-data-jpa-repo-3/pom.xml
new file mode 100644
index 0000000000..8cd8ca7f61
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/pom.xml
@@ -0,0 +1,35 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ parent-boot-3
+ 0.0.1-SNAPSHOT
+ ../../parent-boot-3
+
+ spring-data-jpa-repo-3
+ 0.0.1-SNAPSHOT
+ spring-data-jpa-repo-3
+ spring-data-jpa-repo-3
+
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+
+
+
+ com.h2database
+ h2
+ runtime
+
+
+ org.springframework.boot
+ spring-boot-starter-test
+ test
+
+
+
+
+
diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/Application.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/Application.java
new file mode 100644
index 0000000000..13d9dbf414
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/Application.java
@@ -0,0 +1,12 @@
+package com.baeldung.spring.data.jpa.listrepositories;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class Application {
+
+ public static void main(String[] args) {
+ SpringApplication.run(SpringBootApplication.class, args);
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Book.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Book.java
new file mode 100644
index 0000000000..40f9f689a6
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Book.java
@@ -0,0 +1,57 @@
+package com.baeldung.spring.data.jpa.listrepositories.entity;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+
+@Entity
+public class Book {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+ private String title;
+ private String author;
+ private String isbn;
+
+ public Book() {
+ }
+
+ public Book(String title, String author, String isbn) {
+ this.title = title;
+ this.author = author;
+ this.isbn = isbn;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getAuthor() {
+ return author;
+ }
+
+ public void setAuthor(String author) {
+ this.author = author;
+ }
+
+ public String getIsbn() {
+ return isbn;
+ }
+
+ public void setIsbn(String isbn) {
+ this.isbn = isbn;
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Library.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Library.java
new file mode 100644
index 0000000000..04c0ad5e0a
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/Library.java
@@ -0,0 +1,66 @@
+package com.baeldung.spring.data.jpa.listrepositories.entity;
+
+import jakarta.persistence.*;
+
+import java.util.ArrayList;
+import java.util.List;
+
+@Entity(name = "library")
+public class Library {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ private Long id;
+
+ private String name;
+
+ @Convert(converter = StringListConverter.class)
+ @Column(name = "addresses", nullable = false)
+ private List addresses = new ArrayList<>();
+
+ @ElementCollection(targetClass = String.class, fetch = FetchType.EAGER)
+ @CollectionTable(name = "book", joinColumns = @JoinColumn(name = "library_id"))
+ @Column(name = "book", nullable = false)
+ private List books = new ArrayList<>();
+
+ public Library() {
+ }
+
+ public Library(String name, List addresses, List books) {
+ this.name = name;
+ this.addresses = addresses;
+ this.books = books;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public List getAddresses() {
+ return addresses;
+ }
+
+ public void setAddresses(List addresses) {
+ this.addresses = addresses;
+ }
+
+ public List getBooks() {
+ return books;
+ }
+
+ public void setBooks(List books) {
+ this.books = books;
+ }
+}
diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/StringListConverter.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/StringListConverter.java
new file mode 100644
index 0000000000..ffc097ee18
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/entity/StringListConverter.java
@@ -0,0 +1,25 @@
+package com.baeldung.spring.data.jpa.listrepositories.entity;
+
+import jakarta.persistence.AttributeConverter;
+import jakarta.persistence.Converter;
+
+import java.util.Arrays;
+import java.util.List;
+
+
+import static java.util.Collections.*;
+
+@Converter
+public class StringListConverter implements AttributeConverter, String> {
+ private static final String SPLIT_CHAR = ";";
+
+ @Override
+ public String convertToDatabaseColumn(List stringList) {
+ return stringList != null ? String.join(SPLIT_CHAR, stringList) : "";
+ }
+
+ @Override
+ public List convertToEntityAttribute(String string) {
+ return string != null ? Arrays.asList(string.split(SPLIT_CHAR)) : emptyList();
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookListRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookListRepository.java
new file mode 100644
index 0000000000..aec8347850
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookListRepository.java
@@ -0,0 +1,13 @@
+package com.baeldung.spring.data.jpa.listrepositories.repository;
+
+import com.baeldung.spring.data.jpa.listrepositories.entity.Book;
+import org.springframework.data.repository.ListCrudRepository;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository
+public interface BookListRepository extends ListCrudRepository {
+
+ List findBooksByAuthor(String author);
+}
diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepository.java
new file mode 100644
index 0000000000..1b37b0d1ef
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepository.java
@@ -0,0 +1,15 @@
+package com.baeldung.spring.data.jpa.listrepositories.repository;
+
+import com.baeldung.spring.data.jpa.listrepositories.entity.Book;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.repository.ListCrudRepository;
+import org.springframework.data.repository.PagingAndSortingRepository;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+
+@Repository
+public interface BookPagingAndSortingRepository extends PagingAndSortingRepository, ListCrudRepository {
+
+ List findBooksByAuthor(String author, Pageable pageable);
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryRepository.java b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryRepository.java
new file mode 100644
index 0000000000..71deb04b3e
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/src/main/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryRepository.java
@@ -0,0 +1,13 @@
+package com.baeldung.spring.data.jpa.listrepositories.repository;
+
+import com.baeldung.spring.data.jpa.listrepositories.entity.Library;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.CrudRepository;
+import org.springframework.data.repository.query.Param;
+import org.springframework.stereotype.Repository;
+
+@Repository
+public interface LibraryRepository extends CrudRepository {
+ @Query("SELECT l FROM library l JOIN FETCH l.books WHERE l.id = (:id)")
+ Library findById(@Param("id") long id);
+}
diff --git a/persistence-modules/spring-data-jpa-repo-3/src/main/resources/application.properties b/persistence-modules/spring-data-jpa-repo-3/src/main/resources/application.properties
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/src/main/resources/application.properties
@@ -0,0 +1 @@
+
diff --git a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookListRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookListRepositoryIntegrationTest.java
new file mode 100644
index 0000000000..d004d485e4
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookListRepositoryIntegrationTest.java
@@ -0,0 +1,28 @@
+package com.baeldung.spring.data.jpa.listrepositories.repository;
+
+import com.baeldung.spring.data.jpa.listrepositories.entity.Book;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+
+import java.util.Arrays;
+import java.util.List;
+
+@SpringBootTest
+public class BookListRepositoryIntegrationTest {
+
+ @Autowired
+ private BookListRepository bookListRepository;
+
+ @Test
+ public void givenDbContainsBooks_whenFindBooksByAuthor_thenReturnBooksByAuthor() {
+ Book book1 = new Book("Spring Data", "John Doe", "1234567890");
+ Book book2 = new Book("Spring Data 2", "John Doe", "1234567891");
+ Book book3 = new Book("Spring Data 3", "John Doe", "1234567892");
+ bookListRepository.saveAll(Arrays.asList(book1, book2, book3));
+
+ List books = bookListRepository.findBooksByAuthor("John Doe");
+ Assertions.assertEquals(3, books.size());
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepositoryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepositoryIntegrationTest.java
new file mode 100644
index 0000000000..8f34e43e3f
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/BookPagingAndSortingRepositoryIntegrationTest.java
@@ -0,0 +1,35 @@
+package com.baeldung.spring.data.jpa.listrepositories.repository;
+
+import com.baeldung.spring.data.jpa.listrepositories.entity.Book;
+import com.baeldung.spring.data.jpa.listrepositories.repository.BookPagingAndSortingRepository;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.data.domain.PageRequest;
+import org.springframework.data.domain.Pageable;
+import org.springframework.data.domain.Sort;
+
+import java.util.Arrays;
+import java.util.List;
+
+@SpringBootTest
+public class BookPagingAndSortingRepositoryIntegrationTest {
+
+ @Autowired
+ private BookPagingAndSortingRepository bookPagingAndSortingRepository;
+
+ @Test
+ public void givenDbContainsBooks_whenfindBooksByAuthor_thenReturnBooksByAuthor() {
+ Book book1 = new Book("Spring Data", "John Doe", "1234567890");
+ Book book2 = new Book("Spring Data 2", "John Doe", "1234567891");
+ Book book3 = new Book("Spring Data 3", "John Doe", "1234567892");
+ bookPagingAndSortingRepository.saveAll(Arrays.asList(book1, book2, book3));
+
+ Pageable pageable = PageRequest.of(0, 2, Sort.by("title").descending());
+ List books = bookPagingAndSortingRepository.findBooksByAuthor("John Doe", pageable);
+ Assertions.assertEquals(2, books.size());
+ Assertions.assertEquals(book3.getId(), books.get(0).getId());
+ Assertions.assertEquals(book2.getId(), books.get(1).getId());
+ }
+}
\ No newline at end of file
diff --git a/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryIntegrationTest.java b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryIntegrationTest.java
new file mode 100644
index 0000000000..7bd1b90407
--- /dev/null
+++ b/persistence-modules/spring-data-jpa-repo-3/src/test/java/com/baeldung/spring/data/jpa/listrepositories/repository/LibraryIntegrationTest.java
@@ -0,0 +1,32 @@
+package com.baeldung.spring.data.jpa.listrepositories.repository;
+
+import com.baeldung.spring.data.jpa.listrepositories.entity.Library;
+import jakarta.transaction.Transactional;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+
+import java.util.Arrays;
+
+@SpringBootTest
+public class LibraryIntegrationTest {
+
+ @Autowired
+ private LibraryRepository libraryRepository;
+
+ @Test
+ @Transactional
+ public void givenLibrary_whenGetAddressesAndGetBooks_thenGetListOfItems(){
+ Library library = new Library();
+ library.setAddresses(Arrays.asList("Address 1", "Address 2"));
+ library.setBooks(Arrays.asList("Book 1", "Book 2"));
+
+ libraryRepository.save(library);
+ Library lib = libraryRepository.findById(library.getId().longValue());
+
+ Assertions.assertEquals(2, lib.getAddresses().size());
+ Assertions.assertEquals(2, lib.getBooks().size());
+ }
+
+}
diff --git a/persistence-modules/spring-data-rest/pom.xml b/persistence-modules/spring-data-rest/pom.xml
index f5601cb7ce..fa2cd033f5 100644
--- a/persistence-modules/spring-data-rest/pom.xml
+++ b/persistence-modules/spring-data-rest/pom.xml
@@ -11,9 +11,9 @@
com.baeldung
- parent-boot-2
+ parent-boot-3
0.0.1-SNAPSHOT
- ../../parent-boot-2
+ ../../parent-boot-3
@@ -42,6 +42,17 @@
spring-boot-starter-test
test
+
+ org.hibernate.orm
+ hibernate-community-dialects
+ ${hibernate-community-dialects.version}
+
+
+ io.rest-assured
+ rest-assured
+ 3.3.0
+ test
+
com.h2database
h2
@@ -64,23 +75,6 @@
${project.artifactId}
-
- com.mysema.maven
- maven-apt-plugin
- ${maven.version}
-
-
- generate-sources
-
- process
-
-
- target/generated-sources
- com.querydsl.apt.jpa.JPAAnnotationProcessor
-
-
-
-
org.springframework.boot
spring-boot-maven-plugin
@@ -91,6 +85,7 @@
com.baeldung.books.SpringDataRestApplication
1.0
+ 6.1.7.Final
\ No newline at end of file
diff --git a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java
deleted file mode 100644
index 6e840eec43..0000000000
--- a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteDialect.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package com.baeldung.books.dialect;
-
-import org.hibernate.dialect.Dialect;
-import org.hibernate.dialect.identity.IdentityColumnSupport;
-
-import java.sql.Types;
-
-public class SQLiteDialect extends Dialect {
-
- public SQLiteDialect() {
- registerColumnType(Types.BIT, "integer");
- registerColumnType(Types.TINYINT, "tinyint");
- registerColumnType(Types.SMALLINT, "smallint");
- registerColumnType(Types.INTEGER, "integer");
- registerColumnType(Types.BIGINT, "bigint");
- registerColumnType(Types.FLOAT, "float");
- registerColumnType(Types.REAL, "real");
- registerColumnType(Types.DOUBLE, "double");
- registerColumnType(Types.NUMERIC, "numeric");
- registerColumnType(Types.DECIMAL, "decimal");
- registerColumnType(Types.CHAR, "char");
- registerColumnType(Types.VARCHAR, "varchar");
- registerColumnType(Types.LONGVARCHAR, "longvarchar");
- registerColumnType(Types.DATE, "date");
- registerColumnType(Types.TIME, "time");
- registerColumnType(Types.TIMESTAMP, "timestamp");
- registerColumnType(Types.BINARY, "blob");
- registerColumnType(Types.VARBINARY, "blob");
- registerColumnType(Types.LONGVARBINARY, "blob");
- registerColumnType(Types.BLOB, "blob");
- registerColumnType(Types.CLOB, "clob");
- registerColumnType(Types.BOOLEAN, "integer");
- }
-
- public IdentityColumnSupport getIdentityColumnSupport() {
- return new SQLiteIdentityColumnSupport();
- }
-
- public boolean hasAlterTable() {
- return false;
- }
-
- public boolean dropConstraints() {
- return false;
- }
-
- public String getDropForeignKeyString() {
- return "";
- }
-
- public String getAddForeignKeyConstraintString(String constraintName, String[] foreignKey, String referencedTable, String[] primaryKey, boolean referencesPrimaryKey) {
- return "";
- }
-
- public String getAddPrimaryKeyConstraintString(String constraintName) {
- return "";
- }
-
- public String getForUpdateString() {
- return "";
- }
-
- public String getAddColumnString() {
- return "add column";
- }
-
- public boolean supportsOuterJoinForUpdate() {
- return false;
- }
-
- public boolean supportsIfExistsBeforeTableName() {
- return true;
- }
-
- public boolean supportsCascadeDelete() {
- return false;
- }
-}
diff --git a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java
deleted file mode 100644
index 682d82c6f1..0000000000
--- a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/dialect/SQLiteIdentityColumnSupport.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.baeldung.books.dialect;
-
-import org.hibernate.MappingException;
-import org.hibernate.dialect.identity.IdentityColumnSupportImpl;
-
-public class SQLiteIdentityColumnSupport extends IdentityColumnSupportImpl {
-
- @Override
- public boolean supportsIdentityColumns() {
- return true;
- }
-
- @Override
- public String getIdentitySelectString(String table, String column, int type) throws MappingException {
- return "select last_insert_rowid()";
- }
-
- @Override
- public String getIdentityColumnString(int type) throws MappingException {
- return "integer";
- }
-}
diff --git a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Address.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Address.java
index 3c36db0f3c..2627c21615 100644
--- a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Address.java
+++ b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Address.java
@@ -1,11 +1,11 @@
package com.baeldung.books.models;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.OneToOne;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.OneToOne;
@Entity
public class Address {
diff --git a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Author.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Author.java
index aec2e62ebf..385113d800 100644
--- a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Author.java
+++ b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Author.java
@@ -2,15 +2,15 @@ package com.baeldung.books.models;
import java.util.List;
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.JoinTable;
-import javax.persistence.ManyToMany;
+import jakarta.persistence.CascadeType;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.JoinTable;
+import jakarta.persistence.ManyToMany;
@Entity
public class Author {
diff --git a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Book.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Book.java
index 7451b04b3b..ea3fb325c1 100644
--- a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Book.java
+++ b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Book.java
@@ -2,15 +2,15 @@ package com.baeldung.books.models;
import java.util.List;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToMany;
-import javax.persistence.ManyToOne;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.FetchType;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.ManyToMany;
+import jakarta.persistence.ManyToOne;
@Entity
public class Book {
diff --git a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Library.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Library.java
index 5f95169a9b..28a54dbd33 100644
--- a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Library.java
+++ b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Library.java
@@ -2,14 +2,14 @@ package com.baeldung.books.models;
import java.util.List;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.OneToMany;
-import javax.persistence.OneToOne;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.JoinColumn;
+import jakarta.persistence.OneToMany;
+import jakarta.persistence.OneToOne;
import org.springframework.data.rest.core.annotation.RestResource;
diff --git a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java
index 11a4425fdd..28d16f5054 100644
--- a/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java
+++ b/persistence-modules/spring-data-rest/src/main/java/com/baeldung/books/models/Subject.java
@@ -1,10 +1,10 @@
package com.baeldung.books.models;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.GeneratedValue;
-import javax.persistence.GenerationType;
-import javax.persistence.Id;
+import jakarta.persistence.Column;
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
@Entity
public class Subject {
diff --git a/persistence-modules/spring-data-rest/src/main/resources/persistence-sqlite.properties b/persistence-modules/spring-data-rest/src/main/resources/persistence-sqlite.properties
index b6b5f4e4d6..e570322a82 100644
--- a/persistence-modules/spring-data-rest/src/main/resources/persistence-sqlite.properties
+++ b/persistence-modules/spring-data-rest/src/main/resources/persistence-sqlite.properties
@@ -2,6 +2,6 @@ driverClassName=org.sqlite.JDBC
url=jdbc:sqlite:memory:myDb?cache=shared
username=sa
password=sa
-hibernate.dialect=com.baeldung.dialect.SQLiteDialect
+spring.jpa.database-platform=org.hibernate.community.dialect.SQLiteDialect
hibernate.hbm2ddl.auto=create-drop
hibernate.show_sql=true
diff --git a/persistence-modules/spring-jpa-2/README.md b/persistence-modules/spring-jpa-2/README.md
index f9f259cdfa..c1068b6a39 100644
--- a/persistence-modules/spring-jpa-2/README.md
+++ b/persistence-modules/spring-jpa-2/README.md
@@ -7,4 +7,5 @@
- [The DAO with Spring and Hibernate](https://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
- [Simplify the DAO with Spring and Java Generics](https://www.baeldung.com/simplifying-the-data-access-layer-with-spring-and-java-generics)
- [Multitenancy With Spring Data JPA](https://www.baeldung.com/multitenancy-with-spring-data-jpa)
+- [Remove Entity with Many-to-Many Relationship in JPA](https://www.baeldung.com/jpa-remove-entity-many-to-many)
- More articles: [[<-- prev]](/spring-jpa)
diff --git a/persistence-modules/spring-jpa-2/pom.xml b/persistence-modules/spring-jpa-2/pom.xml
index 19bc9cba14..974dd41df9 100644
--- a/persistence-modules/spring-jpa-2/pom.xml
+++ b/persistence-modules/spring-jpa-2/pom.xml
@@ -101,7 +101,7 @@
- 5.1.5.RELEASE
+ 5.2.0.RELEASE
2.2.6.RELEASE
9.0.0.M26
diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Application.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Application.java
new file mode 100644
index 0000000000..7b8551ee0c
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Application.java
@@ -0,0 +1,12 @@
+package com.baeldung.manytomanyremoval;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+@SpringBootApplication
+public class Application {
+
+ public static void main(String[] args) {
+ SpringApplication.run(Application.class, args);
+ }
+}
diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Author.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Author.java
new file mode 100644
index 0000000000..d9906a21cd
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Author.java
@@ -0,0 +1,62 @@
+package com.baeldung.manytomanyremoval;
+
+import javax.persistence.*;
+import java.util.HashSet;
+import java.util.Set;
+
+@Entity
+@Table(name = "author")
+public class Author {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "id")
+ private Long id;
+
+ @Column(name = "name")
+ private String name;
+
+ @ManyToMany(mappedBy = "authors")
+ private Set books = new HashSet<>();
+
+ // standard getters and setters
+
+ public Author() {
+ }
+
+ public Author(String name) {
+ this.name = name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public Set getBooks() {
+ return books;
+ }
+
+ public void setBooks(Set books) {
+ this.books = books;
+ }
+
+ @PreRemove
+ private void removeBookAssociations() {
+ for (Book book : this.books) {
+ book.getAuthors().remove(this);
+ }
+ }
+
+}
diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Book.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Book.java
new file mode 100644
index 0000000000..4b49acd000
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Book.java
@@ -0,0 +1,65 @@
+package com.baeldung.manytomanyremoval;
+
+
+import javax.persistence.*;
+import java.util.HashSet;
+import java.util.Set;
+
+@Entity
+@Table(name = "book")
+public class Book {
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "id")
+ private Long id;
+
+ @Column(name = "title")
+ private String title;
+
+ @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
+ @JoinTable(name = "book_author",
+ joinColumns = @JoinColumn(name = "book_id"),
+ inverseJoinColumns = @JoinColumn(name = "author_id")
+ )
+ private Set authors = new HashSet<>();
+
+ // standard getters and setters
+
+ public Book() {
+ }
+
+ public Book(String title) {
+ this.title = title;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public Set getAuthors() {
+ return authors;
+ }
+
+ public void removeAuthor(Author author) {
+ this.authors.remove(author);
+ author.getBooks().remove(this);
+ }
+
+ public void addAuthor(Author author) {
+ authors.add(author);
+ author.getBooks().add(this);
+ }
+
+}
diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Category.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Category.java
new file mode 100644
index 0000000000..f7202f544c
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Category.java
@@ -0,0 +1,41 @@
+package com.baeldung.manytomanyremoval;
+
+import javax.persistence.*;
+
+@Entity
+@Table(name = "category")
+public class Category {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "id")
+ private Long id;
+
+ @Column(name = "name")
+ private String name;
+
+ // getters and setters
+
+ public Category() {
+ }
+
+ public Category(String name) {
+ this.name = name;
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Post.java b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Post.java
new file mode 100644
index 0000000000..d229a9d0d7
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/main/java/com/baeldung/manytomanyremoval/Post.java
@@ -0,0 +1,59 @@
+package com.baeldung.manytomanyremoval;
+
+
+import javax.persistence.*;
+import java.util.HashSet;
+import java.util.Set;
+
+@Entity
+@Table(name = "post")
+public class Post {
+
+ @Id
+ @GeneratedValue(strategy = GenerationType.IDENTITY)
+ @Column(name = "id")
+ private Long id;
+
+ @Column(name = "title")
+ private String title;
+
+ @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
+ @JoinTable(name = "post_category",
+ joinColumns = @JoinColumn(name = "post_id"),
+ inverseJoinColumns = @JoinColumn(name = "category_id")
+ )
+ private Set categories = new HashSet<>();
+
+ // getters and setters
+
+ public Post(String title) {
+ this.title = title;
+ }
+
+ public Post() {
+ }
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public Set getCategories() {
+ return categories;
+ }
+
+ public void setCategories(Set categories) {
+ this.categories = categories;
+ }
+}
diff --git a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomanyremoval/BidirectionalRemovalUnitTest.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomanyremoval/BidirectionalRemovalUnitTest.java
new file mode 100644
index 0000000000..f214fcdc2a
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomanyremoval/BidirectionalRemovalUnitTest.java
@@ -0,0 +1,78 @@
+package com.baeldung.manytomanyremoval;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.persistence.EntityManager;
+
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = TestContextConfig.class)
+@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
+@Transactional
+class BidirectionalRemovalUnitTest {
+
+ @Autowired
+ private EntityManager entityManager;
+
+ @BeforeEach
+ void init() {
+ Author author1 = new Author("Erich Gamma");
+ Author author2 = new Author("John Vlissides");
+ Author author3 = new Author("Ralph Johnson");
+ Author author4 = new Author("Richard Helm");
+
+ Book book = new Book();
+ book.setTitle("GOF Java");
+ book.addAuthor(author1);
+ book.addAuthor(author2);
+ book.addAuthor(author3);
+ book.addAuthor(author4);
+ entityManager.persist(book);
+
+ Book book2 = new Book();
+ book2.setTitle("A Lost Age");
+ book2.addAuthor(author3);
+ entityManager.persist(book2);
+ }
+
+ @Test
+ void givenEntities_whenRemoveFromOwner_thenRemoveAssociation() {
+ Author author = (Author) entityManager
+ .createQuery("SELECT author from Author author where author.name = ?1")
+ .setParameter(1, "Ralph Johnson")
+ .getSingleResult();
+
+ Book book1 = entityManager.find(Book.class, 1L);
+ Book book2 = entityManager.find(Book.class, 2L);
+
+ book1.removeAuthor(author);
+ entityManager.persist(book1);
+
+ Assertions.assertEquals(3, book1.getAuthors().size());
+ Assertions.assertEquals(1, book2.getAuthors().size());
+ }
+
+ @Transactional
+ @Test
+ void givenEntities_whenRemoveFromNotOwner_thenRemoveAssociation() {
+ Author author = (Author) entityManager
+ .createQuery("SELECT author from Author author where author.name = ?1")
+ .setParameter(1, "Ralph Johnson")
+ .getSingleResult();
+ Book book1 = entityManager.find(Book.class, 1L);
+ Book book2 = entityManager.find(Book.class, 2L);
+
+ entityManager.remove(author);
+
+ Assertions.assertEquals(3, book1.getAuthors().size());
+ Assertions.assertEquals(0, book2.getAuthors().size());
+ }
+}
+
diff --git a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomanyremoval/TestContextConfig.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomanyremoval/TestContextConfig.java
new file mode 100644
index 0000000000..6a840824de
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomanyremoval/TestContextConfig.java
@@ -0,0 +1,12 @@
+package com.baeldung.manytomanyremoval;
+
+import org.springframework.context.annotation.ComponentScan;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+
+@Configuration
+@PropertySource("classpath:/manytomanyremoval/test.properties")
+@ComponentScan("com.baeldung.manytomanyremoval")
+public class TestContextConfig {
+
+}
diff --git a/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomanyremoval/UnidirectionalRemovalUnitTest.java b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomanyremoval/UnidirectionalRemovalUnitTest.java
new file mode 100644
index 0000000000..b23b589fb7
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/test/java/com/baeldung/manytomanyremoval/UnidirectionalRemovalUnitTest.java
@@ -0,0 +1,55 @@
+package com.baeldung.manytomanyremoval;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.annotation.DirtiesContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+import org.springframework.transaction.annotation.Transactional;
+
+import javax.persistence.EntityManager;
+
+@ExtendWith(SpringExtension.class)
+@ContextConfiguration(classes = TestContextConfig.class)
+@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
+@Transactional
+class UnidirectionalRemovalUnitTest {
+
+ @Autowired
+ private EntityManager entityManager;
+
+ @BeforeEach
+ void init() {
+ Category category1 = new Category("JPA");
+ Category category2 = new Category("Persistence");
+
+ Post post1 = new Post("Many-to-Many Relationship");
+ post1.getCategories().add(category1);
+ post1.getCategories().add(category2);
+
+ Post post2 = new Post("Entity Manager");
+ post2.getCategories().add(category1);
+
+ entityManager.persist(post1);
+ entityManager.persist(post2);
+
+ Assertions.assertEquals(2, post1.getCategories().size());
+ Assertions.assertEquals(1, post2.getCategories().size());
+ }
+
+ @Test
+ void givenEntities_whenRemove_thenRemoveAssociation() {
+ Post post1 = entityManager.find(Post.class, 1L);
+ Post post2 = entityManager.find(Post.class, 2L);
+ Category category = entityManager.find(Category.class, 1L);
+
+ post1.getCategories().remove(category);
+
+ Assertions.assertEquals(1, post1.getCategories().size());
+ Assertions.assertEquals(1, post2.getCategories().size());
+ }
+
+}
diff --git a/persistence-modules/spring-jpa-2/src/test/resources/manytomanyremoval/test.properties b/persistence-modules/spring-jpa-2/src/test/resources/manytomanyremoval/test.properties
new file mode 100644
index 0000000000..83479cd453
--- /dev/null
+++ b/persistence-modules/spring-jpa-2/src/test/resources/manytomanyremoval/test.properties
@@ -0,0 +1,11 @@
+spring.datasource.url=jdbc:h2:mem:mydb;MODE=LEGACY;
+spring.datasource.driverClassName=org.h2.Driver
+spring.datasource.username=sa
+spring.datasource.password=
+
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.hbm2ddl.auto=none
+spring.jpa.show-sql=true
+spring.jpa.hibernate.dialect=org.hibernate.dialect.H2Dialect
+spring.jpa.hibernate.ddl-auto=create-drop
+
diff --git a/persistence-modules/spring-persistence-simple/src/main/resources/com/baeldung/spring/jndi/datasource/mock/datasource.properties b/persistence-modules/spring-persistence-simple/src/main/resources/com/baeldung/spring/jndi/datasource/mock/datasource.properties
index 8be94daf36..6a803f5f4c 100644
--- a/persistence-modules/spring-persistence-simple/src/main/resources/com/baeldung/spring/jndi/datasource/mock/datasource.properties
+++ b/persistence-modules/spring-persistence-simple/src/main/resources/com/baeldung/spring/jndi/datasource/mock/datasource.properties
@@ -1,5 +1,5 @@
ds.type=javax.sql.DataSource
ds.driver=org.h2.Driver
-ds.url=jdbc:jdbc:h2:mem:testdb
+ds.url=jdbc:h2:mem:testdb
ds.user=sa
ds.password=password
diff --git a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleJNDIUnitTest.java b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleJNDIUnitTest.java
index 6576962609..3788c0dde8 100644
--- a/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleJNDIUnitTest.java
+++ b/persistence-modules/spring-persistence-simple/src/test/java/com/baeldung/spring/jndi/datasource/mock/SimpleJNDIUnitTest.java
@@ -21,7 +21,7 @@ public class SimpleJNDIUnitTest {
@Test
public void whenMockJndiDataSource_thenReturnJndiDataSource() throws Exception {
- String dsString = "org.h2.Driver::::jdbc:jdbc:h2:mem:testdb::::sa";
+ String dsString = "org.h2.Driver::::jdbc:h2:mem:testdb::::sa";
Context envContext = (Context) this.initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup("datasource/ds");
diff --git a/pom.xml b/pom.xml
index 3994c713c8..996ebdc459 100644
--- a/pom.xml
+++ b/pom.xml
@@ -222,6 +222,9 @@
maven-war-plugin
${maven-war-plugin.version}
+
+ false
+
@@ -330,89 +333,41 @@
parent-spring-5
parent-java
- apache-cxf-modules
+ checker-framework
+
- azure
- checker-plugin
-
+ core-java-modules/core-java-8
+ core-java-modules/core-java-8-2
+ core-java-modules/core-java-8-datetime
+ core-java-modules/core-java-8-datetime-2
+ core-java-modules/core-java-sun
+ core-java-modules/core-java-security
+ core-java-modules/core-java-nio-2
+ core-java-modules/core-java-serialization
+ core-java-modules/core-java-lang
+ core-java-modules/core-java-lang-math-3
+ core-java-modules/core-java-collections-conversions-2
+ core-java-modules/core-java-streams-2
- core-groovy-modules
- core-java-modules
couchbase
-
- drools
gradle-modules/gradle/maven-to-gradle
-
- guava-modules
- apache-httpclient
- httpclient4
-
-
- jackson-modules
-
- javafx
- java-jdi
- java-websocket
-
- jaxb
- jersey
- jhipster-5
- jmeter
- jmh
-
- jsf
- json-modules
-
- kubernetes-modules
-
+ jetbrains
language-interop
- libraries-2
- libraries-3
- libraries-data
+ libraries-jdk8
- libraries-data-db
- libraries-security
- libraries-server-2
- libraries-testing
- logging-modules
- lombok-modules
+ lombok-modules/lombok-custom
- maven-modules
-
- messaging-modules
-
- microservices-modules
muleesb
-
- netflix-modules
-
- osgi
- orika
-
- patterns-modules
-
- performance-tests
- persistence-modules
-
-
- quarkus-modules
-
- rule-engines-modules
- rxjava-modules
-
- reactive-systems
- security-modules
-
- vavr-modules
- web-modules
+ persistence-modules/deltaspike
+ persistence-modules/hibernate-ogm
@@ -457,34 +412,15 @@
parent-spring-5
parent-java
- saas-modules
- server-modules
- spf4j
spring-4
spring-aop
- spring-aop-2
- spring-batch
- spring-bom
- spring-boot-modules
- spring-boot-rest
- spring-caching
+
spring-cloud-modules
- spring-core
- spring-core-4
- spring-di
- spring-di-2
- spring-drools
- spring-ejb-modules
spring-exceptions
spring-integration
spring-jenkins-pipeline
- spring-jersey
- spring-jinq
- spring-katharsis
- spring-mobile
- spring-remoting-modules
@@ -494,7 +430,6 @@
spring-spel
spring-static-resources
spring-swagger-codegen
- spring-vault
spring-web-modules
spring-websockets
static-analysis
@@ -550,18 +485,7 @@
jenkins-modules
jhipster-modules
- jhipster-5
jws
-
- libraries
- libraries-4
- libraries-5
- libraries-6
- spring-boot-modules/spring-boot-react
- spring-ejb-modules/ejb-beans
-
- vaadin
- vavr-modules
@@ -597,88 +521,39 @@
parent-spring-5
parent-java
- apache-cxf-modules
+ checker-framework
+
- azure
- checker-plugin
-
+ core-java-modules/core-java-8
+ core-java-modules/core-java-8-2
+ core-java-modules/core-java-8-datetime
+ core-java-modules/core-java-8-datetime-2
+ core-java-modules/core-java-sun
+ core-java-modules/core-java-security
+ core-java-modules/core-java-nio-2
+ core-java-modules/core-java-serialization
+ core-java-modules/core-java-lang
+ core-java-modules/core-java-lang-math-3
+ core-java-modules/core-java-collections-conversions-2
+ core-java-modules/core-java-streams-2
- core-groovy-modules
- core-java-modules
couchbase
- drools
gradle-modules/gradle/maven-to-gradle
-
- guava-modules
- apache-httpclient
- httpclient4
-
-
- jackson-modules
-
- javafx
- java-jdi
- java-websocket
-
- jaxb
- jersey
- jhipster-5
- jmeter
- jmh
-
- jsf
- json-modules
-
- kubernetes-modules
-
language-interop
- libraries-2
- libraries-3
- libraries-data
+ libraries-jdk8
- libraries-data-db
- libraries-security
- libraries-server-2
- libraries-testing
- logging-modules
- lombok-modules
-
- maven-modules
-
- messaging-modules
-
- microservices-modules
+ lombok-modules/lombok-custom
muleesb
-
- netflix-modules
-
- osgi
- orika
-
- patterns-modules
-
- performance-tests
- persistence-modules
-
-
- quarkus-modules
-
- rule-engines-modules
- rxjava-modules
-
- reactive-systems
- security-modules
-
- vavr-modules
- web-modules
+ persistence-modules/deltaspike
+ persistence-modules/hibernate-ogm
@@ -715,33 +590,14 @@
parent-spring-5
parent-java
- saas-modules
- server-modules
- spf4j
spring-4
- spring-aop
- spring-aop-2
- spring-batch
- spring-bom
- spring-boot-modules
- spring-boot-rest
- spring-caching
+
spring-cloud-modules
- spring-core
- spring-core-4
- spring-di
- spring-di-2
- spring-drools
- spring-ejb-modules
+
spring-exceptions
spring-integration
spring-jenkins-pipeline
- spring-jersey
- spring-jinq
- spring-katharsis
- spring-mobile
- spring-remoting-modules
@@ -751,7 +607,6 @@
spring-spel
spring-static-resources
spring-swagger-codegen
- spring-vault
spring-web-modules
spring-websockets
static-analysis
@@ -799,17 +654,7 @@
jenkins-modules
jhipster-modules
- jhipster-5
jws
-
- libraries
- libraries-4
- libraries-5
- libraries-6
- spring-boot-modules/spring-boot-react
- spring-ejb-modules/ejb-beans
- vaadin
- vavr-modules
@@ -875,6 +720,58 @@
+ lombok-modules
+ osgi
+ spring-katharsis
+ logging-modules
+ spring-boot-modules
+ apache-httpclient
+ apache-httpclient4
+ apache-httpclient-2
+ spring-mobile
+ microservices-modules
+ spring-ejb-modules
+ spring-di
+ spring-di-2
+ spring-jinq
+ vavr-modules
+ java-websocket
+ azure
+ netflix-modules
+ spf4j
+ spring-jersey
+ jersey
+ jaxb
+
+ javafx
+ spring-batch
+ spring-batch-2
+ spring-boot-rest
+ spring-drools
+ spring-exceptions
+ spring-jenkins-pipeline
+ spring-core
+ spring-core-4
+ spring-integration
+ spring-remoting-modules
+ libraries-security
+ libraries-data-db
+
+ performance-tests
+ security-modules
+ libraries-server-2
+ orika
+ patterns-modules
+ json-modules
+ libraries-data
+ saas-modules
+ server-modules
+ apache-cxf-modules
+
+ spring-aop
+ jmeter
+ spring-aop-2
+
algorithms-modules
apache-libraries
apache-poi
@@ -882,15 +779,12 @@
di-modules
asciidoctor
aws-modules
- core-java-modules/core-java-9
- core-java-modules/core-java-9-improvements
- core-java-modules/core-java-9-jigsaw
+
+ couchbase
+ core-groovy-modules
+
+ core-java-modules
- core-java-modules/core-java-9-streams
- core-java-modules/core-java-10
- core-java-modules/core-java-11
- core-java-modules/core-java-11-2
- core-java-modules/core-java-11-3
@@ -898,53 +792,34 @@
- core-java-modules/core-java-collections-set
- core-java-modules/core-java-collections-list-4
- core-java-modules/core-java-collections-array-list
- core-java-modules/core-java-collections-maps-4
- core-java-modules/core-java-collections-maps-5
- core-java-modules/core-java-concurrency-simple
- core-java-modules/core-java-date-operations-1
- core-java-modules/core-java-datetime-conversion
- core-java-modules/core-java-datetime-string
- core-java-modules/core-java-io-conversions-2
- core-java-modules/core-java-jpms
- core-java-modules/core-java-os
- core-java-modules/core-java-streams-4
- core-java-modules/core-java-string-algorithms-3
- core-java-modules/core-java-string-operations-3
- core-java-modules/core-java-string-operations-4
- core-java-modules/core-java-string-operations-5
- core-java-modules/core-java-time-measurements
- core-java-modules/core-java-networking-3
- core-java-modules/core-java-strings
- core-java-modules/core-java-httpclient
- custom-pmd
- spring-core-6
+ custom-pmd
data-structures
ddd-contexts
+ jackson-modules
+ jmh
deeplearning4j
docker-modules
- apache-httpclient-2
- kubernetes-modules/kubernetes-spring
+ drools
+ guava-modules
+ kubernetes-modules
libraries-concurrency
- maven-modules/compiler-plugin-java-9
- maven-modules/maven-generate-war
- maven-modules/multimodulemavenproject
+ jhipster-6
+ libraries-testing
+ maven-modules
optaplanner
- persistence-modules/sirix
- persistence-modules/spring-data-cassandra-2
- quarkus-modules/quarkus-vs-springboot
- quarkus-modules/quarkus-jandex
- spring-boot-modules/spring-boot-cassandre
- spring-boot-modules/spring-boot-3
- spring-boot-modules/spring-boot-3-native
- spring-boot-modules/spring-boot-3-observation
- spring-boot-modules/spring-boot-3-test-pitfalls
+ persistence-modules
+ quarkus-modules
spring-reactive-modules
spring-swagger-codegen/custom-validations-opeanpi-codegen
testing-modules/testing-assertions
persistence-modules/fauna
+ persistence-modules/spring-data-rest
+
+ rule-engines-modules
+
+ reactive-systems
+ rxjava-modules
+
lightrun
tablesaw
geotools
@@ -953,7 +828,6 @@
akka-modules
annotations
- apache-httpclient
httpclient-simple
antlr
apache-kafka
@@ -961,23 +835,22 @@
apache-olingo
apache-poi-2
- apache-rocketmq
apache-thrift
apache-tika
asm
atomikos
atomix
+
axon
bazel
- code-generation
+ google-auto-project
ddd
- discord4j
disruptor
dozer
dubbo
- feign
+
google-cloud
graphql-modules
grpc
@@ -985,7 +858,7 @@
hystrix
jackson-simple
java-blockchain
-
+ java-jdi
java-rmi
java-spi
javax-sound
@@ -998,7 +871,14 @@
java-native
jsoup
ksqldb
- libraries-7
+ jsf
+
+ libraries
+ libraries-2
+ libraries-4
+ libraries-5
+ libraries-6
+
libraries-apache-commons
libraries-apache-commons-collections
libraries-apache-commons-io
@@ -1023,7 +903,6 @@
protobuffer
reactor-core
rsocket
- slack
@@ -1031,17 +910,16 @@
spring-5-webflux
spring-5-webflux-2
spring-activiti
- spring-batch-2
- spring-caching-2
spring-core-2
spring-core-3
- spring-core-5
+ spring-credhub
spring-di-3
spring-cucumber
spring-kafka
spring-native
+ spring-security-modules/spring-security-oauth2-testing
spring-protobuf
spring-quartz
@@ -1049,16 +927,30 @@
spring-state-machine
spring-threads
+ spring-vault
tensorflow-java
xstream
webrtc
- messaging-modules/spring-apache-camel
+ persistence-modules/java-mongodb
+
+ messaging-modules
+
+ persistence-modules/questdb
+ vaadin
+ libraries-3
+ web-modules/apache-tapestry
+ web-modules/blade
+ web-modules/bootique
+ web-modules/dropwizard
+ web-modules/google-web-toolkit
+ web-modules/jakarta-ee
UTF-8
11
- 11
+ 11
+ 11
@@ -1085,6 +977,54 @@
+ lombok-modules
+ osgi
+ spring-katharsis
+ logging-modules
+ spring-boot-modules
+ apache-httpclient
+ apache-httpclient4
+ apache-httpclient-2
+ spring-mobile
+ microservices-modules
+ spring-ejb-modules
+ spring-di
+ spring-di-2
+ spring-jinq
+ vavr-modules
+ java-websocket
+ azure
+ netflix-modules
+ spf4j
+ spring-jersey
+ jersey
+ jaxb
+
+ javafx
+ spring-batch
+ spring-batch-2
+ spring-boot-rest
+ spring-drools
+ spring-exceptions
+ spring-jenkins-pipeline
+ spring-core
+ spring-core-4
+ spring-integration
+ spring-remoting-modules
+ libraries-security
+ libraries-data-db
+
+ performance-tests
+ security-modules
+ libraries-server-2
+ orika
+ patterns-modules
+ json-modules
+ libraries-data
+ saas-modules
+ server-modules
+ apache-cxf-modules
+
algorithms-modules
apache-libraries
apache-poi
@@ -1093,15 +1033,12 @@
asciidoctor
aws-modules
- core-java-modules/core-java-9
- core-java-modules/core-java-9-improvements
- core-java-modules/core-java-9-jigsaw
+ couchbase
+
+ core-groovy-modules
+
+ core-java-modules
- core-java-modules/core-java-9-streams
- core-java-modules/core-java-10
- core-java-modules/core-java-11
- core-java-modules/core-java-11-2
- core-java-modules/core-java-11-3
@@ -1109,53 +1046,37 @@
- core-java-modules/core-java-collections-set
- core-java-modules/core-java-collections-list-4
- core-java-modules/core-java-collections-array-list
- core-java-modules/core-java-collections-maps-4
- core-java-modules/core-java-collections-maps-5
- core-java-modules/core-java-concurrency-simple
- core-java-modules/core-java-date-operations-1
- core-java-modules/core-java-datetime-conversion
- core-java-modules/core-java-datetime-string
- core-java-modules/core-java-io-conversions-2
- core-java-modules/core-java-jpms
- core-java-modules/core-java-os
- core-java-modules/core-java-streams-4
- core-java-modules/core-java-string-algorithms-3
- core-java-modules/core-java-string-operations-3
- core-java-modules/core-java-string-operations-4
- core-java-modules/core-java-string-operations-5
- core-java-modules/core-java-time-measurements
- core-java-modules/core-java-networking-3
- core-java-modules/core-java-strings
- core-java-modules/core-java-httpclient
- custom-pmd
- spring-core-6
+ spring-aop
+ spring-aop-2
+ custom-pmd
data-structures
ddd-contexts
+ jackson-modules
+ jmh
deeplearning4j
+ jmeter
docker-modules
- apache-httpclient-2
- kubernetes-modules/kubernetes-spring
+ drools
+ guava-modules
+ kubernetes-modules
libraries-concurrency
- maven-modules/compiler-plugin-java-9
- maven-modules/maven-generate-war
- maven-modules/multimodulemavenproject
+ jhipster-6
+ libraries-testing
+ maven-modules
optaplanner
- persistence-modules/sirix
- persistence-modules/spring-data-cassandra-2
- quarkus-modules/quarkus-vs-springboot
- quarkus-modules/quarkus-jandex
- spring-boot-modules/spring-boot-cassandre
- spring-boot-modules/spring-boot-3
- spring-boot-modules/spring-boot-3-native
- spring-boot-modules/spring-boot-3-observation
- spring-boot-modules/spring-boot-3-test-pitfalls
+ persistence-modules
+ quarkus-modules
spring-reactive-modules
spring-swagger-codegen/custom-validations-opeanpi-codegen
testing-modules/testing-assertions
persistence-modules/fauna
+ persistence-modules/spring-data-rest
+
+ rule-engines-modules
+
+ reactive-systems
+ rxjava-modules
+
lightrun
tablesaw
geotools
@@ -1164,31 +1085,29 @@
akka-modules
annotations
- apache-httpclient
antlr
apache-kafka
apache-kafka-2
apache-olingo
apache-poi-2
- apache-rocketmq
apache-thrift
apache-tika
asm
atomikos
atomix
+
axon
bazel
- code-generation
+ google-auto-project
ddd
- discord4j
disruptor
dozer
dubbo
- feign
+
google-cloud
graphql-modules
grpc
@@ -1197,7 +1116,7 @@
hystrix
jackson-simple
java-blockchain
-
+ java-jdi
java-rmi
java-spi
javax-sound
@@ -1209,9 +1128,14 @@
java-native
jsoup
+ jsf
ksqldb
- libraries-7
+ libraries
+ libraries-2
+ libraries-4
+ libraries-5
+ libraries-6
libraries-apache-commons
libraries-apache-commons-collections
libraries-apache-commons-io
@@ -1221,6 +1145,7 @@
libraries-http
libraries-http-2
libraries-io
+ libraries-ai
libraries-primitive
libraries-rpc
libraries-server
@@ -1236,7 +1161,6 @@
protobuffer
reactor-core
rsocket
- slack
@@ -1245,11 +1169,9 @@
spring-5-webflux
spring-5-webflux-2
spring-activiti
- spring-batch-2
- spring-caching-2
spring-core-2
spring-core-3
- spring-core-5
+ spring-credhub
spring-di-3
spring-cucumber
@@ -1263,16 +1185,30 @@
spring-state-machine
spring-threads
+ spring-vault
tensorflow-java
xstream
webrtc
- messaging-modules/spring-apache-camel
+ persistence-modules/java-mongodb
+
+ messaging-modules
+
+ persistence-modules/questdb
+ vaadin
+ libraries-3
+ web-modules/apache-tapestry
+ web-modules/blade
+ web-modules/bootique
+ web-modules/dropwizard
+ web-modules/google-web-toolkit
+ web-modules/google-jakarta-ee
UTF-8
11
- 11
+ 11
+ 11
@@ -1318,6 +1254,7 @@
1.12.13
+
1.7.32
1.2.7
@@ -1336,15 +1273,15 @@
2.6
3.12.0
1.5.0
- 3.0.0
+ 3.3.2
4.0.1
1.2
2.3.3
1.2
2.13.3
1.4
- 1.8.1
- 5.8.1
+ 1.9.2
+ 5.9.2
1.3.2
0.3.1
2.5.2
diff --git a/quarkus-modules/pom.xml b/quarkus-modules/pom.xml
index 94fe1ae10f..ab9f7c3906 100644
--- a/quarkus-modules/pom.xml
+++ b/quarkus-modules/pom.xml
@@ -16,7 +16,8 @@
quarkus
quarkus-extension
-
+ quarkus-jandex
+ quarkus-vs-springboot
\ No newline at end of file
diff --git a/quarkus-modules/quarkus/pom.xml b/quarkus-modules/quarkus/pom.xml
index 3e1cbff01c..99d18579c3 100644
--- a/quarkus-modules/quarkus/pom.xml
+++ b/quarkus-modules/quarkus/pom.xml
@@ -182,7 +182,7 @@
- 1.7.0.Final
+ 2.16.3.Final
3.3.0
diff --git a/rule-engines-modules/easy-rules/pom.xml b/rule-engines-modules/easy-rules/pom.xml
index c8e875944c..6f43307e89 100644
--- a/rule-engines-modules/easy-rules/pom.xml
+++ b/rule-engines-modules/easy-rules/pom.xml
@@ -23,7 +23,7 @@
- 3.0.0
+ 4.1.0
\ No newline at end of file
diff --git a/rule-engines-modules/evrete/pom.xml b/rule-engines-modules/evrete/pom.xml
index d94da2853f..5b7f195722 100644
--- a/rule-engines-modules/evrete/pom.xml
+++ b/rule-engines-modules/evrete/pom.xml
@@ -30,7 +30,7 @@
- 2.1.04
+ 3.0.01
\ No newline at end of file
diff --git a/rule-engines-modules/openl-tablets/pom.xml b/rule-engines-modules/openl-tablets/pom.xml
index 204efce6c5..a24e06c44d 100644
--- a/rule-engines-modules/openl-tablets/pom.xml
+++ b/rule-engines-modules/openl-tablets/pom.xml
@@ -28,7 +28,7 @@
- 5.19.4
+ 5.26.5
\ No newline at end of file
diff --git a/rule-engines-modules/rulebook/pom.xml b/rule-engines-modules/rulebook/pom.xml
index 55e312289e..88feb148e2 100644
--- a/rule-engines-modules/rulebook/pom.xml
+++ b/rule-engines-modules/rulebook/pom.xml
@@ -23,7 +23,7 @@
- 0.6.2
+ 0.12
\ No newline at end of file
diff --git a/rxjava-modules/pom.xml b/rxjava-modules/pom.xml
index cd46270d92..2f2597b644 100644
--- a/rxjava-modules/pom.xml
+++ b/rxjava-modules/pom.xml
@@ -17,6 +17,7 @@
rxjava-core
+ rxjava-core-2
rxjava-libraries
rxjava-observables
rxjava-operators
diff --git a/rxjava-modules/rxjava-core-2/src/test/java/com/baeldung/rxjava/justvscallable/SingleJustVsFromCallableTest.java b/rxjava-modules/rxjava-core-2/src/test/java/com/baeldung/rxjava/justvscallable/SingleJustVsFromCallableTest.java
index d0de86fed8..a693432343 100644
--- a/rxjava-modules/rxjava-core-2/src/test/java/com/baeldung/rxjava/justvscallable/SingleJustVsFromCallableTest.java
+++ b/rxjava-modules/rxjava-core-2/src/test/java/com/baeldung/rxjava/justvscallable/SingleJustVsFromCallableTest.java
@@ -12,7 +12,7 @@ import org.mockito.Mockito;
import rx.Single;
import rx.observers.TestSubscriber;
-class SingleJustVsFromCallableTest {
+class SingleJustVsFromCallableUnitTest {
public EmployeeRepository repository = mock(EmployeeRepository.class);
diff --git a/discord4j/.gitignore b/saas-modules/discord4j/.gitignore
similarity index 100%
rename from discord4j/.gitignore
rename to saas-modules/discord4j/.gitignore
diff --git a/discord4j/README.md b/saas-modules/discord4j/README.md
similarity index 100%
rename from discord4j/README.md
rename to saas-modules/discord4j/README.md
diff --git a/discord4j/pom.xml b/saas-modules/discord4j/pom.xml
similarity index 90%
rename from discord4j/pom.xml
rename to saas-modules/discord4j/pom.xml
index 3ea85c05c7..ff398dd1a3 100644
--- a/discord4j/pom.xml
+++ b/saas-modules/discord4j/pom.xml
@@ -3,17 +3,14 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
- com.baeldung
discord4j
- 0.0.1-SNAPSHOT
discord4j
Demo Discord bot using Discord4J + Spring Boot
com.baeldung
- parent-boot-2
- 0.0.1-SNAPSHOT
- ../parent-boot-2
+ saas-modules
+ 1.0.0-SNAPSHOT
diff --git a/discord4j/src/main/java/com/baeldung/discordbot/BotConfiguration.java b/saas-modules/discord4j/src/main/java/com/baeldung/discordbot/BotConfiguration.java
similarity index 100%
rename from discord4j/src/main/java/com/baeldung/discordbot/BotConfiguration.java
rename to saas-modules/discord4j/src/main/java/com/baeldung/discordbot/BotConfiguration.java
diff --git a/discord4j/src/main/java/com/baeldung/discordbot/DiscordBotApplication.java b/saas-modules/discord4j/src/main/java/com/baeldung/discordbot/DiscordBotApplication.java
similarity index 100%
rename from discord4j/src/main/java/com/baeldung/discordbot/DiscordBotApplication.java
rename to saas-modules/discord4j/src/main/java/com/baeldung/discordbot/DiscordBotApplication.java
diff --git a/discord4j/src/main/java/com/baeldung/discordbot/events/EventListener.java b/saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/EventListener.java
similarity index 100%
rename from discord4j/src/main/java/com/baeldung/discordbot/events/EventListener.java
rename to saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/EventListener.java
diff --git a/discord4j/src/main/java/com/baeldung/discordbot/events/MessageCreateListener.java b/saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/MessageCreateListener.java
similarity index 100%
rename from discord4j/src/main/java/com/baeldung/discordbot/events/MessageCreateListener.java
rename to saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/MessageCreateListener.java
diff --git a/discord4j/src/main/java/com/baeldung/discordbot/events/MessageListener.java b/saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/MessageListener.java
similarity index 100%
rename from discord4j/src/main/java/com/baeldung/discordbot/events/MessageListener.java
rename to saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/MessageListener.java
diff --git a/discord4j/src/main/java/com/baeldung/discordbot/events/MessageUpdateListener.java b/saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/MessageUpdateListener.java
similarity index 100%
rename from discord4j/src/main/java/com/baeldung/discordbot/events/MessageUpdateListener.java
rename to saas-modules/discord4j/src/main/java/com/baeldung/discordbot/events/MessageUpdateListener.java
diff --git a/discord4j/src/main/resources/application.yml b/saas-modules/discord4j/src/main/resources/application.yml
similarity index 100%
rename from discord4j/src/main/resources/application.yml
rename to saas-modules/discord4j/src/main/resources/application.yml
diff --git a/discord4j/src/test/java/com/baeldung/discordbot/DiscordBotLiveTest.java b/saas-modules/discord4j/src/test/java/com/baeldung/discordbot/DiscordBotLiveTest.java
similarity index 100%
rename from discord4j/src/test/java/com/baeldung/discordbot/DiscordBotLiveTest.java
rename to saas-modules/discord4j/src/test/java/com/baeldung/discordbot/DiscordBotLiveTest.java
diff --git a/saas-modules/pom.xml b/saas-modules/pom.xml
index 7e8adebdd9..16ed50918c 100644
--- a/saas-modules/pom.xml
+++ b/saas-modules/pom.xml
@@ -16,11 +16,13 @@
+ discord4j
jira-rest-integration
+ sentry-servlet
+ slack
stripe
twilio
twitter4j
- sentry-servlet
diff --git a/saas-modules/sentry-servlet/pom.xml b/saas-modules/sentry-servlet/pom.xml
index c86fcbce03..2e4f95b5fb 100644
--- a/saas-modules/sentry-servlet/pom.xml
+++ b/saas-modules/sentry-servlet/pom.xml
@@ -15,6 +15,7 @@
6.11.0
1.10.4
+ 3.3.2
diff --git a/saas-modules/sentry-servlet/src/main/java/com/baeldung/sentry/support/SentryFilter.java b/saas-modules/sentry-servlet/src/main/java/com/baeldung/sentry/support/SentryFilter.java
index e853368ad9..51055f321d 100644
--- a/saas-modules/sentry-servlet/src/main/java/com/baeldung/sentry/support/SentryFilter.java
+++ b/saas-modules/sentry-servlet/src/main/java/com/baeldung/sentry/support/SentryFilter.java
@@ -21,7 +21,7 @@ public class SentryFilter implements Filter {
try {
chain.doFilter(request, response);
int rc = ((HttpServletResponse) response).getStatus();
- if (rc/100 == 5) {
+ if (rc / 100 == 5) {
Sentry.captureMessage("Application error: code=" + rc, SentryLevel.ERROR);
}
} catch (Throwable t) {
diff --git a/saas-modules/sentry-servlet/src/main/resources/sentry.properties b/saas-modules/sentry-servlet/src/main/resources/sentry.properties
index c937874420..cd8b3005dd 100644
--- a/saas-modules/sentry-servlet/src/main/resources/sentry.properties
+++ b/saas-modules/sentry-servlet/src/main/resources/sentry.properties
@@ -1,3 +1,3 @@
# Sentry configuration file
-# put your DSN here
-dsn=https://xxxxxxxxxxxxxxxx@zzzzzzz.ingest.sentry.io/wwww
\ No newline at end of file
+# put your own DSN here. This one is NOT valid !!!
+dsn=https://c295098aadd04f719f1c9f50d801f93e@o75061.ingest.sentry.io/4504455033978880
\ No newline at end of file
diff --git a/slack/README.md b/saas-modules/slack/README.md
similarity index 100%
rename from slack/README.md
rename to saas-modules/slack/README.md
diff --git a/slack/pom.xml b/saas-modules/slack/pom.xml
similarity index 97%
rename from slack/pom.xml
rename to saas-modules/slack/pom.xml
index 690bf5132c..326167c055 100644
--- a/slack/pom.xml
+++ b/saas-modules/slack/pom.xml
@@ -11,7 +11,7 @@
com.baeldung
- parent-modules
+ saas-modules
1.0.0-SNAPSHOT
diff --git a/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java b/saas-modules/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java
similarity index 100%
rename from slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java
rename to saas-modules/slack/src/main/java/com/baeldung/examples/slack/DiskSpaceErrorChecker.java
diff --git a/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java b/saas-modules/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java
similarity index 100%
rename from slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java
rename to saas-modules/slack/src/main/java/com/baeldung/examples/slack/ErrorChecker.java
diff --git a/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java b/saas-modules/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java
similarity index 100%
rename from slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java
rename to saas-modules/slack/src/main/java/com/baeldung/examples/slack/ErrorReporter.java
diff --git a/slack/src/main/java/com/baeldung/examples/slack/MainClass.java b/saas-modules/slack/src/main/java/com/baeldung/examples/slack/MainClass.java
similarity index 100%
rename from slack/src/main/java/com/baeldung/examples/slack/MainClass.java
rename to saas-modules/slack/src/main/java/com/baeldung/examples/slack/MainClass.java
diff --git a/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java b/saas-modules/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java
similarity index 100%
rename from slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java
rename to saas-modules/slack/src/main/java/com/baeldung/examples/slack/SlackChannelErrorReporter.java
diff --git a/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java b/saas-modules/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java
similarity index 100%
rename from slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java
rename to saas-modules/slack/src/main/java/com/baeldung/examples/slack/SlackUserErrorReporter.java
diff --git a/slack/src/main/resources/logback.xml b/saas-modules/slack/src/main/resources/logback.xml
similarity index 100%
rename from slack/src/main/resources/logback.xml
rename to saas-modules/slack/src/main/resources/logback.xml
diff --git a/security-modules/pom.xml b/security-modules/pom.xml
index 70f29cecd7..d0edced4e0 100644
--- a/security-modules/pom.xml
+++ b/security-modules/pom.xml
@@ -17,7 +17,7 @@
apache-shiro
cas
cloud-foundry-uaa
-
+ java-ee-8-security-api
jee-7-security
jjwt
jwt
@@ -25,4 +25,8 @@
sql-injection-samples
+
+ 3.3.2
+
+
\ No newline at end of file
diff --git a/server-modules/wildfly/pom.xml b/server-modules/wildfly/pom.xml
index eaec4d176c..af742c7bd3 100644
--- a/server-modules/wildfly/pom.xml
+++ b/server-modules/wildfly/pom.xml
@@ -13,7 +13,7 @@
com.baeldung
parent-boot-2
0.0.1-SNAPSHOT
- ../parent-boot-2
+ ../../parent-boot-2
@@ -63,6 +63,7 @@
org.apache.maven.plugins
maven-war-plugin
+ ${maven-war-plugin.version}
@@ -74,4 +75,8 @@
+
+ 3.3.2
+
+
\ No newline at end of file
diff --git a/spf4j/spf4j-aspects-app/pom.xml b/spf4j/spf4j-aspects-app/pom.xml
index 09ca41ea47..3eccdd879a 100644
--- a/spf4j/spf4j-aspects-app/pom.xml
+++ b/spf4j/spf4j-aspects-app/pom.xml
@@ -55,11 +55,6 @@
org.apache.maven.plugins
maven-compiler-plugin
- ${compiler.plugin.version}
-
-
- ${java.version}
-
org.apache.maven.plugins
@@ -98,7 +93,6 @@
8.9.0
- 3.8.0
3.1.1
diff --git a/spf4j/spf4j-core-app/pom.xml b/spf4j/spf4j-core-app/pom.xml
index 2f7f3745f1..20251860aa 100644
--- a/spf4j/spf4j-core-app/pom.xml
+++ b/spf4j/spf4j-core-app/pom.xml
@@ -61,11 +61,6 @@
org.apache.maven.plugins
maven-compiler-plugin
- ${compiler.plugin.version}
-
-
- ${java.version}
-
org.apache.maven.plugins
@@ -104,7 +99,6 @@
8.9.0
- 3.8.0
3.1.1
diff --git a/spring-aop-2/pom.xml b/spring-aop-2/pom.xml
index 76e4780e72..cb84ed4ca2 100644
--- a/spring-aop-2/pom.xml
+++ b/spring-aop-2/pom.xml
@@ -39,8 +39,22 @@
+
+
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+ false
+
+
+
+
+
- 1.11
+ 1.14.0
+ 3.3.2
\ No newline at end of file
diff --git a/spring-aop/pom.xml b/spring-aop/pom.xml
index 0d48c479ca..ae5ab5fce1 100644
--- a/spring-aop/pom.xml
+++ b/spring-aop/pom.xml
@@ -69,11 +69,20 @@
+
+ org.apache.maven.plugins
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+ false
+
+
- 1.11
+ 1.14.0
+ 3.3.2
\ No newline at end of file
diff --git a/spring-batch-2/pom.xml b/spring-batch-2/pom.xml
index 12d31aca14..378191c91c 100644
--- a/spring-batch-2/pom.xml
+++ b/spring-batch-2/pom.xml
@@ -11,9 +11,9 @@
com.baeldung
- parent-boot-2
+ parent-boot-3
0.0.1-SNAPSHOT
- ../parent-boot-2
+ ../parent-boot-3
@@ -51,8 +51,9 @@
- 4.3.0
- 3.1.1
+ 5.0.0
+ 4.2.0
+ com.baeldung.batch.SpringBootBatchProcessingApplication
\ No newline at end of file
diff --git a/spring-batch-2/src/main/java/com/baeldung/batch/BatchConfiguration.java b/spring-batch-2/src/main/java/com/baeldung/batch/BatchConfiguration.java
index 0c053dd86c..770b6330dd 100644
--- a/spring-batch-2/src/main/java/com/baeldung/batch/BatchConfiguration.java
+++ b/spring-batch-2/src/main/java/com/baeldung/batch/BatchConfiguration.java
@@ -4,31 +4,24 @@ import javax.sql.DataSource;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
-import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
-import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
-import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
+import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
+import org.springframework.batch.core.repository.JobRepository;
+import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
-import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
+import org.springframework.transaction.PlatformTransactionManager;
@Configuration
-@EnableBatchProcessing
public class BatchConfiguration {
-
- @Autowired
- public JobBuilderFactory jobBuilderFactory;
-
- @Autowired
- public StepBuilderFactory stepBuilderFactory;
@Value("${file.input}")
private String fileInput;
@@ -59,8 +52,8 @@ public class BatchConfiguration {
}
@Bean
- public Job importUserJob(JobCompletionNotificationListener listener, Step step1) {
- return jobBuilderFactory.get("importUserJob")
+ public Job importUserJob(JobRepository jobRepository, JobCompletionNotificationListener listener, Step step1) {
+ return new JobBuilder("importUserJob", jobRepository)
.incrementer(new RunIdIncrementer())
.listener(listener)
.flow(step1)
@@ -69,9 +62,9 @@ public class BatchConfiguration {
}
@Bean
- public Step step1(JdbcBatchItemWriter writer) {
- return stepBuilderFactory.get("step1")
- . chunk(10)
+ public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager, JdbcBatchItemWriter writer) {
+ return new StepBuilder("step1", jobRepository)
+ . chunk(10, transactionManager)
.reader(reader())
.processor(processor())
.writer(writer)
diff --git a/spring-batch-2/src/main/java/com/baeldung/batch/CoffeeItemProcessor.java b/spring-batch-2/src/main/java/com/baeldung/batch/CoffeeItemProcessor.java
index b154b80453..bd4173e9ed 100644
--- a/spring-batch-2/src/main/java/com/baeldung/batch/CoffeeItemProcessor.java
+++ b/spring-batch-2/src/main/java/com/baeldung/batch/CoffeeItemProcessor.java
@@ -10,7 +10,7 @@ public class CoffeeItemProcessor implements ItemProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(CoffeeItemProcessor.class);
@Override
- public Coffee process(final Coffee coffee) throws Exception {
+ public Coffee process(final Coffee coffee) {
String brand = coffee.getBrand().toUpperCase();
String origin = coffee.getOrigin().toUpperCase();
String chracteristics = coffee.getCharacteristics().toUpperCase();
diff --git a/spring-batch-2/src/main/java/com/baeldung/batch/JobCompletionNotificationListener.java b/spring-batch-2/src/main/java/com/baeldung/batch/JobCompletionNotificationListener.java
index ca1de40aea..b61faeb13b 100644
--- a/spring-batch-2/src/main/java/com/baeldung/batch/JobCompletionNotificationListener.java
+++ b/spring-batch-2/src/main/java/com/baeldung/batch/JobCompletionNotificationListener.java
@@ -4,13 +4,13 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
-import org.springframework.batch.core.listener.JobExecutionListenerSupport;
+import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
-public class JobCompletionNotificationListener extends JobExecutionListenerSupport {
+public class JobCompletionNotificationListener implements JobExecutionListener {
private static final Logger LOGGER = LoggerFactory.getLogger(JobCompletionNotificationListener.class);
diff --git a/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java
index c830a41855..dcb2bc5199 100644
--- a/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java
+++ b/spring-batch-2/src/main/java/com/baeldung/batchscheduler/SpringBatchScheduler.java
@@ -7,15 +7,16 @@ import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.Step;
-import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
-import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
-import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
+import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.launch.JobLauncher;
+import org.springframework.batch.core.repository.JobRepository;
+import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
@@ -24,17 +25,16 @@ import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.ScheduledMethodRunnable;
+import org.springframework.transaction.PlatformTransactionManager;
import java.util.Date;
import java.util.IdentityHashMap;
-import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
@Configuration
-@EnableBatchProcessing
@EnableScheduling
public class SpringBatchScheduler {
@@ -46,21 +46,21 @@ public class SpringBatchScheduler {
private final Map